id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
30,100
iterative/dvc
dvc/analytics.py
Analytics.load
def load(path): """Loads analytics report from json file specified by path. Args: path (str): path to json file with analytics report. """ with open(path, "r") as fobj: analytics = Analytics(info=json.load(fobj)) os.unlink(path) return analytics
python
def load(path): """Loads analytics report from json file specified by path. Args: path (str): path to json file with analytics report. """ with open(path, "r") as fobj: analytics = Analytics(info=json.load(fobj)) os.unlink(path) return analytics
[ "def", "load", "(", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "fobj", ":", "analytics", "=", "Analytics", "(", "info", "=", "json", ".", "load", "(", "fobj", ")", ")", "os", ".", "unlink", "(", "path", ")", "return",...
Loads analytics report from json file specified by path. Args: path (str): path to json file with analytics report.
[ "Loads", "analytics", "report", "from", "json", "file", "specified", "by", "path", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L72-L81
30,101
iterative/dvc
dvc/analytics.py
Analytics.collect
def collect(self): """Collect analytics report.""" from dvc.scm import SCM from dvc.utils import is_binary from dvc.repo import Repo from dvc.exceptions import NotDvcRepoError self.info[self.PARAM_DVC_VERSION] = __version__ self.info[self.PARAM_IS_BINARY] = is_bi...
python
def collect(self): """Collect analytics report.""" from dvc.scm import SCM from dvc.utils import is_binary from dvc.repo import Repo from dvc.exceptions import NotDvcRepoError self.info[self.PARAM_DVC_VERSION] = __version__ self.info[self.PARAM_IS_BINARY] = is_bi...
[ "def", "collect", "(", "self", ")", ":", "from", "dvc", ".", "scm", "import", "SCM", "from", "dvc", ".", "utils", "import", "is_binary", "from", "dvc", ".", "repo", "import", "Repo", "from", "dvc", ".", "exceptions", "import", "NotDvcRepoError", "self", ...
Collect analytics report.
[ "Collect", "analytics", "report", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L164-L181
30,102
iterative/dvc
dvc/analytics.py
Analytics.collect_cmd
def collect_cmd(self, args, ret): """Collect analytics info from a CLI command.""" from dvc.command.daemon import CmdDaemonAnalytics assert isinstance(ret, int) or ret is None if ret is not None: self.info[self.PARAM_CMD_RETURN_CODE] = ret if args is not None and h...
python
def collect_cmd(self, args, ret): """Collect analytics info from a CLI command.""" from dvc.command.daemon import CmdDaemonAnalytics assert isinstance(ret, int) or ret is None if ret is not None: self.info[self.PARAM_CMD_RETURN_CODE] = ret if args is not None and h...
[ "def", "collect_cmd", "(", "self", ",", "args", ",", "ret", ")", ":", "from", "dvc", ".", "command", ".", "daemon", "import", "CmdDaemonAnalytics", "assert", "isinstance", "(", "ret", ",", "int", ")", "or", "ret", "is", "None", "if", "ret", "is", "not"...
Collect analytics info from a CLI command.
[ "Collect", "analytics", "info", "from", "a", "CLI", "command", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L183-L194
30,103
iterative/dvc
dvc/analytics.py
Analytics.dump
def dump(self): """Save analytics report to a temporary file. Returns: str: path to the temporary file that contains the analytics report. """ import tempfile with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj: json.dump(self.info, fobj) ...
python
def dump(self): """Save analytics report to a temporary file. Returns: str: path to the temporary file that contains the analytics report. """ import tempfile with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj: json.dump(self.info, fobj) ...
[ "def", "dump", "(", "self", ")", ":", "import", "tempfile", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ",", "mode", "=", "\"w\"", ")", "as", "fobj", ":", "json", ".", "dump", "(", "self", ".", "info", ",", "fobj", ")"...
Save analytics report to a temporary file. Returns: str: path to the temporary file that contains the analytics report.
[ "Save", "analytics", "report", "to", "a", "temporary", "file", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L196-L206
30,104
iterative/dvc
dvc/analytics.py
Analytics.send_cmd
def send_cmd(cmd, args, ret): """Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command. """ from dvc.daemon import daemon if not Analytics._is_enabled(cmd): ...
python
def send_cmd(cmd, args, ret): """Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command. """ from dvc.daemon import daemon if not Analytics._is_enabled(cmd): ...
[ "def", "send_cmd", "(", "cmd", ",", "args", ",", "ret", ")", ":", "from", "dvc", ".", "daemon", "import", "daemon", "if", "not", "Analytics", ".", "_is_enabled", "(", "cmd", ")", ":", "return", "analytics", "=", "Analytics", "(", ")", "analytics", ".",...
Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command.
[ "Collect", "and", "send", "analytics", "for", "CLI", "command", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L247-L261
30,105
iterative/dvc
dvc/analytics.py
Analytics.send
def send(self): """Collect and send analytics.""" import requests if not self._is_enabled(): return self.collect() logger.debug("Sending analytics: {}".format(self.info)) try: requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST) ...
python
def send(self): """Collect and send analytics.""" import requests if not self._is_enabled(): return self.collect() logger.debug("Sending analytics: {}".format(self.info)) try: requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST) ...
[ "def", "send", "(", "self", ")", ":", "import", "requests", "if", "not", "self", ".", "_is_enabled", "(", ")", ":", "return", "self", ".", "collect", "(", ")", "logger", ".", "debug", "(", "\"Sending analytics: {}\"", ".", "format", "(", "self", ".", "...
Collect and send analytics.
[ "Collect", "and", "send", "analytics", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L263-L277
30,106
iterative/dvc
dvc/data_cloud.py
DataCloud.push
def push(self, targets, jobs=None, remote=None, show_checksums=False): """Push data items in a cloud-agnostic way. Args: targets (list): list of targets to push to the cloud. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remote.base.Remot...
python
def push(self, targets, jobs=None, remote=None, show_checksums=False): """Push data items in a cloud-agnostic way. Args: targets (list): list of targets to push to the cloud. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remote.base.Remot...
[ "def", "push", "(", "self", ",", "targets", ",", "jobs", "=", "None", ",", "remote", "=", "None", ",", "show_checksums", "=", "False", ")", ":", "return", "self", ".", "repo", ".", "cache", ".", "local", ".", "push", "(", "targets", ",", "jobs", "=...
Push data items in a cloud-agnostic way. Args: targets (list): list of targets to push to the cloud. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remote.base.RemoteBase): optional remote to push to. By default remote from core.re...
[ "Push", "data", "items", "in", "a", "cloud", "-", "agnostic", "way", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/data_cloud.py#L117-L133
30,107
iterative/dvc
dvc/data_cloud.py
DataCloud.status
def status(self, targets, jobs=None, remote=None, show_checksums=False): """Check status of data items in a cloud-agnostic way. Args: targets (list): list of targets to check status for. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remot...
python
def status(self, targets, jobs=None, remote=None, show_checksums=False): """Check status of data items in a cloud-agnostic way. Args: targets (list): list of targets to check status for. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remot...
[ "def", "status", "(", "self", ",", "targets", ",", "jobs", "=", "None", ",", "remote", "=", "None", ",", "show_checksums", "=", "False", ")", ":", "cloud", "=", "self", ".", "_get_cloud", "(", "remote", ",", "\"status\"", ")", "return", "self", ".", ...
Check status of data items in a cloud-agnostic way. Args: targets (list): list of targets to check status for. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remote.base.RemoteBase): optional remote to compare targets to. By defaul...
[ "Check", "status", "of", "data", "items", "in", "a", "cloud", "-", "agnostic", "way", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/data_cloud.py#L153-L168
30,108
iterative/dvc
dvc/repo/brancher.py
brancher
def brancher( # noqa: E302 self, branches=None, all_branches=False, tags=None, all_tags=False ): """Generator that iterates over specified revisions. Args: branches (list): a list of branches to iterate over. all_branches (bool): iterate over all available branches. tags (list): a ...
python
def brancher( # noqa: E302 self, branches=None, all_branches=False, tags=None, all_tags=False ): """Generator that iterates over specified revisions. Args: branches (list): a list of branches to iterate over. all_branches (bool): iterate over all available branches. tags (list): a ...
[ "def", "brancher", "(", "# noqa: E302", "self", ",", "branches", "=", "None", ",", "all_branches", "=", "False", ",", "tags", "=", "None", ",", "all_tags", "=", "False", ")", ":", "if", "not", "any", "(", "[", "branches", ",", "all_branches", ",", "tag...
Generator that iterates over specified revisions. Args: branches (list): a list of branches to iterate over. all_branches (bool): iterate over all available branches. tags (list): a list of tags to iterate over. all_tags (bool): iterate over all available tags. Yields: ...
[ "Generator", "that", "iterates", "over", "specified", "revisions", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/brancher.py#L1-L56
30,109
iterative/dvc
dvc/state.py
State.load
def load(self): """Loads state database.""" retries = 1 while True: assert self.database is None assert self.cursor is None assert self.inserts == 0 empty = not os.path.exists(self.state_file) self.database = sqlite3.connect(self.state_...
python
def load(self): """Loads state database.""" retries = 1 while True: assert self.database is None assert self.cursor is None assert self.inserts == 0 empty = not os.path.exists(self.state_file) self.database = sqlite3.connect(self.state_...
[ "def", "load", "(", "self", ")", ":", "retries", "=", "1", "while", "True", ":", "assert", "self", ".", "database", "is", "None", "assert", "self", ".", "cursor", "is", "None", "assert", "self", ".", "inserts", "==", "0", "empty", "=", "not", "os", ...
Loads state database.
[ "Loads", "state", "database", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L214-L240
30,110
iterative/dvc
dvc/state.py
State.dump
def dump(self): """Saves state database.""" assert self.database is not None cmd = "SELECT count from {} WHERE rowid={}" self._execute(cmd.format(self.STATE_INFO_TABLE, self.STATE_INFO_ROW)) ret = self._fetchall() assert len(ret) == 1 assert len(ret[0]) == 1 ...
python
def dump(self): """Saves state database.""" assert self.database is not None cmd = "SELECT count from {} WHERE rowid={}" self._execute(cmd.format(self.STATE_INFO_TABLE, self.STATE_INFO_ROW)) ret = self._fetchall() assert len(ret) == 1 assert len(ret[0]) == 1 ...
[ "def", "dump", "(", "self", ")", ":", "assert", "self", ".", "database", "is", "not", "None", "cmd", "=", "\"SELECT count from {} WHERE rowid={}\"", "self", ".", "_execute", "(", "cmd", ".", "format", "(", "self", ".", "STATE_INFO_TABLE", ",", "self", ".", ...
Saves state database.
[ "Saves", "state", "database", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L248-L299
30,111
iterative/dvc
dvc/state.py
State.save
def save(self, path_info, checksum): """Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save. """ assert path_info["scheme"] == "local" assert checksum is not None pat...
python
def save(self, path_info, checksum): """Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save. """ assert path_info["scheme"] == "local" assert checksum is not None pat...
[ "def", "save", "(", "self", ",", "path_info", ",", "checksum", ")", ":", "assert", "path_info", "[", "\"scheme\"", "]", "==", "\"local\"", "assert", "checksum", "is", "not", "None", "path", "=", "path_info", "[", "\"path\"", "]", "assert", "os", ".", "pa...
Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save.
[ "Save", "checksum", "for", "the", "specified", "path", "info", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L367-L392
30,112
iterative/dvc
dvc/state.py
State.get
def get(self, path_info): """Gets the checksum for the specified path info. Checksum will be retrieved from the state database if available. Args: path_info (dict): path info to get the checksum for. Returns: str or None: checksum for the specified path info or ...
python
def get(self, path_info): """Gets the checksum for the specified path info. Checksum will be retrieved from the state database if available. Args: path_info (dict): path info to get the checksum for. Returns: str or None: checksum for the specified path info or ...
[ "def", "get", "(", "self", ",", "path_info", ")", ":", "assert", "path_info", "[", "\"scheme\"", "]", "==", "\"local\"", "path", "=", "path_info", "[", "\"path\"", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "...
Gets the checksum for the specified path info. Checksum will be retrieved from the state database if available. Args: path_info (dict): path info to get the checksum for. Returns: str or None: checksum for the specified path info or None if it doesn't exist ...
[ "Gets", "the", "checksum", "for", "the", "specified", "path", "info", ".", "Checksum", "will", "be", "retrieved", "from", "the", "state", "database", "if", "available", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L394-L423
30,113
iterative/dvc
dvc/state.py
State.save_link
def save_link(self, path_info): """Adds the specified path to the list of links created by dvc. This list is later used on `dvc checkout` to cleanup old links. Args: path_info (dict): path info to add to the list of links. """ assert path_info["scheme"] == "local" ...
python
def save_link(self, path_info): """Adds the specified path to the list of links created by dvc. This list is later used on `dvc checkout` to cleanup old links. Args: path_info (dict): path info to add to the list of links. """ assert path_info["scheme"] == "local" ...
[ "def", "save_link", "(", "self", ",", "path_info", ")", ":", "assert", "path_info", "[", "\"scheme\"", "]", "==", "\"local\"", "path", "=", "path_info", "[", "\"path\"", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return...
Adds the specified path to the list of links created by dvc. This list is later used on `dvc checkout` to cleanup old links. Args: path_info (dict): path info to add to the list of links.
[ "Adds", "the", "specified", "path", "to", "the", "list", "of", "links", "created", "by", "dvc", ".", "This", "list", "is", "later", "used", "on", "dvc", "checkout", "to", "cleanup", "old", "links", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L425-L448
30,114
iterative/dvc
dvc/state.py
State.remove_unused_links
def remove_unused_links(self, used): """Removes all saved links except the ones that are used. Args: used (list): list of used links that should not be removed. """ unused = [] self._execute("SELECT * FROM {}".format(self.LINK_STATE_TABLE)) for row in self.c...
python
def remove_unused_links(self, used): """Removes all saved links except the ones that are used. Args: used (list): list of used links that should not be removed. """ unused = [] self._execute("SELECT * FROM {}".format(self.LINK_STATE_TABLE)) for row in self.c...
[ "def", "remove_unused_links", "(", "self", ",", "used", ")", ":", "unused", "=", "[", "]", "self", ".", "_execute", "(", "\"SELECT * FROM {}\"", ".", "format", "(", "self", ".", "LINK_STATE_TABLE", ")", ")", "for", "row", "in", "self", ".", "cursor", ":"...
Removes all saved links except the ones that are used. Args: used (list): list of used links that should not be removed.
[ "Removes", "all", "saved", "links", "except", "the", "ones", "that", "are", "used", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/state.py#L450-L480
30,115
iterative/dvc
dvc/lock.py
Lock.lock
def lock(self): """Acquire lock for dvc repo.""" try: self._do_lock() return except LockError: time.sleep(self.TIMEOUT) self._do_lock()
python
def lock(self): """Acquire lock for dvc repo.""" try: self._do_lock() return except LockError: time.sleep(self.TIMEOUT) self._do_lock()
[ "def", "lock", "(", "self", ")", ":", "try", ":", "self", ".", "_do_lock", "(", ")", "return", "except", "LockError", ":", "time", ".", "sleep", "(", "self", ".", "TIMEOUT", ")", "self", ".", "_do_lock", "(", ")" ]
Acquire lock for dvc repo.
[ "Acquire", "lock", "for", "dvc", "repo", "." ]
8bb21261e34c9632453e09090de7ebe50e38d341
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/lock.py#L41-L49
30,116
PySimpleGUI/PySimpleGUI
PySimpleGUI27.py
TkScrollableFrame.set_scrollregion
def set_scrollregion(self, event=None): """ Set the scroll region on the canvas""" self.canvas.configure(scrollregion=self.canvas.bbox('all'))
python
def set_scrollregion(self, event=None): """ Set the scroll region on the canvas""" self.canvas.configure(scrollregion=self.canvas.bbox('all'))
[ "def", "set_scrollregion", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "canvas", ".", "configure", "(", "scrollregion", "=", "self", ".", "canvas", ".", "bbox", "(", "'all'", ")", ")" ]
Set the scroll region on the canvas
[ "Set", "the", "scroll", "region", "on", "the", "canvas" ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L2769-L2771
30,117
PySimpleGUI/PySimpleGUI
PySimpleGUI27.py
TKCalendar._show_selection
def _show_selection(self, text, bbox): """Configure canvas for a new selection.""" x, y, width, height = bbox textw = self._font.measure(text) canvas = self._canvas canvas.configure(width=width, height=height) canvas.coords(canvas.text, width - textw, height / 2 - 1) ...
python
def _show_selection(self, text, bbox): """Configure canvas for a new selection.""" x, y, width, height = bbox textw = self._font.measure(text) canvas = self._canvas canvas.configure(width=width, height=height) canvas.coords(canvas.text, width - textw, height / 2 - 1) ...
[ "def", "_show_selection", "(", "self", ",", "text", ",", "bbox", ")", ":", "x", ",", "y", ",", "width", ",", "height", "=", "bbox", "textw", "=", "self", ".", "_font", ".", "measure", "(", "text", ")", "canvas", "=", "self", ".", "_canvas", "canvas...
Configure canvas for a new selection.
[ "Configure", "canvas", "for", "a", "new", "selection", "." ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3052-L3062
30,118
PySimpleGUI/PySimpleGUI
PySimpleGUI27.py
TKCalendar._prev_month
def _prev_month(self): """Updated calendar to show the previous month.""" self._canvas.place_forget() self._date = self._date - self.timedelta(days=1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar()
python
def _prev_month(self): """Updated calendar to show the previous month.""" self._canvas.place_forget() self._date = self._date - self.timedelta(days=1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar()
[ "def", "_prev_month", "(", "self", ")", ":", "self", ".", "_canvas", ".", "place_forget", "(", ")", "self", ".", "_date", "=", "self", ".", "_date", "-", "self", ".", "timedelta", "(", "days", "=", "1", ")", "self", ".", "_date", "=", "self", ".", ...
Updated calendar to show the previous month.
[ "Updated", "calendar", "to", "show", "the", "previous", "month", "." ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3104-L3110
30,119
PySimpleGUI/PySimpleGUI
PySimpleGUI27.py
TKCalendar._next_month
def _next_month(self): """Update calendar to show the next month.""" self._canvas.place_forget() year, month = self._date.year, self._date.month self._date = self._date + self.timedelta( days=calendar.monthrange(year, month)[1] + 1) self._date = self.datetime(self._d...
python
def _next_month(self): """Update calendar to show the next month.""" self._canvas.place_forget() year, month = self._date.year, self._date.month self._date = self._date + self.timedelta( days=calendar.monthrange(year, month)[1] + 1) self._date = self.datetime(self._d...
[ "def", "_next_month", "(", "self", ")", ":", "self", ".", "_canvas", ".", "place_forget", "(", ")", "year", ",", "month", "=", "self", ".", "_date", ".", "year", ",", "self", ".", "_date", ".", "month", "self", ".", "_date", "=", "self", ".", "_dat...
Update calendar to show the next month.
[ "Update", "calendar", "to", "show", "the", "next", "month", "." ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3112-L3120
30,120
PySimpleGUI/PySimpleGUI
PySimpleGUI27.py
TKCalendar.selection
def selection(self): """Return a datetime representing the current selected date.""" if not self._selection: return None year, month = self._date.year, self._date.month return self.datetime(year, month, int(self._selection[0]))
python
def selection(self): """Return a datetime representing the current selected date.""" if not self._selection: return None year, month = self._date.year, self._date.month return self.datetime(year, month, int(self._selection[0]))
[ "def", "selection", "(", "self", ")", ":", "if", "not", "self", ".", "_selection", ":", "return", "None", "year", ",", "month", "=", "self", ".", "_date", ".", "year", ",", "self", ".", "_date", ".", "month", "return", "self", ".", "datetime", "(", ...
Return a datetime representing the current selected date.
[ "Return", "a", "datetime", "representing", "the", "current", "selected", "date", "." ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3125-L3131
30,121
PySimpleGUI/PySimpleGUI
PySimpleGUI27.py
Window.AddRow
def AddRow(self, *args): ''' Parms are a variable number of Elements ''' NumRows = len(self.Rows) # number of existing rows is our row number CurrentRowNumber = NumRows # this row's number CurrentRow = [] # start with a blank row and build up # ------------------------- Add t...
python
def AddRow(self, *args): ''' Parms are a variable number of Elements ''' NumRows = len(self.Rows) # number of existing rows is our row number CurrentRowNumber = NumRows # this row's number CurrentRow = [] # start with a blank row and build up # ------------------------- Add t...
[ "def", "AddRow", "(", "self", ",", "*", "args", ")", ":", "NumRows", "=", "len", "(", "self", ".", "Rows", ")", "# number of existing rows is our row number", "CurrentRowNumber", "=", "NumRows", "# this row's number", "CurrentRow", "=", "[", "]", "# start with a b...
Parms are a variable number of Elements
[ "Parms", "are", "a", "variable", "number", "of", "Elements" ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3638-L3649
30,122
PySimpleGUI/PySimpleGUI
DemoPrograms/Demo_Uno_Card_Game.py
Card.setColor
def setColor(self, color): '''Sets Card's color and escape code.''' if color == 'blue': self.color = 'blue' self.colorCode = self.colors['blue'] self.colorCodeDark = self.colors['dblue'] elif color == 'red': self.color = 'red' self.colo...
python
def setColor(self, color): '''Sets Card's color and escape code.''' if color == 'blue': self.color = 'blue' self.colorCode = self.colors['blue'] self.colorCodeDark = self.colors['dblue'] elif color == 'red': self.color = 'red' self.colo...
[ "def", "setColor", "(", "self", ",", "color", ")", ":", "if", "color", "==", "'blue'", ":", "self", ".", "color", "=", "'blue'", "self", ".", "colorCode", "=", "self", ".", "colors", "[", "'blue'", "]", "self", ".", "colorCodeDark", "=", "self", ".",...
Sets Card's color and escape code.
[ "Sets", "Card", "s", "color", "and", "escape", "code", "." ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Uno_Card_Game.py#L633-L655
30,123
PySimpleGUI/PySimpleGUI
DemoPrograms/Demo_Img_Viewer.py
get_img_data
def get_img_data(f, maxsize = (1200, 850), first = False): """Generate image data using PIL """ img = Image.open(f) img.thumbnail(maxsize) if first: # tkinter is inactive the first time bio = io.BytesIO() img.save(bio, format = "PNG") del img retur...
python
def get_img_data(f, maxsize = (1200, 850), first = False): """Generate image data using PIL """ img = Image.open(f) img.thumbnail(maxsize) if first: # tkinter is inactive the first time bio = io.BytesIO() img.save(bio, format = "PNG") del img retur...
[ "def", "get_img_data", "(", "f", ",", "maxsize", "=", "(", "1200", ",", "850", ")", ",", "first", "=", "False", ")", ":", "img", "=", "Image", ".", "open", "(", "f", ")", "img", ".", "thumbnail", "(", "maxsize", ")", "if", "first", ":", "# tkinte...
Generate image data using PIL
[ "Generate", "image", "data", "using", "PIL" ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Img_Viewer.py#L50-L60
30,124
PySimpleGUI/PySimpleGUI
DemoPrograms/Demo_Matplotlib_Ping_Graph.py
quiet_ping
def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, packet_size=PACKET_SIZE, path_finder=False): """ Same as verbose_ping, but the results are returned as tuple """ myStats = MyStats() # Reset the stats mySeqNumber = 0 # Starting value try: destIP = socket.g...
python
def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, packet_size=PACKET_SIZE, path_finder=False): """ Same as verbose_ping, but the results are returned as tuple """ myStats = MyStats() # Reset the stats mySeqNumber = 0 # Starting value try: destIP = socket.g...
[ "def", "quiet_ping", "(", "hostname", ",", "timeout", "=", "WAIT_TIMEOUT", ",", "count", "=", "NUM_PACKETS", ",", "packet_size", "=", "PACKET_SIZE", ",", "path_finder", "=", "False", ")", ":", "myStats", "=", "MyStats", "(", ")", "# Reset the stats", "mySeqNum...
Same as verbose_ping, but the results are returned as tuple
[ "Same", "as", "verbose_ping", "but", "the", "results", "are", "returned", "as", "tuple" ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Matplotlib_Ping_Graph.py#L527-L570
30,125
PySimpleGUI/PySimpleGUI
DemoPrograms/Demo_DOC_Viewer_PIL.py
get_page
def get_page(pno, zoom = False, max_size = None, first = False): """Return a PNG image for a document page number. """ dlist = dlist_tab[pno] # get display list of page number if not dlist: # create if not yet there dlist_tab[pno] = doc[pno].getDisplayList() dlist = dlist_ta...
python
def get_page(pno, zoom = False, max_size = None, first = False): """Return a PNG image for a document page number. """ dlist = dlist_tab[pno] # get display list of page number if not dlist: # create if not yet there dlist_tab[pno] = doc[pno].getDisplayList() dlist = dlist_ta...
[ "def", "get_page", "(", "pno", ",", "zoom", "=", "False", ",", "max_size", "=", "None", ",", "first", "=", "False", ")", ":", "dlist", "=", "dlist_tab", "[", "pno", "]", "# get display list of page number", "if", "not", "dlist", ":", "# create if not yet the...
Return a PNG image for a document page number.
[ "Return", "a", "PNG", "image", "for", "a", "document", "page", "number", "." ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_DOC_Viewer_PIL.py#L75-L118
30,126
PySimpleGUI/PySimpleGUI
DemoPrograms/Demo_Conways_Game_of_Life.py
GameOfLife.play
def play(self): """ Play Conway's Game of Life. """ # Write the initial configuration to file. self.t = 1 # Current time level while self.t <= self.T: # Evolve! # print( "At time level %d" % t) # Loop over each cell of the grid and apply Conway's rules. ...
python
def play(self): """ Play Conway's Game of Life. """ # Write the initial configuration to file. self.t = 1 # Current time level while self.t <= self.T: # Evolve! # print( "At time level %d" % t) # Loop over each cell of the grid and apply Conway's rules. ...
[ "def", "play", "(", "self", ")", ":", "# Write the initial configuration to file.", "self", ".", "t", "=", "1", "# Current time level", "while", "self", ".", "t", "<=", "self", ".", "T", ":", "# Evolve!", "# print( \"At time level %d\" % t)", "# Loop over each cell of...
Play Conway's Game of Life.
[ "Play", "Conway", "s", "Game", "of", "Life", "." ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Conways_Game_of_Life.py#L69-L97
30,127
PySimpleGUI/PySimpleGUI
DemoPrograms/Demo_Desktop_Widget_psutil_Dashboard.py
human_size
def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']): """ Returns a human readable string reprentation of bytes""" return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])
python
def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']): """ Returns a human readable string reprentation of bytes""" return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])
[ "def", "human_size", "(", "bytes", ",", "units", "=", "[", "' bytes'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", ",", "'EB'", "]", ")", ":", "return", "str", "(", "bytes", ")", "+", "units", "[", "0", "]", "if", "bytes", ...
Returns a human readable string reprentation of bytes
[ "Returns", "a", "human", "readable", "string", "reprentation", "of", "bytes" ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/Demo_Desktop_Widget_psutil_Dashboard.py#L51-L53
30,128
PySimpleGUI/PySimpleGUI
PySimpleGUIWeb/Demo Programs/widgets_overview_app.py
MyApp.list_view_on_selected
def list_view_on_selected(self, widget, selected_item_key): """ The selection event of the listView, returns a key of the clicked event. You can retrieve the item rapidly """ self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text())
python
def list_view_on_selected(self, widget, selected_item_key): """ The selection event of the listView, returns a key of the clicked event. You can retrieve the item rapidly """ self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text())
[ "def", "list_view_on_selected", "(", "self", ",", "widget", ",", "selected_item_key", ")", ":", "self", ".", "lbl", ".", "set_text", "(", "'List selection: '", "+", "self", ".", "listView", ".", "children", "[", "selected_item_key", "]", ".", "get_text", "(", ...
The selection event of the listView, returns a key of the clicked event. You can retrieve the item rapidly
[ "The", "selection", "event", "of", "the", "listView", "returns", "a", "key", "of", "the", "clicked", "event", ".", "You", "can", "retrieve", "the", "item", "rapidly" ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/Demo Programs/widgets_overview_app.py#L281-L285
30,129
PySimpleGUI/PySimpleGUI
DemoPrograms/ping.py
receive_one_ping
def receive_one_ping(mySocket, myID, timeout): """ Receive the ping from the socket. Timeout = in ms """ timeLeft = timeout/1000 while True: # Loop while waiting for packet or timeout startedSelect = default_timer() whatReady = select.select([mySocket], [], [], timeLeft) how...
python
def receive_one_ping(mySocket, myID, timeout): """ Receive the ping from the socket. Timeout = in ms """ timeLeft = timeout/1000 while True: # Loop while waiting for packet or timeout startedSelect = default_timer() whatReady = select.select([mySocket], [], [], timeLeft) how...
[ "def", "receive_one_ping", "(", "mySocket", ",", "myID", ",", "timeout", ")", ":", "timeLeft", "=", "timeout", "/", "1000", "while", "True", ":", "# Loop while waiting for packet or timeout", "startedSelect", "=", "default_timer", "(", ")", "whatReady", "=", "sele...
Receive the ping from the socket. Timeout = in ms
[ "Receive", "the", "ping", "from", "the", "socket", ".", "Timeout", "=", "in", "ms" ]
08184197f5bd4580ab5e5aca28bdda30f87b86fc
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/DemoPrograms/ping.py#L390-L427
30,130
tensorflow/hub
tensorflow_hub/module_spec.py
ModuleSpec.export
def export(self, path, _sentinel=None, # pylint: disable=invalid-name checkpoint_path=None, name_transform_fn=None): """Exports a ModuleSpec with weights taken from a checkpoint. This is an helper to export modules directly from a ModuleSpec without having to create a session and set the vari...
python
def export(self, path, _sentinel=None, # pylint: disable=invalid-name checkpoint_path=None, name_transform_fn=None): """Exports a ModuleSpec with weights taken from a checkpoint. This is an helper to export modules directly from a ModuleSpec without having to create a session and set the vari...
[ "def", "export", "(", "self", ",", "path", ",", "_sentinel", "=", "None", ",", "# pylint: disable=invalid-name", "checkpoint_path", "=", "None", ",", "name_transform_fn", "=", "None", ")", ":", "from", "tensorflow_hub", ".", "module", "import", "export_module_spec...
Exports a ModuleSpec with weights taken from a checkpoint. This is an helper to export modules directly from a ModuleSpec without having to create a session and set the variables to the intended values. Example usage: ```python spec = hub.create_module_spec(module_fn) spec.export("/path/t...
[ "Exports", "a", "ModuleSpec", "with", "weights", "taken", "from", "a", "checkpoint", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module_spec.py#L41-L77
30,131
tensorflow/hub
tensorflow_hub/module_spec.py
ModuleSpec.get_attached_message
def get_attached_message(self, key, message_type, tags=None, required=False): """Returns the message attached to the module under the given key, or None. Module publishers can attach protocol messages to modules at creation time to provide module consumers with additional information, e.g., on module u...
python
def get_attached_message(self, key, message_type, tags=None, required=False): """Returns the message attached to the module under the given key, or None. Module publishers can attach protocol messages to modules at creation time to provide module consumers with additional information, e.g., on module u...
[ "def", "get_attached_message", "(", "self", ",", "key", ",", "message_type", ",", "tags", "=", "None", ",", "required", "=", "False", ")", ":", "attached_bytes", "=", "self", ".", "_get_attached_bytes", "(", "key", ",", "tags", ")", "if", "attached_bytes", ...
Returns the message attached to the module under the given key, or None. Module publishers can attach protocol messages to modules at creation time to provide module consumers with additional information, e.g., on module usage or provenance (see see hub.attach_message()). A typical use would be to stor...
[ "Returns", "the", "message", "attached", "to", "the", "module", "under", "the", "given", "key", "or", "None", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module_spec.py#L129-L169
30,132
tensorflow/hub
examples/image_retraining/retrain.py
create_image_lists
def create_image_lists(image_dir, testing_percentage, validation_percentage): """Builds a list of training images from the file system. Analyzes the sub folders in the image directory, splits them into stable training, testing, and validation sets, and returns a data structure describing the lists of images fo...
python
def create_image_lists(image_dir, testing_percentage, validation_percentage): """Builds a list of training images from the file system. Analyzes the sub folders in the image directory, splits them into stable training, testing, and validation sets, and returns a data structure describing the lists of images fo...
[ "def", "create_image_lists", "(", "image_dir", ",", "testing_percentage", ",", "validation_percentage", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "image_dir", ")", ":", "tf", ".", "logging", ".", "error", "(", "\"Image directory '\"", "+",...
Builds a list of training images from the file system. Analyzes the sub folders in the image directory, splits them into stable training, testing, and validation sets, and returns a data structure describing the lists of images for each label and their paths. Args: image_dir: String path to a folder conta...
[ "Builds", "a", "list", "of", "training", "images", "from", "the", "file", "system", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L147-L234
30,133
tensorflow/hub
examples/image_retraining/retrain.py
get_image_path
def get_image_path(image_lists, label_name, index, image_dir, category): """Returns a path to an image for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image for. index: Int offset of the image we want. This wil...
python
def get_image_path(image_lists, label_name, index, image_dir, category): """Returns a path to an image for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image for. index: Int offset of the image we want. This wil...
[ "def", "get_image_path", "(", "image_lists", ",", "label_name", ",", "index", ",", "image_dir", ",", "category", ")", ":", "if", "label_name", "not", "in", "image_lists", ":", "tf", ".", "logging", ".", "fatal", "(", "'Label does not exist %s.'", ",", "label_n...
Returns a path to an image for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image for. index: Int offset of the image we want. This will be moduloed by the available number of images for the label, so it can b...
[ "Returns", "a", "path", "to", "an", "image", "for", "a", "label", "at", "the", "given", "index", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L237-L267
30,134
tensorflow/hub
examples/image_retraining/retrain.py
get_bottleneck_path
def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category, module_name): """Returns a path to a bottleneck file for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image f...
python
def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category, module_name): """Returns a path to a bottleneck file for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image f...
[ "def", "get_bottleneck_path", "(", "image_lists", ",", "label_name", ",", "index", ",", "bottleneck_dir", ",", "category", ",", "module_name", ")", ":", "module_name", "=", "(", "module_name", ".", "replace", "(", "'://'", ",", "'~'", ")", "# URL scheme.", "."...
Returns a path to a bottleneck file for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be moduloed by the available number of images for the label...
[ "Returns", "a", "path", "to", "a", "bottleneck", "file", "for", "a", "label", "at", "the", "given", "index", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L270-L291
30,135
tensorflow/hub
examples/image_retraining/retrain.py
create_module_graph
def create_module_graph(module_spec): """Creates a graph and loads Hub Module into it. Args: module_spec: the hub.ModuleSpec for the image module being used. Returns: graph: the tf.Graph that was created. bottleneck_tensor: the bottleneck values output by the module. resized_input_tensor: the in...
python
def create_module_graph(module_spec): """Creates a graph and loads Hub Module into it. Args: module_spec: the hub.ModuleSpec for the image module being used. Returns: graph: the tf.Graph that was created. bottleneck_tensor: the bottleneck values output by the module. resized_input_tensor: the in...
[ "def", "create_module_graph", "(", "module_spec", ")", ":", "height", ",", "width", "=", "hub", ".", "get_expected_image_size", "(", "module_spec", ")", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", "as", "graph", ":", "resized_input_ten...
Creates a graph and loads Hub Module into it. Args: module_spec: the hub.ModuleSpec for the image module being used. Returns: graph: the tf.Graph that was created. bottleneck_tensor: the bottleneck values output by the module. resized_input_tensor: the input images, resized as expected by the modu...
[ "Creates", "a", "graph", "and", "loads", "Hub", "Module", "into", "it", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L294-L314
30,136
tensorflow/hub
examples/image_retraining/retrain.py
run_bottleneck_on_image
def run_bottleneck_on_image(sess, image_data, image_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): """Runs inference on an image to extract the 'bottleneck' summary layer. Args: sess: Current active TensorFlow Session. im...
python
def run_bottleneck_on_image(sess, image_data, image_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): """Runs inference on an image to extract the 'bottleneck' summary layer. Args: sess: Current active TensorFlow Session. im...
[ "def", "run_bottleneck_on_image", "(", "sess", ",", "image_data", ",", "image_data_tensor", ",", "decoded_image_tensor", ",", "resized_input_tensor", ",", "bottleneck_tensor", ")", ":", "# First decode the JPEG image, resize it, and rescale the pixel values.", "resized_input_values...
Runs inference on an image to extract the 'bottleneck' summary layer. Args: sess: Current active TensorFlow Session. image_data: String of raw JPEG data. image_data_tensor: Input data layer in the graph. decoded_image_tensor: Output of initial image resizing and preprocessing. resized_input_tenso...
[ "Runs", "inference", "on", "an", "image", "to", "extract", "the", "bottleneck", "summary", "layer", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L317-L340
30,137
tensorflow/hub
examples/image_retraining/retrain.py
create_bottleneck_file
def create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): """Create a single bottleneck file.""" tf.logging....
python
def create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): """Create a single bottleneck file.""" tf.logging....
[ "def", "create_bottleneck_file", "(", "bottleneck_path", ",", "image_lists", ",", "label_name", ",", "index", ",", "image_dir", ",", "category", ",", "sess", ",", "jpeg_data_tensor", ",", "decoded_image_tensor", ",", "resized_input_tensor", ",", "bottleneck_tensor", "...
Create a single bottleneck file.
[ "Create", "a", "single", "bottleneck", "file", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L353-L373
30,138
tensorflow/hub
examples/image_retraining/retrain.py
get_or_create_bottleneck
def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name): """Retrieves or calculates bottl...
python
def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name): """Retrieves or calculates bottl...
[ "def", "get_or_create_bottleneck", "(", "sess", ",", "image_lists", ",", "label_name", ",", "index", ",", "image_dir", ",", "category", ",", "bottleneck_dir", ",", "jpeg_data_tensor", ",", "decoded_image_tensor", ",", "resized_input_tensor", ",", "bottleneck_tensor", ...
Retrieves or calculates bottleneck values for an image. If a cached version of the bottleneck data exists on-disk, return that, otherwise calculate the data and save it to disk for future use. Args: sess: The current active TensorFlow Session. image_lists: OrderedDict of training images for each label. ...
[ "Retrieves", "or", "calculates", "bottleneck", "values", "for", "an", "image", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L376-L434
30,139
tensorflow/hub
examples/image_retraining/retrain.py
cache_bottlenecks
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name): """Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read th...
python
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name): """Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read th...
[ "def", "cache_bottlenecks", "(", "sess", ",", "image_lists", ",", "image_dir", ",", "bottleneck_dir", ",", "jpeg_data_tensor", ",", "decoded_image_tensor", ",", "resized_input_tensor", ",", "bottleneck_tensor", ",", "module_name", ")", ":", "how_many_bottlenecks", "=", ...
Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read the same image multiple times (if there are no distortions applied during training) it can speed things up a lot if we calculate the bottleneck layer values once for each image during preprocessing, and then ...
[ "Ensures", "all", "the", "training", "testing", "and", "validation", "bottlenecks", "are", "cached", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L437-L478
30,140
tensorflow/hub
examples/image_retraining/retrain.py
get_random_cached_bottlenecks
def get_random_cached_bottlenecks(sess, image_lists, how_many, category, bottleneck_dir, image_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name): """Retrieves bottlene...
python
def get_random_cached_bottlenecks(sess, image_lists, how_many, category, bottleneck_dir, image_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name): """Retrieves bottlene...
[ "def", "get_random_cached_bottlenecks", "(", "sess", ",", "image_lists", ",", "how_many", ",", "category", ",", "bottleneck_dir", ",", "image_dir", ",", "jpeg_data_tensor", ",", "decoded_image_tensor", ",", "resized_input_tensor", ",", "bottleneck_tensor", ",", "module_...
Retrieves bottleneck values for cached images. If no distortions are being applied, this function can retrieve the cached bottleneck values directly from disk for images. It picks a random set of images from the specified category. Args: sess: Current TensorFlow Session. image_lists: OrderedDict of tr...
[ "Retrieves", "bottleneck", "values", "for", "cached", "images", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L481-L544
30,141
tensorflow/hub
examples/image_retraining/retrain.py
get_random_distorted_bottlenecks
def get_random_distorted_bottlenecks( sess, image_lists, how_many, category, image_dir, input_jpeg_tensor, distorted_image, resized_input_tensor, bottleneck_tensor): """Retrieves bottleneck values for training images, after distortions. If we're training with distortions like crops, scales, or flips, we ha...
python
def get_random_distorted_bottlenecks( sess, image_lists, how_many, category, image_dir, input_jpeg_tensor, distorted_image, resized_input_tensor, bottleneck_tensor): """Retrieves bottleneck values for training images, after distortions. If we're training with distortions like crops, scales, or flips, we ha...
[ "def", "get_random_distorted_bottlenecks", "(", "sess", ",", "image_lists", ",", "how_many", ",", "category", ",", "image_dir", ",", "input_jpeg_tensor", ",", "distorted_image", ",", "resized_input_tensor", ",", "bottleneck_tensor", ")", ":", "class_count", "=", "len"...
Retrieves bottleneck values for training images, after distortions. If we're training with distortions like crops, scales, or flips, we have to recalculate the full model for every image, and so we can't use cached bottleneck values. Instead we find random images for the requested category, run them through th...
[ "Retrieves", "bottleneck", "values", "for", "training", "images", "after", "distortions", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L547-L596
30,142
tensorflow/hub
examples/image_retraining/retrain.py
add_input_distortions
def add_input_distortions(flip_left_right, random_crop, random_scale, random_brightness, module_spec): """Creates the operations to apply the specified distortions. During training it can help to improve the results if we run the images through simple distortions like crops, scales, and...
python
def add_input_distortions(flip_left_right, random_crop, random_scale, random_brightness, module_spec): """Creates the operations to apply the specified distortions. During training it can help to improve the results if we run the images through simple distortions like crops, scales, and...
[ "def", "add_input_distortions", "(", "flip_left_right", ",", "random_crop", ",", "random_scale", ",", "random_brightness", ",", "module_spec", ")", ":", "input_height", ",", "input_width", "=", "hub", ".", "get_expected_image_size", "(", "module_spec", ")", "input_dep...
Creates the operations to apply the specified distortions. During training it can help to improve the results if we run the images through simple distortions like crops, scales, and flips. These reflect the kind of variations we expect in the real world, and so can help train the model to cope with natural dat...
[ "Creates", "the", "operations", "to", "apply", "the", "specified", "distortions", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L617-L706
30,143
tensorflow/hub
examples/image_retraining/retrain.py
add_final_retrain_ops
def add_final_retrain_ops(class_count, final_tensor_name, bottleneck_tensor, quantize_layer, is_training): """Adds a new softmax and fully-connected layer for training and eval. We need to retrain the top layer to identify our new classes, so this function adds the right operations to t...
python
def add_final_retrain_ops(class_count, final_tensor_name, bottleneck_tensor, quantize_layer, is_training): """Adds a new softmax and fully-connected layer for training and eval. We need to retrain the top layer to identify our new classes, so this function adds the right operations to t...
[ "def", "add_final_retrain_ops", "(", "class_count", ",", "final_tensor_name", ",", "bottleneck_tensor", ",", "quantize_layer", ",", "is_training", ")", ":", "batch_size", ",", "bottleneck_tensor_size", "=", "bottleneck_tensor", ".", "get_shape", "(", ")", ".", "as_lis...
Adds a new softmax and fully-connected layer for training and eval. We need to retrain the top layer to identify our new classes, so this function adds the right operations to the graph, along with some variables to hold the weights, and then sets up all the gradients for the backward pass. The set up for the...
[ "Adds", "a", "new", "softmax", "and", "fully", "-", "connected", "layer", "for", "training", "and", "eval", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L722-L804
30,144
tensorflow/hub
examples/image_retraining/retrain.py
add_evaluation_step
def add_evaluation_step(result_tensor, ground_truth_tensor): """Inserts the operations we need to evaluate the accuracy of our results. Args: result_tensor: The new final node that produces results. ground_truth_tensor: The node we feed ground truth data into. Returns: Tuple of (evaluation step,...
python
def add_evaluation_step(result_tensor, ground_truth_tensor): """Inserts the operations we need to evaluate the accuracy of our results. Args: result_tensor: The new final node that produces results. ground_truth_tensor: The node we feed ground truth data into. Returns: Tuple of (evaluation step,...
[ "def", "add_evaluation_step", "(", "result_tensor", ",", "ground_truth_tensor", ")", ":", "with", "tf", ".", "name_scope", "(", "'accuracy'", ")", ":", "with", "tf", ".", "name_scope", "(", "'correct_prediction'", ")", ":", "prediction", "=", "tf", ".", "argma...
Inserts the operations we need to evaluate the accuracy of our results. Args: result_tensor: The new final node that produces results. ground_truth_tensor: The node we feed ground truth data into. Returns: Tuple of (evaluation step, prediction).
[ "Inserts", "the", "operations", "we", "need", "to", "evaluate", "the", "accuracy", "of", "our", "results", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L807-L825
30,145
tensorflow/hub
examples/image_retraining/retrain.py
run_final_eval
def run_final_eval(train_session, module_spec, class_count, image_lists, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor): """Runs a final evaluation on an eval graph using the test data set. Args: train_session: Session for the train graph ...
python
def run_final_eval(train_session, module_spec, class_count, image_lists, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor): """Runs a final evaluation on an eval graph using the test data set. Args: train_session: Session for the train graph ...
[ "def", "run_final_eval", "(", "train_session", ",", "module_spec", ",", "class_count", ",", "image_lists", ",", "jpeg_data_tensor", ",", "decoded_image_tensor", ",", "resized_image_tensor", ",", "bottleneck_tensor", ")", ":", "test_bottlenecks", ",", "test_ground_truth", ...
Runs a final evaluation on an eval graph using the test data set. Args: train_session: Session for the train graph with the tensors below. module_spec: The hub.ModuleSpec for the image module being used. class_count: Number of classes image_lists: OrderedDict of training images for each label. jp...
[ "Runs", "a", "final", "evaluation", "on", "an", "eval", "graph", "using", "the", "test", "data", "set", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L828-L867
30,146
tensorflow/hub
examples/image_retraining/retrain.py
build_eval_session
def build_eval_session(module_spec, class_count): """Builds an restored eval session without train operations for exporting. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: Number of classes Returns: Eval session containing the restored eval graph. The bottlen...
python
def build_eval_session(module_spec, class_count): """Builds an restored eval session without train operations for exporting. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: Number of classes Returns: Eval session containing the restored eval graph. The bottlen...
[ "def", "build_eval_session", "(", "module_spec", ",", "class_count", ")", ":", "# If quantized, we need to create the correct eval graph for exporting.", "eval_graph", ",", "bottleneck_tensor", ",", "resized_input_tensor", ",", "wants_quantization", "=", "(", "create_module_graph...
Builds an restored eval session without train operations for exporting. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: Number of classes Returns: Eval session containing the restored eval graph. The bottleneck input, ground truth, eval step, and prediction tens...
[ "Builds", "an", "restored", "eval", "session", "without", "train", "operations", "for", "exporting", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L870-L901
30,147
tensorflow/hub
examples/image_retraining/retrain.py
save_graph_to_file
def save_graph_to_file(graph_file_name, module_spec, class_count): """Saves an graph to file, creating a valid quantized one if necessary.""" sess, _, _, _, _, _ = build_eval_session(module_spec, class_count) graph = sess.graph output_graph_def = tf.graph_util.convert_variables_to_constants( sess, graph....
python
def save_graph_to_file(graph_file_name, module_spec, class_count): """Saves an graph to file, creating a valid quantized one if necessary.""" sess, _, _, _, _, _ = build_eval_session(module_spec, class_count) graph = sess.graph output_graph_def = tf.graph_util.convert_variables_to_constants( sess, graph....
[ "def", "save_graph_to_file", "(", "graph_file_name", ",", "module_spec", ",", "class_count", ")", ":", "sess", ",", "_", ",", "_", ",", "_", ",", "_", ",", "_", "=", "build_eval_session", "(", "module_spec", ",", "class_count", ")", "graph", "=", "sess", ...
Saves an graph to file, creating a valid quantized one if necessary.
[ "Saves", "an", "graph", "to", "file", "creating", "a", "valid", "quantized", "one", "if", "necessary", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L904-L913
30,148
tensorflow/hub
examples/image_retraining/retrain.py
add_jpeg_decoding
def add_jpeg_decoding(module_spec): """Adds operations that perform JPEG decoding and resizing to the graph.. Args: module_spec: The hub.ModuleSpec for the image module being used. Returns: Tensors for the node to feed JPEG data into, and the output of the preprocessing steps. """ input_height...
python
def add_jpeg_decoding(module_spec): """Adds operations that perform JPEG decoding and resizing to the graph.. Args: module_spec: The hub.ModuleSpec for the image module being used. Returns: Tensors for the node to feed JPEG data into, and the output of the preprocessing steps. """ input_height...
[ "def", "add_jpeg_decoding", "(", "module_spec", ")", ":", "input_height", ",", "input_width", "=", "hub", ".", "get_expected_image_size", "(", "module_spec", ")", "input_depth", "=", "hub", ".", "get_num_image_channels", "(", "module_spec", ")", "jpeg_data", "=", ...
Adds operations that perform JPEG decoding and resizing to the graph.. Args: module_spec: The hub.ModuleSpec for the image module being used. Returns: Tensors for the node to feed JPEG data into, and the output of the preprocessing steps.
[ "Adds", "operations", "that", "perform", "JPEG", "decoding", "and", "resizing", "to", "the", "graph", ".." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L926-L948
30,149
tensorflow/hub
examples/image_retraining/retrain.py
export_model
def export_model(module_spec, class_count, saved_model_dir): """Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables. """ # The SavedModel should...
python
def export_model(module_spec, class_count, saved_model_dir): """Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables. """ # The SavedModel should...
[ "def", "export_model", "(", "module_spec", ",", "class_count", ",", "saved_model_dir", ")", ":", "# The SavedModel should hold the eval graph.", "sess", ",", "in_image", ",", "_", ",", "_", ",", "_", ",", "_", "=", "build_eval_session", "(", "module_spec", ",", ...
Exports model for serving. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: The number of classes. saved_model_dir: Directory in which to save exported model and variables.
[ "Exports", "model", "for", "serving", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L951-L968
30,150
tensorflow/hub
examples/image_retraining/retrain.py
logging_level_verbosity
def logging_level_verbosity(logging_verbosity): """Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing logging level: 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL' """ name_to_level = { 'FATAL': tf.logging.FATAL, 'ERROR': tf.logging.ERROR, ...
python
def logging_level_verbosity(logging_verbosity): """Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing logging level: 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL' """ name_to_level = { 'FATAL': tf.logging.FATAL, 'ERROR': tf.logging.ERROR, ...
[ "def", "logging_level_verbosity", "(", "logging_verbosity", ")", ":", "name_to_level", "=", "{", "'FATAL'", ":", "tf", ".", "logging", ".", "FATAL", ",", "'ERROR'", ":", "tf", ".", "logging", ".", "ERROR", ",", "'WARN'", ":", "tf", ".", "logging", ".", "...
Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing logging level: 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'
[ "Converts", "logging_level", "into", "TensorFlow", "logging", "verbosity", "value" ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L971-L990
30,151
tensorflow/hub
tensorflow_hub/image_util.py
get_image_module_info
def get_image_module_info(module_or_spec, required=False): """Returns the module's attached ImageModuleInfo message, or None.""" return module_or_spec.get_attached_message( IMAGE_MODULE_INFO_KEY, ImageModuleInfo, required=required)
python
def get_image_module_info(module_or_spec, required=False): """Returns the module's attached ImageModuleInfo message, or None.""" return module_or_spec.get_attached_message( IMAGE_MODULE_INFO_KEY, ImageModuleInfo, required=required)
[ "def", "get_image_module_info", "(", "module_or_spec", ",", "required", "=", "False", ")", ":", "return", "module_or_spec", ".", "get_attached_message", "(", "IMAGE_MODULE_INFO_KEY", ",", "ImageModuleInfo", ",", "required", "=", "required", ")" ]
Returns the module's attached ImageModuleInfo message, or None.
[ "Returns", "the", "module", "s", "attached", "ImageModuleInfo", "message", "or", "None", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/image_util.py#L39-L42
30,152
tensorflow/hub
tensorflow_hub/image_util.py
get_num_image_channels
def get_num_image_channels(module_or_spec, signature=None, input_name=None): """Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleS...
python
def get_num_image_channels(module_or_spec, signature=None, input_name=None): """Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleS...
[ "def", "get_num_image_channels", "(", "module_or_spec", ",", "signature", "=", "None", ",", "input_name", "=", "None", ")", ":", "if", "input_name", "is", "None", ":", "input_name", "=", "\"images\"", "input_info_dict", "=", "module_or_spec", ".", "get_input_info_...
Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleSpec that accepts image inputs. signature: a string with the key of the signatu...
[ "Returns", "expected", "num_channels", "dimensions", "of", "an", "image", "input", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/image_util.py#L89-L125
30,153
tensorflow/hub
tensorflow_hub/tensor_info.py
_parse_tensor_info_proto
def _parse_tensor_info_proto(tensor_info): """Returns a ParsedTensorInfo instance from a TensorInfo proto.""" encoding = tensor_info.WhichOneof("encoding") dtype = tf.DType(tensor_info.dtype) shape = tf.TensorShape(tensor_info.tensor_shape) if encoding == "name": return ParsedTensorInfo(dtype=dtype, shape...
python
def _parse_tensor_info_proto(tensor_info): """Returns a ParsedTensorInfo instance from a TensorInfo proto.""" encoding = tensor_info.WhichOneof("encoding") dtype = tf.DType(tensor_info.dtype) shape = tf.TensorShape(tensor_info.tensor_shape) if encoding == "name": return ParsedTensorInfo(dtype=dtype, shape...
[ "def", "_parse_tensor_info_proto", "(", "tensor_info", ")", ":", "encoding", "=", "tensor_info", ".", "WhichOneof", "(", "\"encoding\"", ")", "dtype", "=", "tf", ".", "DType", "(", "tensor_info", ".", "dtype", ")", "shape", "=", "tf", ".", "TensorShape", "("...
Returns a ParsedTensorInfo instance from a TensorInfo proto.
[ "Returns", "a", "ParsedTensorInfo", "instance", "from", "a", "TensorInfo", "proto", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L65-L75
30,154
tensorflow/hub
tensorflow_hub/tensor_info.py
_is_sparse
def _is_sparse(x): """Returns whether x is a SparseTensor or a parsed sparse tensor info.""" return ( isinstance(x, (tf.SparseTensor, tf_v1.SparseTensorValue)) or (hasattr(x, "is_sparse") and x.is_sparse))
python
def _is_sparse(x): """Returns whether x is a SparseTensor or a parsed sparse tensor info.""" return ( isinstance(x, (tf.SparseTensor, tf_v1.SparseTensorValue)) or (hasattr(x, "is_sparse") and x.is_sparse))
[ "def", "_is_sparse", "(", "x", ")", ":", "return", "(", "isinstance", "(", "x", ",", "(", "tf", ".", "SparseTensor", ",", "tf_v1", ".", "SparseTensorValue", ")", ")", "or", "(", "hasattr", "(", "x", ",", "\"is_sparse\"", ")", "and", "x", ".", "is_spa...
Returns whether x is a SparseTensor or a parsed sparse tensor info.
[ "Returns", "whether", "x", "is", "a", "SparseTensor", "or", "a", "parsed", "sparse", "tensor", "info", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L97-L101
30,155
tensorflow/hub
tensorflow_hub/tensor_info.py
_convert_to_compatible_tensor
def _convert_to_compatible_tensor(value, target, error_prefix): """Converts `value` into a tensor that can be feed into `tensor_info`. Args: value: A value to convert into Tensor or SparseTensor. target: An object returned by `parse_tensor_info_map`. error_prefix: A string to prefix on raised TypeError...
python
def _convert_to_compatible_tensor(value, target, error_prefix): """Converts `value` into a tensor that can be feed into `tensor_info`. Args: value: A value to convert into Tensor or SparseTensor. target: An object returned by `parse_tensor_info_map`. error_prefix: A string to prefix on raised TypeError...
[ "def", "_convert_to_compatible_tensor", "(", "value", ",", "target", ",", "error_prefix", ")", ":", "try", ":", "tensor", "=", "tf_v1", ".", "convert_to_tensor_or_indexed_slices", "(", "value", ",", "target", ".", "dtype", ")", "except", "TypeError", "as", "e", ...
Converts `value` into a tensor that can be feed into `tensor_info`. Args: value: A value to convert into Tensor or SparseTensor. target: An object returned by `parse_tensor_info_map`. error_prefix: A string to prefix on raised TypeErrors. Raises: TypeError: If it fails to convert. Returns: ...
[ "Converts", "value", "into", "a", "tensor", "that", "can", "be", "feed", "into", "tensor_info", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L104-L130
30,156
tensorflow/hub
tensorflow_hub/tensor_info.py
convert_dict_to_compatible_tensor
def convert_dict_to_compatible_tensor(values, targets): """Converts dict `values` in tensors that are compatible with `targets`. Args: values: A dict to objects to convert with same keys as `targets`. targets: A dict returned by `parse_tensor_info_map`. Returns: A map with the same keys as `values` ...
python
def convert_dict_to_compatible_tensor(values, targets): """Converts dict `values` in tensors that are compatible with `targets`. Args: values: A dict to objects to convert with same keys as `targets`. targets: A dict returned by `parse_tensor_info_map`. Returns: A map with the same keys as `values` ...
[ "def", "convert_dict_to_compatible_tensor", "(", "values", ",", "targets", ")", ":", "result", "=", "{", "}", "for", "key", ",", "value", "in", "sorted", "(", "values", ".", "items", "(", ")", ")", ":", "result", "[", "key", "]", "=", "_convert_to_compat...
Converts dict `values` in tensors that are compatible with `targets`. Args: values: A dict to objects to convert with same keys as `targets`. targets: A dict returned by `parse_tensor_info_map`. Returns: A map with the same keys as `values` but values converted into Tensor/SparseTensors that can b...
[ "Converts", "dict", "values", "in", "tensors", "that", "are", "compatible", "with", "targets", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L133-L151
30,157
tensorflow/hub
tensorflow_hub/tensor_info.py
build_input_map
def build_input_map(protomap, inputs): """Builds a map to feed tensors in `protomap` using `inputs`. Args: protomap: A proto map<string,TensorInfo>. inputs: A map with same keys as `protomap` of Tensors and SparseTensors. Returns: A map from nodes refered by TensorInfo protos to corresponding input ...
python
def build_input_map(protomap, inputs): """Builds a map to feed tensors in `protomap` using `inputs`. Args: protomap: A proto map<string,TensorInfo>. inputs: A map with same keys as `protomap` of Tensors and SparseTensors. Returns: A map from nodes refered by TensorInfo protos to corresponding input ...
[ "def", "build_input_map", "(", "protomap", ",", "inputs", ")", ":", "if", "set", "(", "protomap", ".", "keys", "(", ")", ")", "!=", "set", "(", "inputs", ".", "keys", "(", ")", ")", ":", "raise", "ValueError", "(", "\"build_input_map: keys do not match.\""...
Builds a map to feed tensors in `protomap` using `inputs`. Args: protomap: A proto map<string,TensorInfo>. inputs: A map with same keys as `protomap` of Tensors and SparseTensors. Returns: A map from nodes refered by TensorInfo protos to corresponding input tensors. Raises: ValueError: if a...
[ "Builds", "a", "map", "to", "feed", "tensors", "in", "protomap", "using", "inputs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L154-L183
30,158
tensorflow/hub
tensorflow_hub/tensor_info.py
build_output_map
def build_output_map(protomap, get_tensor_by_name): """Builds a map of tensors from `protomap` using `get_tensor_by_name`. Args: protomap: A proto map<string,TensorInfo>. get_tensor_by_name: A lambda that receives a tensor name and returns a Tensor instance. Returns: A map from string to Tenso...
python
def build_output_map(protomap, get_tensor_by_name): """Builds a map of tensors from `protomap` using `get_tensor_by_name`. Args: protomap: A proto map<string,TensorInfo>. get_tensor_by_name: A lambda that receives a tensor name and returns a Tensor instance. Returns: A map from string to Tenso...
[ "def", "build_output_map", "(", "protomap", ",", "get_tensor_by_name", ")", ":", "def", "get_output_from_tensor_info", "(", "tensor_info", ")", ":", "encoding", "=", "tensor_info", ".", "WhichOneof", "(", "\"encoding\"", ")", "if", "encoding", "==", "\"name\"", ":...
Builds a map of tensors from `protomap` using `get_tensor_by_name`. Args: protomap: A proto map<string,TensorInfo>. get_tensor_by_name: A lambda that receives a tensor name and returns a Tensor instance. Returns: A map from string to Tensor or SparseTensor instances built from `protomap` and...
[ "Builds", "a", "map", "of", "tensors", "from", "protomap", "using", "get_tensor_by_name", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L186-L217
30,159
tensorflow/hub
examples/text_embeddings/export.py
parse_line
def parse_line(line): """Parses a line of a text embedding file. Args: line: (str) One line of the text embedding file. Returns: A token string and its embedding vector in floats. """ columns = line.split() token = columns.pop(0) values = [float(column) for column in columns] return token, val...
python
def parse_line(line): """Parses a line of a text embedding file. Args: line: (str) One line of the text embedding file. Returns: A token string and its embedding vector in floats. """ columns = line.split() token = columns.pop(0) values = [float(column) for column in columns] return token, val...
[ "def", "parse_line", "(", "line", ")", ":", "columns", "=", "line", ".", "split", "(", ")", "token", "=", "columns", ".", "pop", "(", "0", ")", "values", "=", "[", "float", "(", "column", ")", "for", "column", "in", "columns", "]", "return", "token...
Parses a line of a text embedding file. Args: line: (str) One line of the text embedding file. Returns: A token string and its embedding vector in floats.
[ "Parses", "a", "line", "of", "a", "text", "embedding", "file", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L47-L59
30,160
tensorflow/hub
examples/text_embeddings/export.py
load
def load(file_path, parse_line_fn): """Loads a text embedding into memory as a numpy matrix. Args: file_path: Path to the text embedding file. parse_line_fn: callback function to parse each file line. Returns: A tuple of (list of vocabulary tokens, numpy matrix of embedding vectors). Raises: ...
python
def load(file_path, parse_line_fn): """Loads a text embedding into memory as a numpy matrix. Args: file_path: Path to the text embedding file. parse_line_fn: callback function to parse each file line. Returns: A tuple of (list of vocabulary tokens, numpy matrix of embedding vectors). Raises: ...
[ "def", "load", "(", "file_path", ",", "parse_line_fn", ")", ":", "vocabulary", "=", "[", "]", "embeddings", "=", "[", "]", "embeddings_dim", "=", "None", "for", "line", "in", "tf", ".", "gfile", ".", "GFile", "(", "file_path", ")", ":", "token", ",", ...
Loads a text embedding into memory as a numpy matrix. Args: file_path: Path to the text embedding file. parse_line_fn: callback function to parse each file line. Returns: A tuple of (list of vocabulary tokens, numpy matrix of embedding vectors). Raises: ValueError: if the data in the sstable is...
[ "Loads", "a", "text", "embedding", "into", "memory", "as", "a", "numpy", "matrix", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L62-L90
30,161
tensorflow/hub
examples/text_embeddings/export.py
make_module_spec
def make_module_spec(vocabulary_file, vocab_size, embeddings_dim, num_oov_buckets, preprocess_text): """Makes a module spec to simply perform token to embedding lookups. Input of this module is a 1-D list of string tokens. For T tokens input and an M dimensional embedding table, the lookup r...
python
def make_module_spec(vocabulary_file, vocab_size, embeddings_dim, num_oov_buckets, preprocess_text): """Makes a module spec to simply perform token to embedding lookups. Input of this module is a 1-D list of string tokens. For T tokens input and an M dimensional embedding table, the lookup r...
[ "def", "make_module_spec", "(", "vocabulary_file", ",", "vocab_size", ",", "embeddings_dim", ",", "num_oov_buckets", ",", "preprocess_text", ")", ":", "def", "module_fn", "(", ")", ":", "\"\"\"Spec function for a token embedding module.\"\"\"", "tokens", "=", "tf", ".",...
Makes a module spec to simply perform token to embedding lookups. Input of this module is a 1-D list of string tokens. For T tokens input and an M dimensional embedding table, the lookup result is a [T, M] shaped Tensor. Args: vocabulary_file: Text file where each line is a key in the vocabulary. vocab_...
[ "Makes", "a", "module", "spec", "to", "simply", "perform", "token", "to", "embedding", "lookups", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L93-L177
30,162
tensorflow/hub
examples/text_embeddings/export.py
export
def export(export_path, vocabulary, embeddings, num_oov_buckets, preprocess_text): """Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the fi...
python
def export(export_path, vocabulary, embeddings, num_oov_buckets, preprocess_text): """Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the fi...
[ "def", "export", "(", "export_path", ",", "vocabulary", ",", "embeddings", ",", "num_oov_buckets", ",", "preprocess_text", ")", ":", "# Write temporary vocab file for module construction.", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "vocabulary_file", "=", "...
Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the first N rows are the M dimensional embeddings for the respective tokens and the next K ro...
[ "Exports", "a", "TF", "-", "Hub", "module", "that", "performs", "embedding", "lookups", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L180-L219
30,163
tensorflow/hub
examples/text_embeddings/export.py
maybe_append_oov_vectors
def maybe_append_oov_vectors(embeddings, num_oov_buckets): """Adds zero vectors for oov buckets if num_oov_buckets > 0. Since we are assigning zero vectors, adding more that one oov bucket is only meaningful if we perform fine-tuning. Args: embeddings: Embeddings to extend. num_oov_buckets: Number of ...
python
def maybe_append_oov_vectors(embeddings, num_oov_buckets): """Adds zero vectors for oov buckets if num_oov_buckets > 0. Since we are assigning zero vectors, adding more that one oov bucket is only meaningful if we perform fine-tuning. Args: embeddings: Embeddings to extend. num_oov_buckets: Number of ...
[ "def", "maybe_append_oov_vectors", "(", "embeddings", ",", "num_oov_buckets", ")", ":", "num_embeddings", "=", "np", ".", "shape", "(", "embeddings", ")", "[", "0", "]", "embedding_dim", "=", "np", ".", "shape", "(", "embeddings", ")", "[", "1", "]", "embe...
Adds zero vectors for oov buckets if num_oov_buckets > 0. Since we are assigning zero vectors, adding more that one oov bucket is only meaningful if we perform fine-tuning. Args: embeddings: Embeddings to extend. num_oov_buckets: Number of OOV buckets in the extended embedding.
[ "Adds", "zero", "vectors", "for", "oov", "buckets", "if", "num_oov_buckets", ">", "0", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/text_embeddings/export.py#L222-L235
30,164
tensorflow/hub
tensorflow_hub/estimator.py
register_module_for_export
def register_module_for_export(module, export_name): """Register a Module to be exported under `export_name`. This function registers `module` to be exported by `LatestModuleExporter` under a subdirectory named `export_name`. Note that `export_name` must be unique for each module exported from the current ...
python
def register_module_for_export(module, export_name): """Register a Module to be exported under `export_name`. This function registers `module` to be exported by `LatestModuleExporter` under a subdirectory named `export_name`. Note that `export_name` must be unique for each module exported from the current ...
[ "def", "register_module_for_export", "(", "module", ",", "export_name", ")", ":", "for", "used_name", ",", "_", "in", "tf_v1", ".", "get_collection", "(", "_EXPORT_MODULES_COLLECTION", ")", ":", "if", "used_name", "==", "export_name", ":", "raise", "ValueError", ...
Register a Module to be exported under `export_name`. This function registers `module` to be exported by `LatestModuleExporter` under a subdirectory named `export_name`. Note that `export_name` must be unique for each module exported from the current graph. It only controls the export subdirectory name and i...
[ "Register", "a", "Module", "to", "be", "exported", "under", "export_name", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/estimator.py#L37-L60
30,165
tensorflow/hub
tensorflow_hub/estimator.py
_make_estimator_serving_session
def _make_estimator_serving_session(estimator, serving_input_fn, checkpoint_path): """Returns a session constructed using `estimator` and `serving_input_fn`. The Estimator API does not provide an API to construct a graph and session, making it necessary for this function to re...
python
def _make_estimator_serving_session(estimator, serving_input_fn, checkpoint_path): """Returns a session constructed using `estimator` and `serving_input_fn`. The Estimator API does not provide an API to construct a graph and session, making it necessary for this function to re...
[ "def", "_make_estimator_serving_session", "(", "estimator", ",", "serving_input_fn", ",", "checkpoint_path", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", "as", "g", ":", "mode", "=", "tf_v1", ".", "estimator", ".", "ModeKeys",...
Returns a session constructed using `estimator` and `serving_input_fn`. The Estimator API does not provide an API to construct a graph and session, making it necessary for this function to replicate how an estimator builds a graph. This code is based on `Estimator.export_savedmodel` (another function that h...
[ "Returns", "a", "session", "constructed", "using", "estimator", "and", "serving_input_fn", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/estimator.py#L171-L214
30,166
tensorflow/hub
tensorflow_hub/native_module.py
create_module_spec
def create_module_spec(module_fn, tags_and_args=None, drop_collections=None): """Creates a ModuleSpec from a function that builds the module's graph. The `module_fn` is called on a new graph (not the current one) to build the graph of the module and define its signatures via `hub.add_signature()`. Example: ...
python
def create_module_spec(module_fn, tags_and_args=None, drop_collections=None): """Creates a ModuleSpec from a function that builds the module's graph. The `module_fn` is called on a new graph (not the current one) to build the graph of the module and define its signatures via `hub.add_signature()`. Example: ...
[ "def", "create_module_spec", "(", "module_fn", ",", "tags_and_args", "=", "None", ",", "drop_collections", "=", "None", ")", ":", "if", "not", "drop_collections", ":", "drop_collections", "=", "[", "]", "report_tags", "=", "True", "if", "not", "tags_and_args", ...
Creates a ModuleSpec from a function that builds the module's graph. The `module_fn` is called on a new graph (not the current one) to build the graph of the module and define its signatures via `hub.add_signature()`. Example: ```python # Define a text embedding module. def my_text_module_fn(): text_i...
[ "Creates", "a", "ModuleSpec", "from", "a", "function", "that", "builds", "the", "module", "s", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L121-L195
30,167
tensorflow/hub
tensorflow_hub/native_module.py
add_signature
def add_signature(name=None, inputs=None, outputs=None): """Adds a signature to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. Args: name: Signature name as a string. If omitted, it is interpreted as 'default' and is the signature used when `Module.__c...
python
def add_signature(name=None, inputs=None, outputs=None): """Adds a signature to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. Args: name: Signature name as a string. If omitted, it is interpreted as 'default' and is the signature used when `Module.__c...
[ "def", "add_signature", "(", "name", "=", "None", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "\"default\"", "if", "inputs", "is", "None", ":", "inputs", "=", "{", "}", "if", "outputs", ...
Adds a signature to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. Args: name: Signature name as a string. If omitted, it is interpreted as 'default' and is the signature used when `Module.__call__` `signature` is not specified. inputs: A dict ...
[ "Adds", "a", "signature", "to", "the", "module", "definition", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L198-L231
30,168
tensorflow/hub
tensorflow_hub/native_module.py
attach_message
def attach_message(key, message): """Adds an attached message to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. See ModuleSpec.get_attached_message() for an introduction to attached messages and the API for module consumers. To define a new type of attached...
python
def attach_message(key, message): """Adds an attached message to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. See ModuleSpec.get_attached_message() for an introduction to attached messages and the API for module consumers. To define a new type of attached...
[ "def", "attach_message", "(", "key", ",", "message", ")", ":", "if", "not", "re", ".", "match", "(", "r\"[a-zA-Z][a-zA-Z0-9_]*$\"", ",", "key", ")", ":", "raise", "ValueError", "(", "\"hub.attach_message() called with malformed key '%s'\"", "%", "key", ")", "saved...
Adds an attached message to the module definition. NOTE: This must be called within a `module_fn` that is defining a Module. See ModuleSpec.get_attached_message() for an introduction to attached messages and the API for module consumers. To define a new type of attached message: * Select a reasonably de...
[ "Adds", "an", "attached", "message", "to", "the", "module", "definition", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L234-L276
30,169
tensorflow/hub
tensorflow_hub/native_module.py
list_registered_stateful_ops_without_inputs
def list_registered_stateful_ops_without_inputs(): """Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings. """ return set([ name ...
python
def list_registered_stateful_ops_without_inputs(): """Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings. """ return set([ name ...
[ "def", "list_registered_stateful_ops_without_inputs", "(", ")", ":", "return", "set", "(", "[", "name", "for", "name", ",", "op", "in", "op_def_registry", ".", "get_registered_ops", "(", ")", ".", "items", "(", ")", "if", "op", ".", "is_stateful", "and", "no...
Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings.
[ "Returns", "set", "of", "registered", "stateful", "ops", "that", "do", "not", "expect", "inputs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L586-L599
30,170
tensorflow/hub
tensorflow_hub/native_module.py
get_state_map
def get_state_map(meta_graph, state_ops, unsupported_state_ops, get_tensor_by_name): """Returns a map from tensor names to tensors that hold the state.""" state_map = {} for node in meta_graph.graph_def.node: if node.op in state_ops: tensor_name = node.name + ":0" tensor = get_te...
python
def get_state_map(meta_graph, state_ops, unsupported_state_ops, get_tensor_by_name): """Returns a map from tensor names to tensors that hold the state.""" state_map = {} for node in meta_graph.graph_def.node: if node.op in state_ops: tensor_name = node.name + ":0" tensor = get_te...
[ "def", "get_state_map", "(", "meta_graph", ",", "state_ops", ",", "unsupported_state_ops", ",", "get_tensor_by_name", ")", ":", "state_map", "=", "{", "}", "for", "node", "in", "meta_graph", ".", "graph_def", ".", "node", ":", "if", "node", ".", "op", "in", ...
Returns a map from tensor names to tensors that hold the state.
[ "Returns", "a", "map", "from", "tensor", "names", "to", "tensors", "that", "hold", "the", "state", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L602-L617
30,171
tensorflow/hub
tensorflow_hub/native_module.py
replace_apply_state
def replace_apply_state(meta_graph, state_ops, feed_map): """Replaces state ops with non state Placeholder ops for the apply graph.""" for node in meta_graph.graph_def.node: keys_to_purge = [] tensor_name = node.name + ":0" # Verify that the node is a state op and that its due to be rewired # in the...
python
def replace_apply_state(meta_graph, state_ops, feed_map): """Replaces state ops with non state Placeholder ops for the apply graph.""" for node in meta_graph.graph_def.node: keys_to_purge = [] tensor_name = node.name + ":0" # Verify that the node is a state op and that its due to be rewired # in the...
[ "def", "replace_apply_state", "(", "meta_graph", ",", "state_ops", ",", "feed_map", ")", ":", "for", "node", "in", "meta_graph", ".", "graph_def", ".", "node", ":", "keys_to_purge", "=", "[", "]", "tensor_name", "=", "node", ".", "name", "+", "\":0\"", "# ...
Replaces state ops with non state Placeholder ops for the apply graph.
[ "Replaces", "state", "ops", "with", "non", "state", "Placeholder", "ops", "for", "the", "apply", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L620-L636
30,172
tensorflow/hub
tensorflow_hub/native_module.py
_extract_variable_parts
def _extract_variable_parts(variable_key, variable): """Matches a variable to individual parts. Args: variable_key: String identifier of the variable in the module scope. variable: Variable tensor. Returns: partitioned: Whether the variable is partitioned. name: Name of the variable up to the pa...
python
def _extract_variable_parts(variable_key, variable): """Matches a variable to individual parts. Args: variable_key: String identifier of the variable in the module scope. variable: Variable tensor. Returns: partitioned: Whether the variable is partitioned. name: Name of the variable up to the pa...
[ "def", "_extract_variable_parts", "(", "variable_key", ",", "variable", ")", ":", "name", ",", "offset", ",", "partitioned", "=", "None", ",", "None", ",", "False", "# pylint: disable=protected-access", "if", "variable", ".", "_save_slice_info", ":", "name", "=", ...
Matches a variable to individual parts. Args: variable_key: String identifier of the variable in the module scope. variable: Variable tensor. Returns: partitioned: Whether the variable is partitioned. name: Name of the variable up to the partitioning. offset: Offset of the variable into the fu...
[ "Matches", "a", "variable", "to", "individual", "parts", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L664-L688
30,173
tensorflow/hub
tensorflow_hub/native_module.py
recover_partitioned_variable_map
def recover_partitioned_variable_map(var_node_map): """Builds a proper variable map if it contains PartitionedVariables. Args: var_node_map: A map to tf.Variables. PartitionedVariables show up in this map as N entries with keys "<var_name>/part_n". Returns: A map to tf.Variables or to list of tf.V...
python
def recover_partitioned_variable_map(var_node_map): """Builds a proper variable map if it contains PartitionedVariables. Args: var_node_map: A map to tf.Variables. PartitionedVariables show up in this map as N entries with keys "<var_name>/part_n". Returns: A map to tf.Variables or to list of tf.V...
[ "def", "recover_partitioned_variable_map", "(", "var_node_map", ")", ":", "offset_variables_map", "=", "{", "}", "for", "var_key", ",", "var_tensor", "in", "var_node_map", ".", "items", "(", ")", ":", "match", ",", "var_name", ",", "offset", "=", "_extract_varia...
Builds a proper variable map if it contains PartitionedVariables. Args: var_node_map: A map to tf.Variables. PartitionedVariables show up in this map as N entries with keys "<var_name>/part_n". Returns: A map to tf.Variables or to list of tf.Variables for each PartitionedVariables in `var_node_m...
[ "Builds", "a", "proper", "variable", "map", "if", "it", "contains", "PartitionedVariables", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L691-L745
30,174
tensorflow/hub
tensorflow_hub/native_module.py
check_unique_tags
def check_unique_tags(tag_list): """Checks that tag list contains each set of tags only once.""" frozen_tags_seen = set() for tags in tag_list: frozen_tags = frozenset(tags) if frozen_tags in frozen_tags_seen: raise ValueError("Tags %r used repeatedly" % tags) frozen_tags_seen.add(frozen_tags)
python
def check_unique_tags(tag_list): """Checks that tag list contains each set of tags only once.""" frozen_tags_seen = set() for tags in tag_list: frozen_tags = frozenset(tags) if frozen_tags in frozen_tags_seen: raise ValueError("Tags %r used repeatedly" % tags) frozen_tags_seen.add(frozen_tags)
[ "def", "check_unique_tags", "(", "tag_list", ")", ":", "frozen_tags_seen", "=", "set", "(", ")", "for", "tags", "in", "tag_list", ":", "frozen_tags", "=", "frozenset", "(", "tags", ")", "if", "frozen_tags", "in", "frozen_tags_seen", ":", "raise", "ValueError",...
Checks that tag list contains each set of tags only once.
[ "Checks", "that", "tag", "list", "contains", "each", "set", "of", "tags", "only", "once", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L748-L755
30,175
tensorflow/hub
tensorflow_hub/native_module.py
check_collections_are_supported
def check_collections_are_supported(saved_model_handler, supported): """Checks that SavedModelHandler only uses supported collections.""" for meta_graph in saved_model_handler.meta_graphs: used_collection_keys = set(meta_graph.collection_def.keys()) unsupported = used_collection_keys - supported if unsu...
python
def check_collections_are_supported(saved_model_handler, supported): """Checks that SavedModelHandler only uses supported collections.""" for meta_graph in saved_model_handler.meta_graphs: used_collection_keys = set(meta_graph.collection_def.keys()) unsupported = used_collection_keys - supported if unsu...
[ "def", "check_collections_are_supported", "(", "saved_model_handler", ",", "supported", ")", ":", "for", "meta_graph", "in", "saved_model_handler", ".", "meta_graphs", ":", "used_collection_keys", "=", "set", "(", "meta_graph", ".", "collection_def", ".", "keys", "(",...
Checks that SavedModelHandler only uses supported collections.
[ "Checks", "that", "SavedModelHandler", "only", "uses", "supported", "collections", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L758-L766
30,176
tensorflow/hub
tensorflow_hub/native_module.py
register_ops_if_needed
def register_ops_if_needed(graph_ops): """Register graph ops absent in op_def_registry, if present in c++ registry. Args: graph_ops: set with graph op names to register. Raises: RuntimeError: if `graph_ops` contains ops that are not in either python or c++ registry. """ missing_ops = graph_ops...
python
def register_ops_if_needed(graph_ops): """Register graph ops absent in op_def_registry, if present in c++ registry. Args: graph_ops: set with graph op names to register. Raises: RuntimeError: if `graph_ops` contains ops that are not in either python or c++ registry. """ missing_ops = graph_ops...
[ "def", "register_ops_if_needed", "(", "graph_ops", ")", ":", "missing_ops", "=", "graph_ops", "-", "set", "(", "op_def_registry", ".", "get_registered_ops", "(", ")", ".", "keys", "(", ")", ")", "if", "not", "missing_ops", ":", "return", "p_buffer", "=", "c_...
Register graph ops absent in op_def_registry, if present in c++ registry. Args: graph_ops: set with graph op names to register. Raises: RuntimeError: if `graph_ops` contains ops that are not in either python or c++ registry.
[ "Register", "graph", "ops", "absent", "in", "op_def_registry", "if", "present", "in", "c", "++", "registry", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L773-L814
30,177
tensorflow/hub
tensorflow_hub/native_module.py
fix_colocation_after_import
def fix_colocation_after_import(input_map, absolute_import_scope): """Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during im...
python
def fix_colocation_after_import(input_map, absolute_import_scope): """Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during im...
[ "def", "fix_colocation_after_import", "(", "input_map", ",", "absolute_import_scope", ")", ":", "attr_map", "=", "_build_colocation_attr_map", "(", "input_map", ",", "absolute_import_scope", ")", "_apply_colocation_attr_map", "(", "attr_map", ",", "absolute_import_scope", "...
Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during import. It also updates devices accordingly. The nodes in the given imp...
[ "Fixes", "colocation", "attributes", "after", "import", "according", "to", "input_map", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L817-L870
30,178
tensorflow/hub
tensorflow_hub/native_module.py
_build_colocation_attr_map
def _build_colocation_attr_map(input_map, absolute_import_scope): """Returns a dict mapping from pre-import to post-import colocation attrs. Args: input_map: as for fix_colocation_after_import. absolute_import_scope: as for fix_colocation_after_import. Returns: A dict that maps bytes `"loc:@" + abso...
python
def _build_colocation_attr_map(input_map, absolute_import_scope): """Returns a dict mapping from pre-import to post-import colocation attrs. Args: input_map: as for fix_colocation_after_import. absolute_import_scope: as for fix_colocation_after_import. Returns: A dict that maps bytes `"loc:@" + abso...
[ "def", "_build_colocation_attr_map", "(", "input_map", ",", "absolute_import_scope", ")", ":", "colocation_attr_map", "=", "collections", ".", "defaultdict", "(", "_ConsistentValue", ")", "used_outputs_of_imported_ops", "=", "collections", ".", "defaultdict", "(", "set", ...
Returns a dict mapping from pre-import to post-import colocation attrs. Args: input_map: as for fix_colocation_after_import. absolute_import_scope: as for fix_colocation_after_import. Returns: A dict that maps bytes `"loc:@" + absolute_import_scope + "/foo"` to _ConsistentValues set to the lists o...
[ "Returns", "a", "dict", "mapping", "from", "pre", "-", "import", "to", "post", "-", "import", "colocation", "attrs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L918-L965
30,179
tensorflow/hub
tensorflow_hub/native_module.py
_apply_colocation_attr_map
def _apply_colocation_attr_map(colocation_attr_map, absolute_import_scope): """Rewrites colocation constraints in the current default graph. Nodes in `absolute_import_scope` get their "_class" attr lists rewritten according to `colocation_attr_map`: each entry that matches a key gets replaced by the associated...
python
def _apply_colocation_attr_map(colocation_attr_map, absolute_import_scope): """Rewrites colocation constraints in the current default graph. Nodes in `absolute_import_scope` get their "_class" attr lists rewritten according to `colocation_attr_map`: each entry that matches a key gets replaced by the associated...
[ "def", "_apply_colocation_attr_map", "(", "colocation_attr_map", ",", "absolute_import_scope", ")", ":", "graph", "=", "tf_v1", ".", "get_default_graph", "(", ")", "for", "op", "in", "graph", ".", "get_operations", "(", ")", ":", "# Rewrite the values of the \"_class\...
Rewrites colocation constraints in the current default graph. Nodes in `absolute_import_scope` get their "_class" attr lists rewritten according to `colocation_attr_map`: each entry that matches a key gets replaced by the associated values (with deduplication). The node's device is updated accordingly. Args...
[ "Rewrites", "colocation", "constraints", "in", "the", "current", "default", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L968-L1037
30,180
tensorflow/hub
tensorflow_hub/native_module.py
find_state_op_colocation_error
def find_state_op_colocation_error(graph, reported_tags=None): """Returns error message for colocation of state ops, or None if ok.""" state_op_types = list_registered_stateful_ops_without_inputs() state_op_map = {op.name: op for op in graph.get_operations() if op.type in state_op_types} for o...
python
def find_state_op_colocation_error(graph, reported_tags=None): """Returns error message for colocation of state ops, or None if ok.""" state_op_types = list_registered_stateful_ops_without_inputs() state_op_map = {op.name: op for op in graph.get_operations() if op.type in state_op_types} for o...
[ "def", "find_state_op_colocation_error", "(", "graph", ",", "reported_tags", "=", "None", ")", ":", "state_op_types", "=", "list_registered_stateful_ops_without_inputs", "(", ")", "state_op_map", "=", "{", "op", ".", "name", ":", "op", "for", "op", "in", "graph", ...
Returns error message for colocation of state ops, or None if ok.
[ "Returns", "error", "message", "for", "colocation", "of", "state", "ops", "or", "None", "if", "ok", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L1040-L1058
30,181
tensorflow/hub
tensorflow_hub/native_module.py
find_signature_input_colocation_error
def find_signature_input_colocation_error(signature_name, inputs): """Returns error message for colocation of signature inputs, or None if ok.""" for input_name, tensor in inputs.items(): expected_colocation_groups = [tf.compat.as_bytes("loc:@" + tensor.op.name)] if tensor.op.colocation_groups() != expected...
python
def find_signature_input_colocation_error(signature_name, inputs): """Returns error message for colocation of signature inputs, or None if ok.""" for input_name, tensor in inputs.items(): expected_colocation_groups = [tf.compat.as_bytes("loc:@" + tensor.op.name)] if tensor.op.colocation_groups() != expected...
[ "def", "find_signature_input_colocation_error", "(", "signature_name", ",", "inputs", ")", ":", "for", "input_name", ",", "tensor", "in", "inputs", ".", "items", "(", ")", ":", "expected_colocation_groups", "=", "[", "tf", ".", "compat", ".", "as_bytes", "(", ...
Returns error message for colocation of signature inputs, or None if ok.
[ "Returns", "error", "message", "for", "colocation", "of", "signature", "inputs", "or", "None", "if", "ok", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L1061-L1072
30,182
tensorflow/hub
tensorflow_hub/native_module.py
find_signature_inputs_from_multivalued_ops
def find_signature_inputs_from_multivalued_ops(inputs): """Returns error message for module inputs from ops with multiple outputs.""" dense_inputs = [] # List of (str, Tensor), with SparseTensors decomposed. for name, tensor in sorted(inputs.items()): if isinstance(tensor, tf.SparseTensor): dense_input...
python
def find_signature_inputs_from_multivalued_ops(inputs): """Returns error message for module inputs from ops with multiple outputs.""" dense_inputs = [] # List of (str, Tensor), with SparseTensors decomposed. for name, tensor in sorted(inputs.items()): if isinstance(tensor, tf.SparseTensor): dense_input...
[ "def", "find_signature_inputs_from_multivalued_ops", "(", "inputs", ")", ":", "dense_inputs", "=", "[", "]", "# List of (str, Tensor), with SparseTensors decomposed.", "for", "name", ",", "tensor", "in", "sorted", "(", "inputs", ".", "items", "(", ")", ")", ":", "if...
Returns error message for module inputs from ops with multiple outputs.
[ "Returns", "error", "message", "for", "module", "inputs", "from", "ops", "with", "multiple", "outputs", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L1075-L1093
30,183
tensorflow/hub
tensorflow_hub/native_module.py
_ModuleImpl._create_state_graph
def _create_state_graph(self, name): """Creates the graph nodes that hold the state of the Module. Args: name: name scope to create the state graph in. Returns: A tuple consisting of: variables_tensor_map: a map from tensor names in the original graph def to the created Varia...
python
def _create_state_graph(self, name): """Creates the graph nodes that hold the state of the Module. Args: name: name scope to create the state graph in. Returns: A tuple consisting of: variables_tensor_map: a map from tensor names in the original graph def to the created Varia...
[ "def", "_create_state_graph", "(", "self", ",", "name", ")", ":", "import_collections", "=", "[", "tf_v1", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ",", "tf_v1", ".", "GraphKeys", ".", "MODEL_VARIABLES", ",", "tf_v1", ".", "GraphKeys", ".", "TABLE_INITIALIZERS...
Creates the graph nodes that hold the state of the Module. Args: name: name scope to create the state graph in. Returns: A tuple consisting of: variables_tensor_map: a map from tensor names in the original graph def to the created Variables objects. state_map: a map from ...
[ "Creates", "the", "graph", "nodes", "that", "hold", "the", "state", "of", "the", "Module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L410-L470
30,184
tensorflow/hub
tensorflow_hub/native_module.py
_ModuleImpl.create_apply_graph
def create_apply_graph(self, signature, input_tensors, name): """See `ModuleImpl.create_apply_graph`.""" signature_def = self._meta_graph.signature_def.get(signature) meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.CopyFrom(self._meta_graph) apply_graph = tf_v1.get_default_graph() infeed_m...
python
def create_apply_graph(self, signature, input_tensors, name): """See `ModuleImpl.create_apply_graph`.""" signature_def = self._meta_graph.signature_def.get(signature) meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.CopyFrom(self._meta_graph) apply_graph = tf_v1.get_default_graph() infeed_m...
[ "def", "create_apply_graph", "(", "self", ",", "signature", ",", "input_tensors", ",", "name", ")", ":", "signature_def", "=", "self", ".", "_meta_graph", ".", "signature_def", ".", "get", "(", "signature", ")", "meta_graph", "=", "meta_graph_pb2", ".", "MetaG...
See `ModuleImpl.create_apply_graph`.
[ "See", "ModuleImpl", ".", "create_apply_graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L472-L561
30,185
tensorflow/hub
tensorflow_hub/native_module.py
_ModuleImpl.export
def export(self, path, session): """See `Module.export`.""" def variables_saver(variables_path): if self._saver: self._saver.save( session, variables_path, write_meta_graph=False, write_state=False) self._spec._export(path, variables_saver)
python
def export(self, path, session): """See `Module.export`.""" def variables_saver(variables_path): if self._saver: self._saver.save( session, variables_path, write_meta_graph=False, write_state=False) self._spec._export(path, variables_saver)
[ "def", "export", "(", "self", ",", "path", ",", "session", ")", ":", "def", "variables_saver", "(", "variables_path", ")", ":", "if", "self", ".", "_saver", ":", "self", ".", "_saver", ".", "save", "(", "session", ",", "variables_path", ",", "write_meta_...
See `Module.export`.
[ "See", "Module", ".", "export", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L569-L578
30,186
tensorflow/hub
tensorflow_hub/native_module.py
_ConsistentValue.Set
def Set(self, value, context=None): """Receives a value for the object and some context on its source.""" if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.v...
python
def Set(self, value, context=None): """Receives a value for the object and some context on its source.""" if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.v...
[ "def", "Set", "(", "self", ",", "value", ",", "context", "=", "None", ")", ":", "if", "self", ".", "has_error", ":", "return", "if", "self", ".", "value", "is", "None", ":", "self", ".", "value", "=", "value", "self", ".", "_context", "[", "\"old_v...
Receives a value for the object and some context on its source.
[ "Receives", "a", "value", "for", "the", "object", "and", "some", "context", "on", "its", "source", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L897-L907
30,187
tensorflow/hub
tensorflow_hub/native_module.py
_ConsistentValue.GetConsistentValueOrRaise
def GetConsistentValueOrRaise(self, error_format, context=None): """Gets consistent value or raises ValueError with formatted contexts.""" if self.has_error: full_context = dict(self._context) if context: full_context.update(context) raise ValueError(error_format.format(**full_context)) re...
python
def GetConsistentValueOrRaise(self, error_format, context=None): """Gets consistent value or raises ValueError with formatted contexts.""" if self.has_error: full_context = dict(self._context) if context: full_context.update(context) raise ValueError(error_format.format(**full_context)) re...
[ "def", "GetConsistentValueOrRaise", "(", "self", ",", "error_format", ",", "context", "=", "None", ")", ":", "if", "self", ".", "has_error", ":", "full_context", "=", "dict", "(", "self", ".", "_context", ")", "if", "context", ":", "full_context", ".", "up...
Gets consistent value or raises ValueError with formatted contexts.
[ "Gets", "consistent", "value", "or", "raises", "ValueError", "with", "formatted", "contexts", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L909-L915
30,188
tensorflow/hub
tensorflow_hub/compressed_module_resolver.py
_module_dir
def _module_dir(handle): """Returns the directory where to cache the module.""" cache_dir = resolver.tfhub_cache_dir(use_temp=True) return resolver.create_local_module_dir( cache_dir, hashlib.sha1(handle.encode("utf8")).hexdigest())
python
def _module_dir(handle): """Returns the directory where to cache the module.""" cache_dir = resolver.tfhub_cache_dir(use_temp=True) return resolver.create_local_module_dir( cache_dir, hashlib.sha1(handle.encode("utf8")).hexdigest())
[ "def", "_module_dir", "(", "handle", ")", ":", "cache_dir", "=", "resolver", ".", "tfhub_cache_dir", "(", "use_temp", "=", "True", ")", "return", "resolver", ".", "create_local_module_dir", "(", "cache_dir", ",", "hashlib", ".", "sha1", "(", "handle", ".", "...
Returns the directory where to cache the module.
[ "Returns", "the", "directory", "where", "to", "cache", "the", "module", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/compressed_module_resolver.py#L44-L49
30,189
tensorflow/hub
tensorflow_hub/saved_model_lib.py
get_variables_path
def get_variables_path(export_dir): """Returns the path for storing variables checkpoints.""" return os.path.join( tf.compat.as_bytes(export_dir), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_DIRECTORY), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_FILENAME))
python
def get_variables_path(export_dir): """Returns the path for storing variables checkpoints.""" return os.path.join( tf.compat.as_bytes(export_dir), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_DIRECTORY), tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_FILENAME))
[ "def", "get_variables_path", "(", "export_dir", ")", ":", "return", "os", ".", "path", ".", "join", "(", "tf", ".", "compat", ".", "as_bytes", "(", "export_dir", ")", ",", "tf", ".", "compat", ".", "as_bytes", "(", "tf_v1", ".", "saved_model", ".", "co...
Returns the path for storing variables checkpoints.
[ "Returns", "the", "path", "for", "storing", "variables", "checkpoints", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L52-L57
30,190
tensorflow/hub
tensorflow_hub/saved_model_lib.py
add_signature
def add_signature(key, inputs, outputs): """Adds a signature to current graph. Args: key: Signature key as a string. inputs: Signature inputs as a map from string to Tensor or SparseTensor. outputs: Signature outputs as a map from string to Tensor or SparseTensor. (Recall that a Variable is not a...
python
def add_signature(key, inputs, outputs): """Adds a signature to current graph. Args: key: Signature key as a string. inputs: Signature inputs as a map from string to Tensor or SparseTensor. outputs: Signature outputs as a map from string to Tensor or SparseTensor. (Recall that a Variable is not a...
[ "def", "add_signature", "(", "key", ",", "inputs", ",", "outputs", ")", ":", "_check_dict_maps_to_tensors_or_sparse_tensors", "(", "inputs", ")", "_check_dict_maps_to_tensors_or_sparse_tensors", "(", "outputs", ")", "input_info", "=", "{", "input_name", ":", "tf_v1", ...
Adds a signature to current graph. Args: key: Signature key as a string. inputs: Signature inputs as a map from string to Tensor or SparseTensor. outputs: Signature outputs as a map from string to Tensor or SparseTensor. (Recall that a Variable is not a Tensor, but Variable.value() is.) Raises: ...
[ "Adds", "a", "signature", "to", "current", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L94-L118
30,191
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_export_signatures
def _export_signatures(meta_graph): """Exports signatures from current graph into a MetaGraphDef.""" named_signatures = tf_v1.get_collection(_SIGNATURE_COLLECTION) if not named_signatures: raise ValueError("No signatures present. Please call hub.add_signature(...)" "at least once in the m...
python
def _export_signatures(meta_graph): """Exports signatures from current graph into a MetaGraphDef.""" named_signatures = tf_v1.get_collection(_SIGNATURE_COLLECTION) if not named_signatures: raise ValueError("No signatures present. Please call hub.add_signature(...)" "at least once in the m...
[ "def", "_export_signatures", "(", "meta_graph", ")", ":", "named_signatures", "=", "tf_v1", ".", "get_collection", "(", "_SIGNATURE_COLLECTION", ")", "if", "not", "named_signatures", ":", "raise", "ValueError", "(", "\"No signatures present. Please call hub.add_signature(.....
Exports signatures from current graph into a MetaGraphDef.
[ "Exports", "signatures", "from", "current", "graph", "into", "a", "MetaGraphDef", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L129-L136
30,192
tensorflow/hub
tensorflow_hub/saved_model_lib.py
attach_bytes
def attach_bytes(key, the_bytes): """Adds a ModuleAttachment to the current graph. Args: key: A string with the unique key of the attachment. the_bytes: A bytes object with the serialized attachment. """ tf_v1.add_to_collection( _ATTACHMENT_COLLECTION_INTERNAL, module_attachment_pb2.ModuleA...
python
def attach_bytes(key, the_bytes): """Adds a ModuleAttachment to the current graph. Args: key: A string with the unique key of the attachment. the_bytes: A bytes object with the serialized attachment. """ tf_v1.add_to_collection( _ATTACHMENT_COLLECTION_INTERNAL, module_attachment_pb2.ModuleA...
[ "def", "attach_bytes", "(", "key", ",", "the_bytes", ")", ":", "tf_v1", ".", "add_to_collection", "(", "_ATTACHMENT_COLLECTION_INTERNAL", ",", "module_attachment_pb2", ".", "ModuleAttachment", "(", "key", "=", "key", ",", "value", "=", "the_bytes", ")", ")" ]
Adds a ModuleAttachment to the current graph. Args: key: A string with the unique key of the attachment. the_bytes: A bytes object with the serialized attachment.
[ "Adds", "a", "ModuleAttachment", "to", "the", "current", "graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L139-L148
30,193
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_export_module_attachments
def _export_module_attachments(meta_graph): """Exports ModuleAttachments from the current tf.Graph into `meta_graph`.""" added_attachments = tf_v1.get_collection(_ATTACHMENT_COLLECTION_INTERNAL) if not added_attachments: return # Don't touch `meta_graph`. unique_attachments = collections.OrderedDict( # Avoid ...
python
def _export_module_attachments(meta_graph): """Exports ModuleAttachments from the current tf.Graph into `meta_graph`.""" added_attachments = tf_v1.get_collection(_ATTACHMENT_COLLECTION_INTERNAL) if not added_attachments: return # Don't touch `meta_graph`. unique_attachments = collections.OrderedDict( # Avoid ...
[ "def", "_export_module_attachments", "(", "meta_graph", ")", ":", "added_attachments", "=", "tf_v1", ".", "get_collection", "(", "_ATTACHMENT_COLLECTION_INTERNAL", ")", "if", "not", "added_attachments", ":", "return", "# Don't touch `meta_graph`.", "unique_attachments", "="...
Exports ModuleAttachments from the current tf.Graph into `meta_graph`.
[ "Exports", "ModuleAttachments", "from", "the", "current", "tf", ".", "Graph", "into", "meta_graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L151-L160
30,194
tensorflow/hub
tensorflow_hub/saved_model_lib.py
get_attached_bytes_map
def get_attached_bytes_map(meta_graph): """Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy() from some graph. Returns: A dict, containing the `(key, bytes)` items passed to `attach_bytes()` when the gr...
python
def get_attached_bytes_map(meta_graph): """Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy() from some graph. Returns: A dict, containing the `(key, bytes)` items passed to `attach_bytes()` when the gr...
[ "def", "get_attached_bytes_map", "(", "meta_graph", ")", ":", "result", "=", "{", "}", "if", "ATTACHMENT_COLLECTION_SAVED", "not", "in", "meta_graph", ".", "collection_def", ":", "return", "result", "collection_def", "=", "meta_graph", ".", "collection_def", "[", ...
Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy() from some graph. Returns: A dict, containing the `(key, bytes)` items passed to `attach_bytes()` when the graph had been built. Raises: ValueError...
[ "Returns", "the", "dict", "of", "ModuleAttachments", "stored", "in", "meta_graph", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L163-L189
30,195
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_check_asset_node_def
def _check_asset_node_def(node_def): """Raises TypeError if `node_def` does not match the expectations.""" if node_def.op != "Const": raise TypeError("Asset node must be of type constant.") if tf.as_dtype(node_def.attr["dtype"].type) != tf.string: raise TypeError("Asset node must be of dtype string.") i...
python
def _check_asset_node_def(node_def): """Raises TypeError if `node_def` does not match the expectations.""" if node_def.op != "Const": raise TypeError("Asset node must be of type constant.") if tf.as_dtype(node_def.attr["dtype"].type) != tf.string: raise TypeError("Asset node must be of dtype string.") i...
[ "def", "_check_asset_node_def", "(", "node_def", ")", ":", "if", "node_def", ".", "op", "!=", "\"Const\"", ":", "raise", "TypeError", "(", "\"Asset node must be of type constant.\"", ")", "if", "tf", ".", "as_dtype", "(", "node_def", ".", "attr", "[", "\"dtype\"...
Raises TypeError if `node_def` does not match the expectations.
[ "Raises", "TypeError", "if", "node_def", "does", "not", "match", "the", "expectations", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L198-L205
30,196
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_merge_assets_key_collection
def _merge_assets_key_collection(saved_model_proto, path): """Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto. Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and modifies nodes with the assets filenames to point to the assets in `path`. After this transformation...
python
def _merge_assets_key_collection(saved_model_proto, path): """Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto. Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and modifies nodes with the assets filenames to point to the assets in `path`. After this transformation...
[ "def", "_merge_assets_key_collection", "(", "saved_model_proto", ",", "path", ")", ":", "for", "meta_graph", "in", "saved_model_proto", ".", "meta_graphs", ":", "node_asset_map", "=", "{", "}", "if", "tf_v1", ".", "saved_model", ".", "constants", ".", "ASSETS_KEY"...
Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto. Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and modifies nodes with the assets filenames to point to the assets in `path`. After this transformation, the SavedModel GraphDefs can be used without feeding asset t...
[ "Merges", "the", "ASSETS_KEY", "collection", "into", "the", "GraphDefs", "in", "saved_model_proto", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L208-L237
30,197
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_make_assets_key_collection
def _make_assets_key_collection(saved_model_proto, export_path): """Creates an ASSETS_KEY collection in the GraphDefs in saved_model_proto. Adds an ASSETS_KEY collection to the GraphDefs in the SavedModel and returns a map from original asset filename to filename when exporting the SavedModel to `export_path`....
python
def _make_assets_key_collection(saved_model_proto, export_path): """Creates an ASSETS_KEY collection in the GraphDefs in saved_model_proto. Adds an ASSETS_KEY collection to the GraphDefs in the SavedModel and returns a map from original asset filename to filename when exporting the SavedModel to `export_path`....
[ "def", "_make_assets_key_collection", "(", "saved_model_proto", ",", "export_path", ")", ":", "asset_filenames", "=", "{", "}", "used_asset_filenames", "=", "set", "(", ")", "def", "_make_asset_filename", "(", "original_filename", ")", ":", "\"\"\"Returns the asset file...
Creates an ASSETS_KEY collection in the GraphDefs in saved_model_proto. Adds an ASSETS_KEY collection to the GraphDefs in the SavedModel and returns a map from original asset filename to filename when exporting the SavedModel to `export_path`. This is roughly the inverse operation of `_merge_assets_key_collec...
[ "Creates", "an", "ASSETS_KEY", "collection", "in", "the", "GraphDefs", "in", "saved_model_proto", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L240-L320
30,198
tensorflow/hub
tensorflow_hub/saved_model_lib.py
_parse_saved_model
def _parse_saved_model(path): """Reads the savedmodel.pb file containing `SavedModel`.""" # Based on tensorflow/python/saved_model/loader.py implementation. path_to_pb = _get_saved_model_proto_path(path) file_content = tf_v1.gfile.Open(path_to_pb, "rb").read() saved_model = saved_model_pb2.SavedModel() try:...
python
def _parse_saved_model(path): """Reads the savedmodel.pb file containing `SavedModel`.""" # Based on tensorflow/python/saved_model/loader.py implementation. path_to_pb = _get_saved_model_proto_path(path) file_content = tf_v1.gfile.Open(path_to_pb, "rb").read() saved_model = saved_model_pb2.SavedModel() try:...
[ "def", "_parse_saved_model", "(", "path", ")", ":", "# Based on tensorflow/python/saved_model/loader.py implementation.", "path_to_pb", "=", "_get_saved_model_proto_path", "(", "path", ")", "file_content", "=", "tf_v1", ".", "gfile", ".", "Open", "(", "path_to_pb", ",", ...
Reads the savedmodel.pb file containing `SavedModel`.
[ "Reads", "the", "savedmodel", ".", "pb", "file", "containing", "SavedModel", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L441-L451
30,199
tensorflow/hub
tensorflow_hub/saved_model_lib.py
load
def load(path): """Creates a SavedModelHandler from a SavedModel in `path`.""" proto = _parse_saved_model(path) _merge_assets_key_collection(proto, path) handler = SavedModelHandler() handler._proto = proto # pylint: disable=protected-access return handler
python
def load(path): """Creates a SavedModelHandler from a SavedModel in `path`.""" proto = _parse_saved_model(path) _merge_assets_key_collection(proto, path) handler = SavedModelHandler() handler._proto = proto # pylint: disable=protected-access return handler
[ "def", "load", "(", "path", ")", ":", "proto", "=", "_parse_saved_model", "(", "path", ")", "_merge_assets_key_collection", "(", "proto", ",", "path", ")", "handler", "=", "SavedModelHandler", "(", ")", "handler", ".", "_proto", "=", "proto", "# pylint: disabl...
Creates a SavedModelHandler from a SavedModel in `path`.
[ "Creates", "a", "SavedModelHandler", "from", "a", "SavedModel", "in", "path", "." ]
09f45963f6787322967b6fec61459f3ac56fbb27
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/saved_model_lib.py#L454-L460