partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Booster.get_score
Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in. * 'cover': the average coverage across all splits the fea...
python-package/xgboost/core.py
def get_score(self, fmap='', importance_type='weight'): """Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in...
def get_score(self, fmap='', importance_type='weight'): """Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in...
[ "Get", "feature", "importance", "of", "each", "feature", ".", "Importance", "type", "can", "be", "defined", "as", ":" ]
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1477-L1578
[ "def", "get_score", "(", "self", ",", "fmap", "=", "''", ",", "importance_type", "=", "'weight'", ")", ":", "if", "getattr", "(", "self", ",", "'booster'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "booster", "not", "in", "{", "'gbtr...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
Booster.trees_to_dataframe
Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as linear learners (`booster=gblinear`). Param...
python-package/xgboost/core.py
def trees_to_dataframe(self, fmap=''): """Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as li...
def trees_to_dataframe(self, fmap=''): """Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as li...
[ "Parse", "a", "boosted", "tree", "model", "text", "dump", "into", "a", "pandas", "DataFrame", "structure", "." ]
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1580-L1663
[ "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.'", ...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
Booster._validate_features
Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix
python-package/xgboost/core.py
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
[ "Validate", "Booster", "and", "data", "s", "feature_names", "are", "identical", ".", "Set", "feature_names", "and", "feature_types", "from", "DMatrix" ]
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1665-L1690
[ "def", "_validate_features", "(", "self", ",", "data", ")", ":", "if", "self", ".", "feature_names", "is", "None", ":", "self", ".", "feature_names", "=", "data", ".", "feature_names", "self", ".", "feature_types", "=", "data", ".", "feature_types", "else", ...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
Booster.get_split_value_histogram
Get split value histogram of a feature Parameters ---------- feature: str The name of the feature. fmap: str (optional) The name of feature map file. bin: int, default None The maximum number of bins. Number of bins equals number o...
python-package/xgboost/core.py
def get_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): """Get split value histogram of a feature Parameters ---------- feature: str The name of the feature. fmap: str (optional) The name of feature map file. bin: int, de...
def get_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): """Get split value histogram of a feature Parameters ---------- feature: str The name of the feature. fmap: str (optional) The name of feature map file. bin: int, de...
[ "Get", "split", "value", "histogram", "of", "a", "feature" ]
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1692-L1733
[ "def", "get_split_value_histogram", "(", "self", ",", "feature", ",", "fmap", "=", "''", ",", "bins", "=", "None", ",", "as_pandas", "=", "True", ")", ":", "xgdump", "=", "self", ".", "get_dump", "(", "fmap", "=", "fmap", ")", "values", "=", "[", "]"...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
plot_importance
Plot importance based on fitted trees. Parameters ---------- booster : Booster, XGBModel or dict Booster or XGBModel instance, or dict taken by Booster.get_fscore() ax : matplotlib Axes, default None Target axes instance. If None, new figure and axes will be created. grid : bool, Tu...
python-package/xgboost/plotting.py
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, show_values=True, **kwargs): """Plot im...
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, show_values=True, **kwargs): """Plot im...
[ "Plot", "importance", "based", "on", "fitted", "trees", "." ]
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L14-L117
[ "def", "plot_importance", "(", "booster", ",", "ax", "=", "None", ",", "height", "=", "0.2", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "title", "=", "'Feature importance'", ",", "xlabel", "=", "'F score'", ",", "ylabel", "=", "'Features'",...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
_parse_node
parse dumped node
python-package/xgboost/plotting.py
def _parse_node(graph, text, condition_node_params, leaf_node_params): """parse dumped node""" 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 = _LEAFPAT.match(text) if ...
def _parse_node(graph, text, condition_node_params, leaf_node_params): """parse dumped node""" 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 = _LEAFPAT.match(text) if ...
[ "parse", "dumped", "node" ]
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L126-L138
[ "def", "_parse_node", "(", "graph", ",", "text", ",", "condition_node_params", ",", "leaf_node_params", ")", ":", "match", "=", "_NODEPAT", ".", "match", "(", "text", ")", "if", "match", "is", "not", "None", ":", "node", "=", "match", ".", "group", "(", ...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
_parse_edge
parse dumped edge
python-package/xgboost/plotting.py
def _parse_edge(graph, node, text, yes_color='#0000FF', no_color='#FF0000'): """parse dumped edge""" try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, label='yes, missing', co...
def _parse_edge(graph, node, text, yes_color='#0000FF', no_color='#FF0000'): """parse dumped edge""" try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, label='yes, missing', co...
[ "parse", "dumped", "edge" ]
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L141-L162
[ "def", "_parse_edge", "(", "graph", ",", "node", ",", "text", ",", "yes_color", "=", "'#0000FF'", ",", "no_color", "=", "'#FF0000'", ")", ":", "try", ":", "match", "=", "_EDGEPAT", ".", "match", "(", "text", ")", "if", "match", "is", "not", "None", "...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
to_graphviz
Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherwise, you should call .render() method of the returned graphiz instance. Parameters ---------- booster : Booster, XGBModel Booster or XGBModel instance fmap: str (optional) ...
python-package/xgboost/plotting.py
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): """Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherw...
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): """Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherw...
[ "Convert", "specified", "tree", "to", "graphviz", "instance", ".", "IPython", "can", "automatically", "plot", "the", "returned", "graphiz", "instance", ".", "Otherwise", "you", "should", "call", ".", "render", "()", "method", "of", "the", "returned", "graphiz", ...
dmlc/xgboost
python
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L165-L241
[ "def", "to_graphviz", "(", "booster", ",", "fmap", "=", "''", ",", "num_trees", "=", "0", ",", "rankdir", "=", "'UT'", ",", "yes_color", "=", "'#0000FF'", ",", "no_color", "=", "'#FF0000'", ",", "condition_node_params", "=", "None", ",", "leaf_node_params", ...
253fdd8a42d5ec6b819788199584d27bf9ea6253
train
newAction
Create a new action and assign callbacks, shortcuts, etc.
libs/utils.py
def newAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True): """Create a new action and assign callbacks, shortcuts, etc.""" a = QAction(text, parent) if icon is not None: a.setIcon(newIcon(icon)) if shortcut is not None: if isi...
def newAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True): """Create a new action and assign callbacks, shortcuts, etc.""" a = QAction(text, parent) if icon is not None: a.setIcon(newIcon(icon)) if shortcut is not None: if isi...
[ "Create", "a", "new", "action", "and", "assign", "callbacks", "shortcuts", "etc", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/utils.py#L29-L48
[ "def", "newAction", "(", "parent", ",", "text", ",", "slot", "=", "None", ",", "shortcut", "=", "None", ",", "icon", "=", "None", ",", "tip", "=", "None", ",", "checkable", "=", "False", ",", "enabled", "=", "True", ")", ":", "a", "=", "QAction", ...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
natural_sort
Sort the list into natural alphanumeric order.
libs/utils.py
def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """ 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_...
def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """ 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_...
[ "Sort", "the", "list", "into", "natural", "alphanumeric", "order", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/utils.py#L95-L103
[ "def", "natural_sort", "(", "list", ",", "key", "=", "lambda", "s", ":", "s", ")", ":", "def", "get_alphanum_key_func", "(", "key", ")", ":", "convert", "=", "lambda", "text", ":", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "e...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
Canvas.mouseMoveEvent
Update line with last point and current coordinates.
libs/canvas.py
def mouseMoveEvent(self, ev): """Update line with last point and current coordinates.""" 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().lab...
def mouseMoveEvent(self, ev): """Update line with last point and current coordinates.""" 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().lab...
[ "Update", "line", "with", "last", "point", "and", "current", "coordinates", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L104-L208
[ "def", "mouseMoveEvent", "(", "self", ",", "ev", ")", ":", "pos", "=", "self", ".", "transformPos", "(", "ev", ".", "pos", "(", ")", ")", "# Update coordinates in status bar if image is opened", "window", "=", "self", ".", "parent", "(", ")", ".", "window", ...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
Canvas.selectShapePoint
Select the first shape created which contains this point.
libs/canvas.py
def selectShapePoint(self, point): """Select the first shape created which contains this point.""" self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape shape.highlightVertex(index, shape.MOVE_VERTEX) ...
def selectShapePoint(self, point): """Select the first shape created which contains this point.""" self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape shape.highlightVertex(index, shape.MOVE_VERTEX) ...
[ "Select", "the", "first", "shape", "created", "which", "contains", "this", "point", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L307-L319
[ "def", "selectShapePoint", "(", "self", ",", "point", ")", ":", "self", ".", "deSelectShape", "(", ")", "if", "self", ".", "selectedVertex", "(", ")", ":", "# A vertex is marked for selection.", "index", ",", "shape", "=", "self", ".", "hVertex", ",", "self"...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
Canvas.snapPointToCanvas
Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x or y were changed, False if not.
libs/canvas.py
def snapPointToCanvas(self, x, y): """ Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x or y were changed, False if not. """ if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height(): x = max(x,...
def snapPointToCanvas(self, x, y): """ Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x or y were changed, False if not. """ if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height(): x = max(x,...
[ "Moves", "a", "point", "x", "y", "to", "within", "the", "boundaries", "of", "the", "canvas", ".", ":", "return", ":", "(", "x", "y", "snapped", ")", "where", "snapped", "is", "True", "if", "x", "or", "y", "were", "changed", "False", "if", "not", "....
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L329-L341
[ "def", "snapPointToCanvas", "(", "self", ",", "x", ",", "y", ")", ":", "if", "x", "<", "0", "or", "x", ">", "self", ".", "pixmap", ".", "width", "(", ")", "or", "y", "<", "0", "or", "y", ">", "self", ".", "pixmap", ".", "height", "(", ")", ...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
Canvas.intersectingEdges
For each edge formed by `points', yield the intersection with the line segment `(x1,y1) - (x2,y2)`, if it exists. Also return the distance of `(x2,y2)' to the middle of the edge along with its index, so that the one closest can be chosen.
libs/canvas.py
def intersectingEdges(self, x1y1, x2y2, points): """For each edge formed by `points', yield the intersection with the line segment `(x1,y1) - (x2,y2)`, if it exists. Also return the distance of `(x2,y2)' to the middle of the edge along with its index, so that the one closest can be chose...
def intersectingEdges(self, x1y1, x2y2, points): """For each edge formed by `points', yield the intersection with the line segment `(x1,y1) - (x2,y2)`, if it exists. Also return the distance of `(x2,y2)' to the middle of the edge along with its index, so that the one closest can be chose...
[ "For", "each", "edge", "formed", "by", "points", "yield", "the", "intersection", "with", "the", "line", "segment", "(", "x1", "y1", ")", "-", "(", "x2", "y2", ")", "if", "it", "exists", ".", "Also", "return", "the", "distance", "of", "(", "x2", "y2",...
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L551-L575
[ "def", "intersectingEdges", "(", "self", ",", "x1y1", ",", "x2y2", ",", "points", ")", ":", "x1", ",", "y1", "=", "x1y1", "x2", ",", "y2", "=", "x2y2", "for", "i", "in", "range", "(", "4", ")", ":", "x3", ",", "y3", "=", "points", "[", "i", "...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
get_main_app
Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread
labelImg.py
def get_main_app(argv=[]): """ Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread """ app = QApplication(argv) app.setApplicationName(__appname__) app.setWindowIcon(newIcon("app")) # Tzutalin 201705+: Accept extra ...
def get_main_app(argv=[]): """ Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread """ app = QApplication(argv) app.setApplicationName(__appname__) app.setWindowIcon(newIcon("app")) # Tzutalin 201705+: Accept extra ...
[ "Standard", "boilerplate", "Qt", "application", "code", ".", "Do", "everything", "but", "app", ".", "exec_", "()", "--", "so", "that", "we", "can", "test", "the", "application", "in", "one", "thread" ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L1450-L1466
[ "def", "get_main_app", "(", "argv", "=", "[", "]", ")", ":", "app", "=", "QApplication", "(", "argv", ")", "app", ".", "setApplicationName", "(", "__appname__", ")", "app", ".", "setWindowIcon", "(", "newIcon", "(", "\"app\"", ")", ")", "# Tzutalin 201705+...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
MainWindow.toggleActions
Enable/Disable widgets which depend on an opened image.
labelImg.py
def toggleActions(self, value=True): """Enable/Disable widgets which depend on an opened image.""" for z in self.actions.zoomActions: z.setEnabled(value) for action in self.actions.onLoadActive: action.setEnabled(value)
def toggleActions(self, value=True): """Enable/Disable widgets which depend on an opened image.""" 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", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L556-L561
[ "def", "toggleActions", "(", "self", ",", "value", "=", "True", ")", ":", "for", "z", "in", "self", ".", "actions", ".", "zoomActions", ":", "z", ".", "setEnabled", "(", "value", ")", "for", "action", "in", "self", ".", "actions", ".", "onLoadActive", ...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
MainWindow.toggleDrawingSensitive
In the middle of drawing, toggling between modes should be disabled.
labelImg.py
def toggleDrawingSensitive(self, drawing=True): """In the middle of drawing, toggling between modes should be disabled.""" self.actions.editMode.setEnabled(not drawing) if not drawing and self.beginner(): # Cancel creation. print('Cancel creation.') self.canva...
def toggleDrawingSensitive(self, drawing=True): """In the middle of drawing, toggling between modes should be disabled.""" self.actions.editMode.setEnabled(not drawing) if not drawing and self.beginner(): # Cancel creation. print('Cancel creation.') self.canva...
[ "In", "the", "middle", "of", "drawing", "toggling", "between", "modes", "should", "be", "disabled", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L621-L629
[ "def", "toggleDrawingSensitive", "(", "self", ",", "drawing", "=", "True", ")", ":", "self", ".", "actions", ".", "editMode", ".", "setEnabled", "(", "not", "drawing", ")", "if", "not", "drawing", "and", "self", ".", "beginner", "(", ")", ":", "# Cancel ...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
MainWindow.btnstate
Function to handle difficult examples Update on each object
labelImg.py
def btnstate(self, item= None): """ Function to handle difficult examples Update on each object """ 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.labe...
def btnstate(self, item= None): """ Function to handle difficult examples Update on each object """ 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.labe...
[ "Function", "to", "handle", "difficult", "examples", "Update", "on", "each", "object" ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L685-L709
[ "def", "btnstate", "(", "self", ",", "item", "=", "None", ")", ":", "if", "not", "self", ".", "canvas", ".", "editing", "(", ")", ":", "return", "item", "=", "self", ".", "currentItem", "(", ")", "if", "not", "item", ":", "# If not selected Item, take ...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
MainWindow.newShape
Pop-up and give focus to the label editor. position MUST be in global coordinates.
labelImg.py
def newShape(self): """Pop-up and give focus to the label editor. position MUST be in global coordinates. """ if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.text(): if len(self.labelHist) > 0: self.labelDialog = LabelDialog( ...
def newShape(self): """Pop-up and give focus to the label editor. position MUST be in global coordinates. """ if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.text(): if len(self.labelHist) > 0: self.labelDialog = LabelDialog( ...
[ "Pop", "-", "up", "and", "give", "focus", "to", "the", "label", "editor", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L839-L876
[ "def", "newShape", "(", "self", ")", ":", "if", "not", "self", ".", "useDefaultLabelCheckbox", ".", "isChecked", "(", ")", "or", "not", "self", ".", "defaultLabelTextLine", ".", "text", "(", ")", ":", "if", "len", "(", "self", ".", "labelHist", ")", ">...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
MainWindow.loadFile
Load the specified file, or the last opened file if None.
labelImg.py
def loadFile(self, filePath=None): """Load the specified file, or the last opened file if 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...
def loadFile(self, filePath=None): """Load the specified file, or the last opened file if 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...
[ "Load", "the", "specified", "file", "or", "the", "last", "opened", "file", "if", "None", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L960-L1051
[ "def", "loadFile", "(", "self", ",", "filePath", "=", "None", ")", ":", "self", ".", "resetState", "(", ")", "self", ".", "canvas", ".", "setEnabled", "(", "False", ")", "if", "filePath", "is", "None", ":", "filePath", "=", "self", ".", "settings", "...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
MainWindow.scaleFitWindow
Figure out the size of the pixmap in order to fit the main widget.
labelImg.py
def scaleFitWindow(self): """Figure out the size of the pixmap in order to fit the main widget.""" 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...
def scaleFitWindow(self): """Figure out the size of the pixmap in order to fit the main widget.""" 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...
[ "Figure", "out", "the", "size", "of", "the", "pixmap", "in", "order", "to", "fit", "the", "main", "widget", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L1069-L1079
[ "def", "scaleFitWindow", "(", "self", ")", ":", "e", "=", "2.0", "# So that no scrollbars are generated.", "w1", "=", "self", ".", "centralWidget", "(", ")", ".", "width", "(", ")", "-", "e", "h1", "=", "self", ".", "centralWidget", "(", ")", ".", "heigh...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
ustr
py2/py3 unicode helper
libs/ustr.py
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/article/details/51088476 #https://b...
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/article/details/51088476 #https://b...
[ "py2", "/", "py3", "unicode", "helper" ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/ustr.py#L4-L17
[ "def", "ustr", "(", "x", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ",", "0", ")", ":", "from", "PyQt4", ".", "QtCore", "import", "QString", "if", "type", "(", "x", ")", "==", "str", ":", "return", "x", ".", "decode", ...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
PascalVocWriter.prettify
Return a pretty-printed XML string for the Element.
libs/pascal_voc_io.py
def prettify(self, elem): """ Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf8') root = etree.fromstring(rough_string) return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace(" ".encode(), ...
def prettify(self, elem): """ Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf8') root = etree.fromstring(rough_string) return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace(" ".encode(), ...
[ "Return", "a", "pretty", "-", "printed", "XML", "string", "for", "the", "Element", "." ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/pascal_voc_io.py#L26-L35
[ "def", "prettify", "(", "self", ",", "elem", ")", ":", "rough_string", "=", "ElementTree", ".", "tostring", "(", "elem", ",", "'utf8'", ")", "root", "=", "etree", ".", "fromstring", "(", "rough_string", ")", "return", "etree", ".", "tostring", "(", "root...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
PascalVocWriter.genXML
Return XML root
libs/pascal_voc_io.py
def genXML(self): """ Return XML root """ # 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: top...
def genXML(self): """ Return XML root """ # 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: top...
[ "Return", "XML", "root" ]
tzutalin/labelImg
python
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/pascal_voc_io.py#L37-L78
[ "def", "genXML", "(", "self", ")", ":", "# Check conditions", "if", "self", ".", "filename", "is", "None", "or", "self", ".", "foldername", "is", "None", "or", "self", ".", "imgSize", "is", "None", ":", "return", "None", "top", "=", "Element", "(", "'a...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
train
Exchange.fetch
Perform a HTTP request and return decoded JSON data
python/ccxt/async_support/base/exchange.py
async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) ...
async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) ...
[ "Perform", "a", "HTTP", "request", "and", "return", "decoded", "JSON", "data" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/async_support/base/exchange.py#L117-L168
[ "async", "def", "fetch", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "request_headers", "=", "self", ".", "prepare_request_headers", "(", "headers", ")", "url", "=", "self", "."...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.fetch2
A better wrapper over request for deferred signing
python/ccxt/base/exchange.py
def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method,...
def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method,...
[ "A", "better", "wrapper", "over", "request", "for", "deferred", "signing" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L423-L429
[ "def", "fetch2", "(", "self", ",", "path", ",", "api", "=", "'public'", ",", "method", "=", "'GET'", ",", "params", "=", "{", "}", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "if", "self", ".", "enableRateLimit", ":", "self", ...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.request
Exchange.request is the entry point for all generated methods
python/ccxt/base/exchange.py
def request(self, path, api='public', method='GET', params={}, headers=None, body=None): """Exchange.request is the entry point for all generated methods""" return self.fetch2(path, api, method, params, headers, body)
def request(self, path, api='public', method='GET', params={}, headers=None, body=None): """Exchange.request is the entry point for all generated methods""" return self.fetch2(path, api, method, params, headers, body)
[ "Exchange", ".", "request", "is", "the", "entry", "point", "for", "all", "generated", "methods" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L431-L433
[ "def", "request", "(", "self", ",", "path", ",", "api", "=", "'public'", ",", "method", "=", "'GET'", ",", "params", "=", "{", "}", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "return", "self", ".", "fetch2", "(", "path", ","...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.find_broadly_matched_key
A helper method for matching error strings exactly vs broadly
python/ccxt/base/exchange.py
def find_broadly_matched_key(self, broad, string): """A helper method for matching error strings exactly vs broadly""" keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string.find(key) >= 0: return key return None
def find_broadly_matched_key(self, broad, string): """A helper method for matching error strings exactly vs broadly""" 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" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L445-L452
[ "def", "find_broadly_matched_key", "(", "self", ",", "broad", ",", "string", ")", ":", "keys", "=", "list", "(", "broad", ".", "keys", "(", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "keys", ")", ")", ":", "key", "=", "keys",...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.fetch
Perform a HTTP request and return decoded JSON data
python/ccxt/base/exchange.py
def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, request_headers, body) ...
def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, request_headers, body) ...
[ "Perform", "a", "HTTP", "request", "and", "return", "decoded", "JSON", "data" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L470-L536
[ "def", "fetch", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "request_headers", "=", "self", ".", "prepare_request_headers", "(", "headers", ")", "url", "=", "self", ".", "proxy"...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.safe_either
A helper-wrapper for the safe_value_2() family.
python/ccxt/base/exchange.py
def safe_either(method, dictionary, key1, key2, default_value=None): """A helper-wrapper for the safe_value_2() family.""" value = method(dictionary, key1) return value if value is not None else method(dictionary, key2, default_value)
def safe_either(method, dictionary, key1, key2, default_value=None): """A helper-wrapper for the safe_value_2() family.""" 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", "." ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L616-L619
[ "def", "safe_either", "(", "method", ",", "dictionary", ",", "key1", ",", "key2", ",", "default_value", "=", "None", ")", ":", "value", "=", "method", "(", "dictionary", ",", "key1", ")", "return", "value", "if", "value", "is", "not", "None", "else", "...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.truncate
Deprecated, use decimal_to_precision instead
python/ccxt/base/exchange.py
def truncate(num, precision=0): """Deprecated, use decimal_to_precision instead""" 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))
def truncate(num, precision=0): """Deprecated, use decimal_to_precision instead""" 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" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L622-L627
[ "def", "truncate", "(", "num", ",", "precision", "=", "0", ")", ":", "if", "precision", ">", "0", ":", "decimal_precision", "=", "math", ".", "pow", "(", "10", ",", "precision", ")", "return", "math", ".", "trunc", "(", "num", "*", "decimal_precision",...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.truncate_to_string
Deprecated, todo: remove references from subclasses
python/ccxt/base/exchange.py
def truncate_to_string(num, precision=0): """Deprecated, todo: remove references from subclasses""" if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip('0') decimal_digits = decimal_digits if ...
def truncate_to_string(num, precision=0): """Deprecated, todo: remove references from subclasses""" if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip('0') decimal_digits = decimal_digits if ...
[ "Deprecated", "todo", ":", "remove", "references", "from", "subclasses" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L630-L637
[ "def", "truncate_to_string", "(", "num", ",", "precision", "=", "0", ")", ":", "if", "precision", ">", "0", ":", "parts", "=", "(", "'{0:.%df}'", "%", "precision", ")", ".", "format", "(", "Decimal", "(", "num", ")", ")", ".", "split", "(", "'.'", ...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
Exchange.check_address
Checks an address is not the same character repeated or an empty sequence
python/ccxt/base/exchange.py
def check_address(self, address): """Checks an address is not the same character repeated or an empty sequence""" 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.minFundingAddres...
def check_address(self, address): """Checks an address is not the same character repeated or an empty sequence""" 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.minFundingAddres...
[ "Checks", "an", "address", "is", "not", "the", "same", "character", "repeated", "or", "an", "empty", "sequence" ]
ccxt/ccxt
python
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L1000-L1006
[ "def", "check_address", "(", "self", ",", "address", ")", ":", "if", "address", "is", "None", ":", "self", ".", "raise_error", "(", "InvalidAddress", ",", "details", "=", "'address is None'", ")", "if", "all", "(", "letter", "==", "address", "[", "0", "]...
23062efd7a5892c79b370c9d951c03cf8c0ddf23
train
reduce_filename
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
bin/benchmark_plotter.py
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('.') return keep_only_digits(f[-3])
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('.') return keep_only_digits(f[-3])
[ "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",...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_plotter.py#L30-L38
[ "def", "reduce_filename", "(", "f", ")", ":", "f", "=", "os", ".", "path", ".", "basename", "(", "f", ")", ".", "split", "(", "'.'", ")", "return", "keep_only_digits", "(", "f", "[", "-", "3", "]", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
keep_only_digits
r''' local helper to just keep digits
util/benchmark.py
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)
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)
[ "r", "local", "helper", "to", "just", "keep", "digits" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/benchmark.py#L6-L15
[ "def", "keep_only_digits", "(", "s", ")", ":", "fs", "=", "''", "for", "c", "in", "s", ":", "if", "c", ".", "isdigit", "(", ")", ":", "fs", "+=", "c", "return", "int", "(", "fs", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
parse_stm_file
r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`.
util/stm.py
def parse_stm_file(stm_file): r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. """ 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_...
def parse_stm_file(stm_file): r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. """ 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_...
[ "r", "Parses", "an", "STM", "file", "at", "stm_file", "into", "a", "list", "of", ":", "class", ":", "STMSegment", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/stm.py#L54-L64
[ "def", "parse_stm_file", "(", "stm_file", ")", ":", "stm_segments", "=", "[", "]", "with", "codecs", ".", "open", "(", "stm_file", ",", "encoding", "=", "\"utf-8\"", ")", "as", "stm_lines", ":", "for", "stm_line", "in", "stm_lines", ":", "stmSegment", "=",...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
read_wave
Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate).
examples/vad_transcriber/wavSplit.py
def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width ...
def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width ...
[ "Reads", "a", ".", "wav", "file", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L6-L21
[ "def", "read_wave", "(", "path", ")", ":", "with", "contextlib", ".", "closing", "(", "wave", ".", "open", "(", "path", ",", "'rb'", ")", ")", "as", "wf", ":", "num_channels", "=", "wf", ".", "getnchannels", "(", ")", "assert", "num_channels", "==", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
write_wave
Writes a .wav file. Takes path, PCM audio data, and sample rate.
examples/vad_transcriber/wavSplit.py
def write_wave(path, audio, sample_rate): """Writes a .wav file. Takes path, PCM audio data, and sample rate. """ with contextlib.closing(wave.open(path, 'wb')) as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(sample_rate) wf.writeframes(audio)
def write_wave(path, audio, sample_rate): """Writes a .wav file. Takes path, PCM audio data, and 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", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L24-L33
[ "def", "write_wave", "(", "path", ",", "audio", ",", "sample_rate", ")", ":", "with", "contextlib", ".", "closing", "(", "wave", ".", "open", "(", "path", ",", "'wb'", ")", ")", "as", "wf", ":", "wf", ".", "setnchannels", "(", "1", ")", "wf", ".", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
frame_generator
Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration.
examples/vad_transcriber/wavSplit.py
def frame_generator(frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) ...
def frame_generator(frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) ...
[ "Generates", "audio", "frames", "from", "PCM", "audio", "data", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L44-L59
[ "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", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
Worker.run
Initialise the runner function with the passed args, kwargs
examples/vad_transcriber/audioTranscript_gui.py
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: traceback.print_exc() ex...
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: traceback.print_exc() ex...
[ "Initialise", "the", "runner", "function", "with", "the", "passed", "args", "kwargs" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/audioTranscript_gui.py#L71-L88
[ "def", "run", "(", "self", ")", ":", "# Retrieve args/kwargs here; and fire up the processing using them", "try", ":", "transcript", "=", "self", ".", "fn", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "except", ":", "traceback", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
exec_command
r''' Helper to exec locally (subprocess) or remotely (paramiko)
bin/benchmark_nc.py
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', '')} p = subprocess.Popen(command, stdo...
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', '')} p = subprocess.Popen(command, stdo...
[ "r", "Helper", "to", "exec", "locally", "(", "subprocess", ")", "or", "remotely", "(", "paramiko", ")" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L41-L61
[ "def", "exec_command", "(", "command", ",", "cwd", "=", "None", ")", ":", "rc", "=", "None", "stdout", "=", "stderr", "=", "None", "if", "ssh_conn", "is", "None", ":", "ld_library_path", "=", "{", "'LD_LIBRARY_PATH'", ":", "'.:%s'", "%", "os", ".", "en...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
get_arch_string
r''' Check local or remote system arch, to produce TaskCluster proper link.
bin/benchmark_nc.py
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 not 'linux' in stdout: raise Assertio...
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 not 'linux' in stdout: raise Assertio...
[ "r", "Check", "local", "or", "remote", "system", "arch", "to", "produce", "TaskCluster", "proper", "link", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L68-L91
[ "def", "get_arch_string", "(", ")", ":", "rc", ",", "stdout", ",", "stderr", "=", "exec_command", "(", "'uname -sm'", ")", "if", "rc", ">", "0", ":", "raise", "AssertionError", "(", "'Error checking OS'", ")", "stdout", "=", "stdout", ".", "lower", "(", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
extract_native_client_tarball
r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir.
bin/benchmark_nc.py
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.stat(target_tarball).st_size == 0: retu...
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.stat(target_tarball).st_size == 0: retu...
[ "r", "Download", "a", "native_client", ".", "tar", ".", "xz", "file", "from", "TaskCluster", "and", "extract", "it", "to", "dir", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L97-L110
[ "def", "extract_native_client_tarball", "(", "dir", ")", ":", "assert_valid_dir", "(", "dir", ")", "target_tarball", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "'native_client.tar.xz'", ")", "if", "os", ".", "path", ".", "isfile", "(", "target_tar...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
is_zip_file
r''' Ensure that a path is a zip file by: - checking length is 1 - checking extension is '.zip'
bin/benchmark_nc.py
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')
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')
[ "r", "Ensure", "that", "a", "path", "is", "a", "zip", "file", "by", ":", "-", "checking", "length", "is", "1", "-", "checking", "extension", "is", ".", "zip" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L112-L119
[ "def", "is_zip_file", "(", "models", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "models", "[", "0", "]", ")", "[", "1", "]", "return", "(", "len", "(", "models", ")", "==", "1", ")", "and", "(", "ext", "==", "'.zip'", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
maybe_inspect_zip
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.
bin/benchmark_nc.py
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 if len(models) > 1: return models ...
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 if len(models) > 1: return 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", "."...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L121-L137
[ "def", "maybe_inspect_zip", "(", "models", ")", ":", "if", "not", "(", "is_zip_file", "(", "models", ")", ")", ":", "return", "models", "if", "len", "(", "models", ")", ">", "1", ":", "return", "models", "if", "len", "(", "models", ")", "<", "1", "...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
all_files
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, test.weights.e5.lstm1200.ldc93s1.pb test.weights.e5.lstm1000....
bin/benchmark_nc.py
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, test.weights.e5.lstm1200.ldc93s1.pb ...
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, test.weights.e5.lstm1200.ldc93s1.pb ...
[ "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", ")", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L139-L186
[ "def", "all_files", "(", "models", "=", "[", "]", ")", ":", "def", "nsort", "(", "a", ",", "b", ")", ":", "fa", "=", "os", ".", "path", ".", "basename", "(", "a", ")", ".", "split", "(", "'.'", ")", "fb", "=", "os", ".", "path", ".", "basen...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
setup_tempdir
r''' Copy models, libs and binary to a directory (new one if dir is None)
bin/benchmark_nc.py
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=models) if binaries is None: maybe_do...
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=models) if binaries is None: maybe_do...
[ "r", "Copy", "models", "libs", "and", "binary", "to", "a", "directory", "(", "new", "one", "if", "dir", "is", "None", ")" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L241-L278
[ "def", "setup_tempdir", "(", "dir", ",", "models", ",", "wav", ",", "alphabet", ",", "lm_binary", ",", "trie", ",", "binaries", ")", ":", "if", "dir", "is", "None", ":", "dir", "=", "tempfile", ".", "mkdtemp", "(", "suffix", "=", "'dsbench'", ")", "s...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
teardown_tempdir
r''' Cleanup temporary directory.
bin/benchmark_nc.py
def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
[ "r", "Cleanup", "temporary", "directory", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L280-L289
[ "def", "teardown_tempdir", "(", "dir", ")", ":", "if", "ssh_conn", ":", "delete_tree", "(", "dir", ")", "assert_valid_dir", "(", "dir", ")", "shutil", ".", "rmtree", "(", "dir", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
get_sshconfig
r''' Read user's SSH configuration file
bin/benchmark_nc.py
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) # Avoid buggy behavior with strange h...
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) # Avoid buggy behavior with strange h...
[ "r", "Read", "user", "s", "SSH", "configuration", "file" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L291-L308
[ "def", "get_sshconfig", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "'~/.ssh/config'", ")", ")", "as", "f", ":", "cfg", "=", "paramiko", ".", "SSHConfig", "(", ")", "cfg", ".", "parse", "(", "f", ")", "ret_dict", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
establish_ssh
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, will use SSH agent and will try to load keys.
bin/benchmark_nc.py
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, will use SSH agent and will try to load keys. ...
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, will use SSH agent and will try to load keys. ...
[ "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", "...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L310-L375
[ "def", "establish_ssh", "(", "target", "=", "None", ",", "auto_trust", "=", "False", ",", "allow_agent", "=", "True", ",", "look_keys", "=", "True", ")", ":", "def", "password_prompt", "(", "username", ",", "hostname", ")", ":", "r'''\n If the Host is r...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
run_benchmarks
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.
bin/benchmark_nc.py
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) inference_times = [ ] for model in mode...
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) inference_times = [ ] for model in mode...
[ "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", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L377-L422
[ "def", "run_benchmarks", "(", "dir", ",", "models", ",", "wav", ",", "alphabet", ",", "lm_binary", "=", "None", ",", "trie", "=", "None", ",", "iters", "=", "-", "1", ")", ":", "assert_valid_dir", "(", "dir", ")", "inference_times", "=", "[", "]", "f...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
produce_csv
r''' Take an input dictionnary and write it to the object-file output.
bin/benchmark_nc.py
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_data['stddev'])) output.flush() outp...
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_data['stddev'])) output.flush() outp...
[ "r", "Take", "an", "input", "dictionnary", "and", "write", "it", "to", "the", "object", "-", "file", "output", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L424-L433
[ "def", "produce_csv", "(", "input", ",", "output", ")", ":", "output", ".", "write", "(", "'\"model\",\"mean\",\"std\"\\n'", ")", "for", "model_data", "in", "input", ":", "output", ".", "write", "(", "'\"%s\",%f,%f\\n'", "%", "(", "model_data", "[", "'name'", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
to_sparse_tuple
r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape)
util/feeding.py
def to_sparse_tuple(sequence): r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape) """ indices = np.asarray(list(zip([0]*len(sequence), range(len(sequence)))), dtype=np.int64) shape = np.asarray([1, len(sequence)], dtype=np.int64) return indice...
def to_sparse_tuple(sequence): r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape) """ indices = np.asarray(list(zip([0]*len(sequence), range(len(sequence)))), dtype=np.int64) shape = np.asarray([1, len(sequence)], dtype=np.int64) return indice...
[ "r", "Creates", "a", "sparse", "representention", "of", "sequence", ".", "Returns", "a", "tuple", "with", "(", "indices", "values", "shape", ")" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/feeding.py#L57-L63
[ "def", "to_sparse_tuple", "(", "sequence", ")", ":", "indices", "=", "np", ".", "asarray", "(", "list", "(", "zip", "(", "[", "0", "]", "*", "len", "(", "sequence", ")", ",", "range", "(", "len", "(", "sequence", ")", ")", ")", ")", ",", "dtype",...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
_parallel_downloader
Generate a function to download a file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param voxforge_url: the base voxforge URL :param archive_dir: the location to store the downloaded file :param total: the ...
bin/import_voxforge.py
def _parallel_downloader(voxforge_url, archive_dir, total, counter): """Generate a function to download a file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param voxforge_url: the base voxforge URL :param archive_d...
def _parallel_downloader(voxforge_url, archive_dir, total, counter): """Generate a function to download a file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param voxforge_url: the base voxforge URL :param archive_d...
[ "Generate", "a", "function", "to", "download", "a", "file", "based", "on", "given", "parameters", "This", "works", "by", "currying", "the", "above", "given", "arguments", "into", "a", "closure", "in", "the", "form", "of", "the", "following", "function", "." ...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L50-L72
[ "def", "_parallel_downloader", "(", "voxforge_url", ",", "archive_dir", ",", "total", ",", "counter", ")", ":", "def", "download", "(", "d", ")", ":", "\"\"\"Binds voxforge_url, archive_dir, total, and counter into this scope\n Downloads the given file\n :param d: a...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
_parallel_extracter
Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to extract into :param number_of_test: the number of files to keep as the test set :...
bin/import_voxforge.py
def _parallel_extracter(data_dir, number_of_test, number_of_dev, total, counter): """Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to ...
def _parallel_extracter(data_dir, number_of_test, number_of_dev, total, counter): """Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to ...
[ "Generate", "a", "function", "to", "extract", "a", "tar", "file", "based", "on", "given", "parameters", "This", "works", "by", "currying", "the", "above", "given", "arguments", "into", "a", "closure", "in", "the", "form", "of", "the", "following", "function"...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L74-L105
[ "def", "_parallel_extracter", "(", "data_dir", ",", "number_of_test", ",", "number_of_dev", ",", "total", ",", "counter", ")", ":", "def", "extract", "(", "d", ")", ":", "\"\"\"Binds data_dir, number_of_test, number_of_dev, total, and counter into this scope\n Extracts...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
AtomicCounter.increment
Increments the counter by the given amount :param amount: the amount to increment by (default 1) :return: the incremented value of the counter
bin/import_voxforge.py
def increment(self, amount=1): """Increments the counter by the given amount :param amount: the amount to increment by (default 1) :return: the incremented value of the counter """ self.__lock.acquire() self.__count += amount v = self.value() self.__...
def increment(self, amount=1): """Increments the counter by the given amount :param amount: the amount to increment by (default 1) :return: the incremented value of the counter """ self.__lock.acquire() self.__count += amount v = self.value() self.__...
[ "Increments", "the", "counter", "by", "the", "given", "amount", ":", "param", "amount", ":", "the", "amount", "to", "increment", "by", "(", "default", "1", ")", ":", "return", ":", "the", "incremented", "value", "of", "the", "counter" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L35-L44
[ "def", "increment", "(", "self", ",", "amount", "=", "1", ")", ":", "self", ".", "__lock", ".", "acquire", "(", ")", "self", ".", "__count", "+=", "amount", "v", "=", "self", ".", "value", "(", ")", "self", ".", "__lock", ".", "release", "(", ")"...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
calculate_report
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 with WER!=0 and ordered by their WER).
util/evaluate_tools.py
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 with WER!=0 and ordered by their WER). '...
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 with WER!=0 and ordered by their WER). '...
[ "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", "res...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/evaluate_tools.py#L30-L47
[ "def", "calculate_report", "(", "labels", ",", "decodings", ",", "distances", ",", "losses", ")", ":", "samples", "=", "pmap", "(", "process_decode_result", ",", "zip", "(", "labels", ",", "decodings", ",", "distances", ",", "losses", ")", ")", "# Getting th...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
sparse_tensor_value_to_texts
r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values, converting tokens to strings using ``alphabet``.
evaluate.py
def sparse_tensor_value_to_texts(value, alphabet): r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values, converting tokens to strings using ``alphabet``. """ return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)
def sparse_tensor_value_to_texts(value, alphabet): r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values, converting tokens to strings using ``alphabet``. """ return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)
[ "r", "Given", "a", ":", "class", ":", "tf", ".", "SparseTensor", "value", "return", "an", "array", "of", "Python", "strings", "representing", "its", "values", "converting", "tokens", "to", "strings", "using", "alphabet", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/evaluate.py#L25-L30
[ "def", "sparse_tensor_value_to_texts", "(", "value", ",", "alphabet", ")", ":", "return", "sparse_tuple_to_texts", "(", "(", "value", ".", "indices", ",", "value", ".", "values", ",", "value", ".", "dense_shape", ")", ",", "alphabet", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
parse_args
Parse command line parameters Args: args ([str]): Command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace
bin/import_gram_vaani.py
def parse_args(args): """Parse command line parameters Args: args ([str]): Command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Imports GramVaani data for Deep Speech" ...
def parse_args(args): """Parse command line parameters Args: args ([str]): Command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Imports GramVaani data for Deep Speech" ...
[ "Parse", "command", "line", "parameters", "Args", ":", "args", "(", "[", "str", "]", ")", ":", "Command", "line", "parameters", "as", "list", "of", "strings", "Returns", ":", ":", "obj", ":", "argparse", ".", "Namespace", ":", "command", "line", "paramet...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L32-L79
[ "def", "parse_args", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Imports GramVaani data for Deep Speech\"", ")", "parser", ".", "add_argument", "(", "\"--version\"", ",", "action", "=", "\"version\"", ",", "...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
setup_logging
Setup basic logging Args: level (int): minimum log level for emitting messages
bin/import_gram_vaani.py
def setup_logging(level): """Setup basic logging Args: level (int): minimum log level for emitting messages """ 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" )
def setup_logging(level): """Setup basic logging Args: level (int): minimum log level for emitting messages """ 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", "Args", ":", "level", "(", "int", ")", ":", "minimum", "log", "level", "for", "emitting", "messages" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L81-L89
[ "def", "setup_logging", "(", "level", ")", ":", "format", "=", "\"[%(asctime)s] %(levelname)s:%(name)s:%(message)s\"", "logging", ".", "basicConfig", "(", "level", "=", "level", ",", "stream", "=", "sys", ".", "stdout", ",", "format", "=", "format", ",", "datefm...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
main
Main entry point allowing external calls Args: args ([str]): command line parameter list
bin/import_gram_vaani.py
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.info("Starting GramVaani importer...") _logger.info("Starting loading GramVaani csv...") csv = GramVaaniCSV(a...
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.info("Starting GramVaani importer...") _logger.info("Starting loading GramVaani csv...") csv = GramVaaniCSV(a...
[ "Main", "entry", "point", "allowing", "external", "calls", "Args", ":", "args", "(", "[", "str", "]", ")", ":", "command", "line", "parameter", "list" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L281-L300
[ "def", "main", "(", "args", ")", ":", "args", "=", "parse_args", "(", "args", ")", "setup_logging", "(", "args", ".", "loglevel", ")", "_logger", ".", "info", "(", "\"Starting GramVaani importer...\"", ")", "_logger", ".", "info", "(", "\"Starting loading Gram...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
GramVaaniDownloader.download
Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which the associated mp3's were downloaded
bin/import_gram_vaani.py
def download(self): """Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which the associated mp3's were downloaded """ mp3_directory = self._pre_download() self.data.swifter.apply(func=lambda arg: self._download(*arg, ...
def download(self): """Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which the associated mp3's were downloaded """ mp3_directory = self._pre_download() self.data.swifter.apply(func=lambda arg: self._download(*arg, ...
[ "Downloads", "the", "data", "associated", "with", "this", "instance", "Return", ":", "mp3_directory", "(", "os", ".", "path", ")", ":", "The", "directory", "into", "which", "the", "associated", "mp3", "s", "were", "downloaded" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L131-L138
[ "def", "download", "(", "self", ")", ":", "mp3_directory", "=", "self", ".", "_pre_download", "(", ")", "self", ".", "data", ".", "swifter", ".", "apply", "(", "func", "=", "lambda", "arg", ":", "self", ".", "_download", "(", "*", "arg", ",", "mp3_di...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
GramVaaniConverter.convert
Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The directory into which the associated wav's were downloaded
bin/import_gram_vaani.py
def convert(self): """Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The directory into which the associated wav's were downloaded """ wav_directory = self._pre_convert() for mp3_filename in self.mp3_directory.glob('**/*.mp3')...
def convert(self): """Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The directory into which the associated wav's were downloaded """ wav_directory = self._pre_convert() for mp3_filename in self.mp3_directory.glob('**/*.mp3')...
[ "Converts", "the", "mp3", "s", "associated", "with", "this", "instance", "to", "wav", "s", "Return", ":", "wav_directory", "(", "os", ".", "path", ")", ":", "The", "directory", "into", "which", "the", "associated", "wav", "s", "were", "downloaded" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L174-L189
[ "def", "convert", "(", "self", ")", ":", "wav_directory", "=", "self", ".", "_pre_convert", "(", ")", "for", "mp3_filename", "in", "self", ".", "mp3_directory", ".", "glob", "(", "'**/*.mp3'", ")", ":", "wav_filename", "=", "path", ".", "join", "(", "wav...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
text_to_char_array
r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string.
util/text.py
def text_to_char_array(original, alphabet): r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string. """ return np.asarray([alphabet.label_from_string(c) for c in original])
def text_to_char_array(original, alphabet): r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string. """ return np.asarray([alphabet.label_from_string(c) for c in original])
[ "r", "Given", "a", "Python", "string", "original", "remove", "unsupported", "characters", "map", "characters", "to", "integers", "and", "return", "a", "numpy", "array", "representing", "the", "processed", "string", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/text.py#L50-L55
[ "def", "text_to_char_array", "(", "original", ",", "alphabet", ")", ":", "return", "np", ".", "asarray", "(", "[", "alphabet", ".", "label_from_string", "(", "c", ")", "for", "c", "in", "original", "]", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
wer_cer_batch
r""" The WER is defined as the editing/Levenshtein distance on word level divided by the amount of words in the original text. In case of the original having more words (N) than the result and both being totally different (all N words resulting in 1 edit operation each), the WER will always be 1 (N ...
util/text.py
def wer_cer_batch(originals, results): r""" The WER is defined as the editing/Levenshtein distance on word level divided by the amount of words in the original text. In case of the original having more words (N) than the result and both being totally different (all N words resulting in 1 edit operat...
def wer_cer_batch(originals, results): r""" The WER is defined as the editing/Levenshtein distance on word level divided by the amount of words in the original text. In case of the original having more words (N) than the result and both being totally different (all N words resulting in 1 edit operat...
[ "r", "The", "WER", "is", "defined", "as", "the", "editing", "/", "Levenshtein", "distance", "on", "word", "level", "divided", "by", "the", "amount", "of", "words", "in", "the", "original", "text", ".", "In", "case", "of", "the", "original", "having", "mo...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/text.py#L58-L83
[ "def", "wer_cer_batch", "(", "originals", ",", "results", ")", ":", "# 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", "...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
variable_on_cpu
r""" Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory.
DeepSpeech.py
def variable_on_cpu(name, shape, initializer): r""" Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory. """ # Use the /cpu:0 device for scoped operations with tf.device(Con...
def variable_on_cpu(name, shape, initializer): r""" Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory. """ # Use the /cpu:0 device for scoped operations with tf.device(Con...
[ "r", "Next", "we", "concern", "ourselves", "with", "graph", "creation", ".", "However", "before", "we", "do", "so", "we", "must", "introduce", "a", "utility", "function", "variable_on_cpu", "()", "used", "to", "create", "a", "variable", "in", "CPU", "memory"...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L31-L41
[ "def", "variable_on_cpu", "(", "name", ",", "shape", ",", "initializer", ")", ":", "# Use the /cpu:0 device for scoped operations", "with", "tf", ".", "device", "(", "Config", ".", "cpu_device", ")", ":", "# Create or get apropos variable", "var", "=", "tf", ".", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
calculate_mean_edit_distance_and_loss
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 the batch's original Y.
DeepSpeech.py
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 the batch's original Y. ''' # Obtain th...
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 the batch's original Y. ''' # Obtain th...
[ "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",...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L176-L195
[ "def", "calculate_mean_edit_distance_and_loss", "(", "iterator", ",", "dropout", ",", "reuse", ")", ":", "# Obtain the next batch of data", "(", "batch_x", ",", "batch_seq_len", ")", ",", "batch_y", "=", "iterator", ".", "get_next", "(", ")", "# Calculate the logits o...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
get_tower_results
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.
DeepSpeech.py
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. ''' # To calculate the mean of the losses ...
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. ''' # To calculate the mean of the losses ...
[ "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", "averag...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L231-L273
[ "def", "get_tower_results", "(", "iterator", ",", "optimizer", ",", "dropout_rates", ")", ":", "# To calculate the mean of the losses", "tower_avg_losses", "=", "[", "]", "# Tower gradients to return", "tower_gradients", "=", "[", "]", "with", "tf", ".", "variable_scope...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
average_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 it can run to completion.
DeepSpeech.py
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 it can run to completion. ''' # List ...
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 it can run to completion. ''' # List ...
[ "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", "a...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L276-L310
[ "def", "average_gradients", "(", "tower_gradients", ")", ":", "# List of average gradients to return to the caller", "average_grads", "=", "[", "]", "# Run this on cpu_device to conserve GPU memory", "with", "tf", ".", "device", "(", "Config", ".", "cpu_device", ")", ":", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
log_variable
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 an optimization gradient.
DeepSpeech.py
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 an optimization gradient. ''' name = ...
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 an optimization gradient. ''' name = ...
[ "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"...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L317-L336
[ "def", "log_variable", "(", "variable", ",", "gradient", "=", "None", ")", ":", "name", "=", "variable", ".", "name", ".", "replace", "(", "':'", ",", "'_'", ")", "mean", "=", "tf", ".", "reduce_mean", "(", "variable", ")", "tf", ".", "summary", ".",...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
export
r''' Restores the trained variables into a simpler graph that will be exported for serving.
DeepSpeech.py
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(batch_size=FLAGS.export_batch_size, n_steps=...
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(batch_size=FLAGS.export_batch_size, n_steps=...
[ "r", "Restores", "the", "trained", "variables", "into", "a", "simpler", "graph", "that", "will", "be", "exported", "for", "serving", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L673-L759
[ "def", "export", "(", ")", ":", "log_info", "(", "'Exporting the model...'", ")", "from", "tensorflow", ".", "python", ".", "framework", ".", "ops", "import", "Tensor", ",", "Operation", "inputs", ",", "outputs", ",", "_", "=", "create_inference_graph", "(", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
ctc_beam_search_decoder
Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2-D list of probability distributions over each time step, with each element being a list of normalized probabilities over alphabet and blank. :type probs_seq: 2-D list :param alphabet: alphabet list. ...
native_client/ctcdecode/__init__.py
def ctc_beam_search_decoder(probs_seq, alphabet, beam_size, cutoff_prob=1.0, cutoff_top_n=40, scorer=None): """Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2...
def ctc_beam_search_decoder(probs_seq, alphabet, beam_size, cutoff_prob=1.0, cutoff_top_n=40, scorer=None): """Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2...
[ "Wrapper", "for", "the", "CTC", "Beam", "Search", "Decoder", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/native_client/ctcdecode/__init__.py#L25-L59
[ "def", "ctc_beam_search_decoder", "(", "probs_seq", ",", "alphabet", ",", "beam_size", ",", "cutoff_prob", "=", "1.0", ",", "cutoff_top_n", "=", "40", ",", "scorer", "=", "None", ")", ":", "beam_results", "=", "swigwrapper", ".", "ctc_beam_search_decoder", "(", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
ctc_beam_search_decoder_batch
Wrapper for the batched CTC beam search decoder. :param probs_seq: 3-D list with each element as an instance of 2-D list of probabilities used by ctc_beam_search_decoder(). :type probs_seq: 3-D list :param alphabet: alphabet list. :alphabet: Alphabet :param beam_size: Width fo...
native_client/ctcdecode/__init__.py
def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob=1.0, cutof...
def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob=1.0, cutof...
[ "Wrapper", "for", "the", "batched", "CTC", "beam", "search", "decoder", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/native_client/ctcdecode/__init__.py#L62-L104
[ "def", "ctc_beam_search_decoder_batch", "(", "probs_seq", ",", "seq_lengths", ",", "alphabet", ",", "beam_size", ",", "num_processes", ",", "cutoff_prob", "=", "1.0", ",", "cutoff_top_n", "=", "40", ",", "scorer", "=", "None", ")", ":", "batch_beam_results", "="...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
Audio.resample
Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio rate to resample from
examples/mic_vad_streaming/mic_vad_streaming.py
def resample(self, data, input_rate): """ Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio r...
def resample(self, data, input_rate): """ Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio r...
[ "Microphone", "may", "not", "support", "our", "native", "processing", "sampling", "rate", "so", "resample", "from", "input_rate", "to", "RATE_PROCESS", "here", "for", "webrtcvad", "and", "deepspeech" ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L52-L66
[ "def", "resample", "(", "self", ",", "data", ",", "input_rate", ")", ":", "data16", "=", "np", ".", "fromstring", "(", "string", "=", "data", ",", "dtype", "=", "np", ".", "int16", ")", "resample_size", "=", "int", "(", "len", "(", "data16", ")", "...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
Audio.read_resampled
Return a block of audio data resampled to 16000hz, blocking if necessary.
examples/mic_vad_streaming/mic_vad_streaming.py
def read_resampled(self): """Return a block of audio data resampled to 16000hz, blocking if necessary.""" return self.resample(data=self.buffer_queue.get(), input_rate=self.input_rate)
def read_resampled(self): """Return a block of audio data resampled to 16000hz, blocking if necessary.""" 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", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L68-L71
[ "def", "read_resampled", "(", "self", ")", ":", "return", "self", ".", "resample", "(", "data", "=", "self", ".", "buffer_queue", ".", "get", "(", ")", ",", "input_rate", "=", "self", ".", "input_rate", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
VADAudio.frame_generator
Generator that yields all audio frames from microphone.
examples/mic_vad_streaming/mic_vad_streaming.py
def frame_generator(self): """Generator that yields all audio frames from microphone.""" if self.input_rate == self.RATE_PROCESS: while True: yield self.read() else: while True: yield self.read_resampled()
def frame_generator(self): """Generator that yields all audio frames from microphone.""" 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", "." ]
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L103-L110
[ "def", "frame_generator", "(", "self", ")", ":", "if", "self", ".", "input_rate", "==", "self", ".", "RATE_PROCESS", ":", "while", "True", ":", "yield", "self", ".", "read", "(", ")", "else", ":", "while", "True", ":", "yield", "self", ".", "read_resam...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
VADAudio.vad_collector
Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being triggered. Example: (frame, ..., frame, None, frame, ..., frame,...
examples/mic_vad_streaming/mic_vad_streaming.py
def vad_collector(self, padding_ms=300, ratio=0.75, frames=None): """Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being...
def vad_collector(self, padding_ms=300, ratio=0.75, frames=None): """Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being...
[ "Generator", "that", "yields", "series", "of", "consecutive", "audio", "frames", "comprising", "each", "utterence", "separated", "by", "yielding", "a", "single", "None", ".", "Determines", "voice", "activity", "by", "ratio", "of", "frames", "in", "padding_ms", "...
mozilla/DeepSpeech
python
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L112-L142
[ "def", "vad_collector", "(", "self", ",", "padding_ms", "=", "300", ",", "ratio", "=", "0.75", ",", "frames", "=", "None", ")", ":", "if", "frames", "is", "None", ":", "frames", "=", "self", ".", "frame_generator", "(", ")", "num_padding_frames", "=", ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
train
cut
Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported.
jieba/posseg/__init__.py
def cut(sentence, HMM=True): """ Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported. """ global dt if jieba.pool is None: for w in dt.cut(sentence, HMM=HMM): yield w else: ...
def cut(sentence, HMM=True): """ Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported. """ global dt if jieba.pool is None: for w in dt.cut(sentence, HMM=HMM): yield w else: ...
[ "Global", "cut", "function", "that", "supports", "parallel", "processing", "." ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/posseg/__init__.py#L272-L291
[ "def", "cut", "(", "sentence", ",", "HMM", "=", "True", ")", ":", "global", "dt", "if", "jieba", ".", "pool", "is", "None", ":", "for", "w", "in", "dt", ".", "cut", "(", "sentence", ",", "HMM", "=", "HMM", ")", ":", "yield", "w", "else", ":", ...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
enable_parallel
Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported.
jieba/__init__.py
def enable_parallel(processnum=None): """ Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported. """ global pool, dt, cut, cut_for_search from multiprocessing import cpu_count ...
def enable_parallel(processnum=None): """ Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported. """ global pool, dt, cut, cut_for_search from multiprocessing import cpu_count ...
[ "Change", "the", "module", "s", "cut", "and", "cut_for_search", "functions", "to", "the", "parallel", "version", "." ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L569-L589
[ "def", "enable_parallel", "(", "processnum", "=", "None", ")", ":", "global", "pool", ",", "dt", ",", "cut", ",", "cut_for_search", "from", "multiprocessing", "import", "cpu_count", "if", "os", ".", "name", "==", "'nt'", ":", "raise", "NotImplementedError", ...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
Tokenizer.cut
The main function that segments an entire sentence that contains Chinese characters into separated words. Parameter: - sentence: The str(unicode) to be segmented. - cut_all: Model type. True for full pattern, False for accurate pattern. - HMM: Whether to use the Hidd...
jieba/__init__.py
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. - cut_all: Model type. True for full pattern, ...
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. - cut_all: Model type. True for full pattern, ...
[ "The", "main", "function", "that", "segments", "an", "entire", "sentence", "that", "contains", "Chinese", "characters", "into", "separated", "words", "." ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L275-L315
[ "def", "cut", "(", "self", ",", "sentence", ",", "cut_all", "=", "False", ",", "HMM", "=", "True", ")", ":", "sentence", "=", "strdecode", "(", "sentence", ")", "if", "cut_all", ":", "re_han", "=", "re_han_cut_all", "re_skip", "=", "re_skip_cut_all", "el...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
Tokenizer.cut_for_search
Finer segmentation for search engines.
jieba/__init__.py
def cut_for_search(self, sentence, HMM=True): """ Finer segmentation for search engines. """ 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 s...
def cut_for_search(self, sentence, HMM=True): """ Finer segmentation for search engines. """ 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 s...
[ "Finer", "segmentation", "for", "search", "engines", "." ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L317-L333
[ "def", "cut_for_search", "(", "self", ",", "sentence", ",", "HMM", "=", "True", ")", ":", "words", "=", "self", ".", "cut", "(", "sentence", ",", "HMM", "=", "HMM", ")", "for", "w", "in", "words", ":", "if", "len", "(", "w", ")", ">", "2", ":",...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
Tokenizer.load_userdict
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, whose encoding must be utf-8. Structure of dict file: word1 freq...
jieba/__init__.py
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, whose encoding must be utf-8. ...
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, whose encoding must be utf-8. ...
[ "Load", "personalized", "dict", "to", "improve", "detect", "rate", "." ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L359-L395
[ "def", "load_userdict", "(", "self", ",", "f", ")", ":", "self", ".", "check_initialized", "(", ")", "if", "isinstance", "(", "f", ",", "string_types", ")", ":", "f_name", "=", "f", "f", "=", "open", "(", "f", ",", "'rb'", ")", "else", ":", "f_name...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
Tokenizer.add_word
Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out.
jieba/__init__.py
def add_word(self, word, freq=None, tag=None): """ Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out. """ self.check_initialized() word = strdecode(word) freq = int(freq) if ...
def add_word(self, word, freq=None, tag=None): """ Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out. """ self.check_initialized() word = strdecode(word) freq = int(freq) if ...
[ "Add", "a", "word", "to", "dictionary", "." ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L397-L416
[ "def", "add_word", "(", "self", ",", "word", ",", "freq", "=", "None", ",", "tag", "=", "None", ")", ":", "self", ".", "check_initialized", "(", ")", "word", "=", "strdecode", "(", "word", ")", "freq", "=", "int", "(", "freq", ")", "if", "freq", ...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
Tokenizer.suggest_freq
Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole, use a str. - tune : If True, tune the word frequency...
jieba/__init__.py
def suggest_freq(self, segment, tune=False): """ Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole,...
def suggest_freq(self, segment, tune=False): """ Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole,...
[ "Suggest", "word", "frequency", "to", "force", "the", "characters", "in", "a", "word", "to", "be", "joined", "or", "splitted", "." ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L424-L453
[ "def", "suggest_freq", "(", "self", ",", "segment", ",", "tune", "=", "False", ")", ":", "self", ".", "check_initialized", "(", ")", "ftotal", "=", "float", "(", "self", ".", "total", ")", "freq", "=", "1", "if", "isinstance", "(", "segment", ",", "s...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
Tokenizer.tokenize
Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: whether to use the Hidden Markov Model.
jieba/__init__.py
def tokenize(self, unicode_sentence, mode="default", HMM=True): """ Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: ...
def tokenize(self, unicode_sentence, mode="default", HMM=True): """ Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: ...
[ "Tokenize", "a", "sentence", "and", "yields", "tuples", "of", "(", "word", "start", "end", ")" ]
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L455-L486
[ "def", "tokenize", "(", "self", ",", "unicode_sentence", ",", "mode", "=", "\"default\"", ",", "HMM", "=", "True", ")", ":", "if", "not", "isinstance", "(", "unicode_sentence", ",", "text_type", ")", ":", "raise", "ValueError", "(", "\"jieba: the input paramet...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
TextRank.textrank
Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed...
jieba/analyse/textrank.py
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
[ "Extract", "keywords", "from", "sentence", "using", "TextRank", "algorithm", ".", "Parameter", ":", "-", "topK", ":", "return", "how", "many", "top", "keywords", ".", "None", "for", "all", "possible", "words", ".", "-", "withWeight", ":", "if", "True", "re...
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/analyse/textrank.py#L69-L108
[ "def", "textrank", "(", "self", ",", "sentence", ",", "topK", "=", "20", ",", "withWeight", "=", "False", ",", "allowPOS", "=", "(", "'ns'", ",", "'n'", ",", "'vn'", ",", "'v'", ")", ",", "withFlag", "=", "False", ")", ":", "self", ".", "pos_filt",...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
TFIDF.extract_tags
Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed P...
jieba/analyse/tfidf.py
def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False): """ Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (wo...
def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False): """ Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (wo...
[ "Extract", "keywords", "from", "sentence", "using", "TF", "-", "IDF", "algorithm", ".", "Parameter", ":", "-", "topK", ":", "return", "how", "many", "top", "keywords", ".", "None", "for", "all", "possible", "words", ".", "-", "withWeight", ":", "if", "Tr...
fxsjy/jieba
python
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/analyse/tfidf.py#L75-L116
[ "def", "extract_tags", "(", "self", ",", "sentence", ",", "topK", "=", "20", ",", "withWeight", "=", "False", ",", "allowPOS", "=", "(", ")", ",", "withFlag", "=", "False", ")", ":", "if", "allowPOS", ":", "allowPOS", "=", "frozenset", "(", "allowPOS",...
8212b6c5725d08311952a3a08e5509eeaee33eb7
train
paracrawl_v3_pairs
Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in the middle of creating a translation p...
tensor2tensor/data_generators/cleaner_en_xx.py
def paracrawl_v3_pairs(paracrawl_file): """Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in t...
def paracrawl_v3_pairs(paracrawl_file): """Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in t...
[ "Generates", "raw", "(", "English", "other", ")", "pairs", "from", "a", "ParaCrawl", "V3", ".", "0", "data", "file", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cleaner_en_xx.py#L66-L86
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_raw_sentences
Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the ParaCrawl data file.
tensor2tensor/data_generators/cleaner_en_xx.py
def _raw_sentences(paracrawl_file): """Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the Pa...
def _raw_sentences(paracrawl_file): """Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the Pa...
[ "Generates", "Unicode", "strings", "one", "for", "each", "<seg", ">", "in", "a", "ParaCrawl", "data", "file", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cleaner_en_xx.py#L89-L110
[ "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", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
clean_en_xx_pairs
Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sentence splitting assumes only that sente...
tensor2tensor/data_generators/cleaner_en_xx.py
def clean_en_xx_pairs(en_xx_pairs): """Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sen...
def clean_en_xx_pairs(en_xx_pairs): """Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sen...
[ "Generates", "a", "cleaned", "-", "up", "stream", "of", "(", "English", "other", ")", "translation", "pairs", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cleaner_en_xx.py#L113-L142
[ "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"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_get_case_file_paths
Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for training (true) or eval (false). training_fraction: float, the ...
tensor2tensor/data_generators/allen_brain.py
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95): """Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for tra...
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95): """Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for tra...
[ "Obtain", "a", "list", "of", "image", "paths", "corresponding", "to", "training", "or", "eval", "case", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L81-L121
[ "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", "(", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
maybe_download_image_dataset
Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images.
tensor2tensor/data_generators/allen_brain.py
def maybe_download_image_dataset(image_ids, target_dir): """Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images. """ tf.gfile.MakeDirs(target_dir) num_images = len(image_ids) for...
def maybe_download_image_dataset(image_ids, target_dir): """Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images. """ tf.gfile.MakeDirs(target_dir) num_images = len(image_ids) for...
[ "Download", "a", "set", "of", "images", "from", "api", ".", "brain", "-", "map", ".", "org", "to", "target_dir", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L124-L163
[ "def", "maybe_download_image_dataset", "(", "image_ids", ",", "target_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "target_dir", ")", "num_images", "=", "len", "(", "image_ids", ")", "for", "i", ",", "image_id", "in", "enumerate", "(", "image_id...
272500b6efe353aeb638d2745ed56e519462ca31
train
random_square_mask
Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask.
tensor2tensor/data_generators/allen_brain.py
def random_square_mask(shape, fraction): """Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask. """ mask =...
def random_square_mask(shape, fraction): """Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask. """ mask =...
[ "Create", "a", "numpy", "array", "with", "specified", "shape", "and", "masked", "fraction", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L166-L189
[ "def", "random_square_mask", "(", "shape", ",", "fraction", ")", ":", "mask", "=", "np", ".", "ones", "(", "shape", ")", "patch_area", "=", "shape", "[", "0", "]", "*", "shape", "[", "1", "]", "*", "fraction", "patch_dim", "=", "np", ".", "int", "(...
272500b6efe353aeb638d2745ed56e519462ca31
train
_generator
Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training (or, alternatively, evaluation), determining whether examples in tmp_dir prefixed with train or d...
tensor2tensor/data_generators/allen_brain.py
def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE, training_fraction=0.95): """Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training...
def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE, training_fraction=0.95): """Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training...
[ "Base", "problem", "example", "generator", "for", "Allen", "Brain", "Atlas", "problems", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L192-L260
[ "def", "_generator", "(", "tmp_dir", ",", "training", ",", "size", "=", "_BASE_EXAMPLE_IMAGE_SIZE", ",", "training_fraction", "=", "0.95", ")", ":", "maybe_download_image_dataset", "(", "_IMAGE_IDS", ",", "tmp_dir", ")", "image_files", "=", "_get_case_file_paths", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_moe_base
Set of hyperparameters.
tensor2tensor/models/research/transformer_moe.py
def transformer_moe_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2001 hparams.max_input_seq_length = 2000 hparams.max_target_seq_length = 2000 hparams.dropout = 0.0 ...
def transformer_moe_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2001 hparams.max_input_seq_length = 2000 hparams.max_target_seq_length = 2000 hparams.dropout = 0.0 ...
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L267-L311
[ "def", "transformer_moe_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "norm_type", "=", "\"layer\"", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "batch_size", "=", "4096", "hparams", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_moe_8k
Hyper parameters specifics for long sequence generation.
tensor2tensor/models/research/transformer_moe.py
def transformer_moe_8k(): """Hyper parameters specifics for long sequence generation.""" hparams = transformer_moe_base() hparams.batch_size = 8192 hparams.max_length = 0 # max_length == batch_size hparams.eval_drop_long_sequences = True hparams.min_length_bucket = 256 # Avoid cyclic problems for big bat...
def transformer_moe_8k(): """Hyper parameters specifics for long sequence generation.""" hparams = transformer_moe_base() hparams.batch_size = 8192 hparams.max_length = 0 # max_length == batch_size hparams.eval_drop_long_sequences = True hparams.min_length_bucket = 256 # Avoid cyclic problems for big bat...
[ "Hyper", "parameters", "specifics", "for", "long", "sequence", "generation", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L315-L327
[ "def", "transformer_moe_8k", "(", ")", ":", "hparams", "=", "transformer_moe_base", "(", ")", "hparams", ".", "batch_size", "=", "8192", "hparams", ".", "max_length", "=", "0", "# max_length == batch_size", "hparams", ".", "eval_drop_long_sequences", "=", "True", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_moe_2k
Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: * Layer 0: a - a - sepm (self-a...
tensor2tensor/models/research/transformer_moe.py
def transformer_moe_2k(): """Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: *...
def transformer_moe_2k(): """Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: *...
[ "Base", "transformers", "model", "with", "moe", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L365-L395
[ "def", "transformer_moe_2k", "(", ")", ":", "hparams", "=", "transformer_moe_8k", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "default_ff", "=", "\"sep\"", "# hparams.layer_types contains the network architecture:", "encoder_archi", "=", "\"a/a/...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_moe_prepend_8k
Model which formulate a seq2seq problem as language modeling.
tensor2tensor/models/research/transformer_moe.py
def transformer_moe_prepend_8k(): """Model which formulate a seq2seq problem as language modeling.""" hparams = transformer_moe_8k() hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.eval_drop_long_sequences = False hparams.max_input_seq_length = 7500 hparams.default_ff = "sepm" hparams.lay...
def transformer_moe_prepend_8k(): """Model which formulate a seq2seq problem as language modeling.""" hparams = transformer_moe_8k() hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.eval_drop_long_sequences = False hparams.max_input_seq_length = 7500 hparams.default_ff = "sepm" hparams.lay...
[ "Model", "which", "formulate", "a", "seq2seq", "problem", "as", "language", "modeling", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L409-L418
[ "def", "transformer_moe_prepend_8k", "(", ")", ":", "hparams", "=", "transformer_moe_8k", "(", ")", "hparams", ".", "prepend_mode", "=", "\"prepend_inputs_masked_attention\"", "hparams", ".", "eval_drop_long_sequences", "=", "False", "hparams", ".", "max_input_seq_length"...
272500b6efe353aeb638d2745ed56e519462ca31
train
f
Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the third conv layer. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. first_batch_norm: Whether to keep the first batch norm...
tensor2tensor/models/revnet.py
def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1, training=True, bottleneck=True, padding='SAME'): """Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the thi...
def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1, training=True, bottleneck=True, padding='SAME'): """Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the thi...
[ "Applies", "residual", "function", "for", "RevNet", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L72-L122
[ "def", "f", "(", "x", ",", "depth1", ",", "depth2", ",", "dim", "=", "'2d'", ",", "first_batch_norm", "=", "True", ",", "stride", "=", "1", ",", "training", "=", "True", ",", "bottleneck", "=", "True", ",", "padding", "=", "'SAME'", ")", ":", "conv...
272500b6efe353aeb638d2745ed56e519462ca31
train
downsample_bottleneck
Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use. Usually 1 or 2. scope: Optional variable scope. Returns: ...
tensor2tensor/models/revnet.py
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What...
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What...
[ "Downsamples", "x", "by", "stride", "using", "a", "1x1", "convolution", "filter", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L125-L144
[ "def", "downsample_bottleneck", "(", "x", ",", "output_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "1", ",", "scope", "=", "'h'", ")", ":", "conv", "=", "CONFIG", "[", "dim", "]", "[", "'conv'", "]", "with", "tf", ".", "variable_scope", "...
272500b6efe353aeb638d2745ed56e519462ca31