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_binary() self.info[self.PARAM_USER_ID] = self._get_user_id() self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info() try: scm = SCM(root_dir=Repo.find_root()) self.info[self.PARAM_SCM_CLASS] = type(scm).__name__ except NotDvcRepoError: pass
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_binary() self.info[self.PARAM_USER_ID] = self._get_user_id() self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info() try: scm = SCM(root_dir=Repo.find_root()) self.info[self.PARAM_SCM_CLASS] = type(scm).__name__ except NotDvcRepoError: pass
[ "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 hasattr(args, "func"): assert args.func != CmdDaemonAnalytics self.info[self.PARAM_CMD_CLASS] = args.func.__name__
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 hasattr(args, "func"): assert args.func != CmdDaemonAnalytics self.info[self.PARAM_CMD_CLASS] = args.func.__name__
[ "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) return fobj.name
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) return fobj.name
[ "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): return analytics = Analytics() analytics.collect_cmd(args, ret) daemon(["analytics", analytics.dump()])
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): return analytics = Analytics() analytics.collect_cmd(args, ret) daemon(["analytics", analytics.dump()])
[ "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) except requests.exceptions.RequestException as exc: logger.debug("Failed to send analytics: {}".format(str(exc)))
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) except requests.exceptions.RequestException as exc: logger.debug("Failed to send analytics: {}".format(str(exc)))
[ "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.RemoteBase): optional remote to push to. By default remote from core.remote config option is used. show_checksums (bool): show checksums instead of file names in information messages. """ return self.repo.cache.local.push( targets, jobs=jobs, remote=self._get_cloud(remote, "push"), show_checksums=show_checksums, )
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.RemoteBase): optional remote to push to. By default remote from core.remote config option is used. show_checksums (bool): show checksums instead of file names in information messages. """ return self.repo.cache.local.push( targets, jobs=jobs, remote=self._get_cloud(remote, "push"), show_checksums=show_checksums, )
[ "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.remote config option is used. show_checksums (bool): show checksums instead of file names in information messages.
[ "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.remote.base.RemoteBase): optional remote to compare targets to. By default remote from core.remote config option is used. show_checksums (bool): show checksums instead of file names in information messages. """ cloud = self._get_cloud(remote, "status") return self.repo.cache.local.status( targets, jobs=jobs, remote=cloud, show_checksums=show_checksums )
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.remote.base.RemoteBase): optional remote to compare targets to. By default remote from core.remote config option is used. show_checksums (bool): show checksums instead of file names in information messages. """ cloud = self._get_cloud(remote, "status") return self.repo.cache.local.status( targets, jobs=jobs, remote=cloud, show_checksums=show_checksums )
[ "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 default remote from core.remote config option is used. show_checksums (bool): show checksums instead of file names in information messages.
[ "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 list of tags to iterate over. all_tags (bool): iterate over all available tags. Yields: str: the display name for the currently selected tree, it could be: - a git revision identifier - empty string it there is no branches to iterate over - "Working Tree" if there are uncommited changes in the SCM repo """ if not any([branches, all_branches, tags, all_tags]): yield "" return saved_tree = self.tree revs = [] scm = self.scm if self.scm.is_dirty(): from dvc.scm.tree import WorkingTree self.tree = WorkingTree(self.root_dir) yield "Working Tree" if all_branches: branches = scm.list_branches() if all_tags: tags = scm.list_tags() if branches is None: revs.extend([scm.active_branch()]) else: revs.extend(branches) if tags is not None: revs.extend(tags) # NOTE: it might be a good idea to wrap this loop in try/finally block # to don't leave the tree on some unexpected branch after the # `brancher()`, but this could cause problems on exception handling # code which might expect the tree on which exception was raised to # stay in place. This behavior is a subject to change. for rev in revs: self.tree = scm.get_tree(rev) yield rev self.tree = saved_tree
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 list of tags to iterate over. all_tags (bool): iterate over all available tags. Yields: str: the display name for the currently selected tree, it could be: - a git revision identifier - empty string it there is no branches to iterate over - "Working Tree" if there are uncommited changes in the SCM repo """ if not any([branches, all_branches, tags, all_tags]): yield "" return saved_tree = self.tree revs = [] scm = self.scm if self.scm.is_dirty(): from dvc.scm.tree import WorkingTree self.tree = WorkingTree(self.root_dir) yield "Working Tree" if all_branches: branches = scm.list_branches() if all_tags: tags = scm.list_tags() if branches is None: revs.extend([scm.active_branch()]) else: revs.extend(branches) if tags is not None: revs.extend(tags) # NOTE: it might be a good idea to wrap this loop in try/finally block # to don't leave the tree on some unexpected branch after the # `brancher()`, but this could cause problems on exception handling # code which might expect the tree on which exception was raised to # stay in place. This behavior is a subject to change. for rev in revs: self.tree = scm.get_tree(rev) yield rev self.tree = saved_tree
[ "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: str: the display name for the currently selected tree, it could be: - a git revision identifier - empty string it there is no branches to iterate over - "Working Tree" if there are uncommited changes in the SCM repo
[ "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_file) self.cursor = self.database.cursor() # Try loading once to check that the file is indeed a database # and reformat it if it is not. try: self._prepare_db(empty=empty) return except sqlite3.DatabaseError: self.cursor.close() self.database.close() self.database = None self.cursor = None self.inserts = 0 if retries > 0: os.unlink(self.state_file) retries -= 1 else: raise
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_file) self.cursor = self.database.cursor() # Try loading once to check that the file is indeed a database # and reformat it if it is not. try: self._prepare_db(empty=empty) return except sqlite3.DatabaseError: self.cursor.close() self.database.close() self.database = None self.cursor = None self.inserts = 0 if retries > 0: os.unlink(self.state_file) retries -= 1 else: raise
[ "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 count = self._from_sqlite(ret[0][0]) + self.inserts if count > self.row_limit: msg = "cleaning up state, this might take a while." logger.warning(msg) delete = count - self.row_limit delete += int(self.row_limit * (self.row_cleanup_quota / 100.0)) cmd = ( "DELETE FROM {} WHERE timestamp IN (" "SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});" ) self._execute( cmd.format(self.STATE_TABLE, self.STATE_TABLE, delete) ) self._vacuum() cmd = "SELECT COUNT(*) FROM {}" self._execute(cmd.format(self.STATE_TABLE)) ret = self._fetchall() assert len(ret) == 1 assert len(ret[0]) == 1 count = ret[0][0] cmd = "UPDATE {} SET count = {} WHERE rowid = {}" self._execute( cmd.format( self.STATE_INFO_TABLE, self._to_sqlite(count), self.STATE_INFO_ROW, ) ) self._update_cache_directory_state() self.database.commit() self.cursor.close() self.database.close() self.database = None self.cursor = None self.inserts = 0
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 count = self._from_sqlite(ret[0][0]) + self.inserts if count > self.row_limit: msg = "cleaning up state, this might take a while." logger.warning(msg) delete = count - self.row_limit delete += int(self.row_limit * (self.row_cleanup_quota / 100.0)) cmd = ( "DELETE FROM {} WHERE timestamp IN (" "SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});" ) self._execute( cmd.format(self.STATE_TABLE, self.STATE_TABLE, delete) ) self._vacuum() cmd = "SELECT COUNT(*) FROM {}" self._execute(cmd.format(self.STATE_TABLE)) ret = self._fetchall() assert len(ret) == 1 assert len(ret[0]) == 1 count = ret[0][0] cmd = "UPDATE {} SET count = {} WHERE rowid = {}" self._execute( cmd.format( self.STATE_INFO_TABLE, self._to_sqlite(count), self.STATE_INFO_ROW, ) ) self._update_cache_directory_state() self.database.commit() self.cursor.close() self.database.close() self.database = None self.cursor = None self.inserts = 0
[ "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 path = path_info["path"] assert os.path.exists(path) actual_mtime, actual_size = get_mtime_and_size(path) actual_inode = get_inode(path) existing_record = self.get_state_record_for_inode(actual_inode) if not existing_record: self._insert_new_state_record( path, actual_inode, actual_mtime, actual_size, checksum ) return self._update_state_for_path_changed( path, actual_inode, actual_mtime, actual_size, checksum )
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 path = path_info["path"] assert os.path.exists(path) actual_mtime, actual_size = get_mtime_and_size(path) actual_inode = get_inode(path) existing_record = self.get_state_record_for_inode(actual_inode) if not existing_record: self._insert_new_state_record( path, actual_inode, actual_mtime, actual_size, checksum ) return self._update_state_for_path_changed( path, actual_inode, actual_mtime, actual_size, checksum )
[ "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 None if it doesn't exist in the state database. """ assert path_info["scheme"] == "local" path = path_info["path"] if not os.path.exists(path): return None actual_mtime, actual_size = get_mtime_and_size(path) actual_inode = get_inode(path) existing_record = self.get_state_record_for_inode(actual_inode) if not existing_record: return None mtime, size, checksum, _ = existing_record if self._file_metadata_changed(actual_mtime, mtime, actual_size, size): return None self._update_state_record_timestamp_for_inode(actual_inode) return checksum
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 None if it doesn't exist in the state database. """ assert path_info["scheme"] == "local" path = path_info["path"] if not os.path.exists(path): return None actual_mtime, actual_size = get_mtime_and_size(path) actual_inode = get_inode(path) existing_record = self.get_state_record_for_inode(actual_inode) if not existing_record: return None mtime, size, checksum, _ = existing_record if self._file_metadata_changed(actual_mtime, mtime, actual_size, size): return None self._update_state_record_timestamp_for_inode(actual_inode) return checksum
[ "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 in the state database.
[ "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" path = path_info["path"] if not os.path.exists(path): return mtime, _ = get_mtime_and_size(path) inode = get_inode(path) relpath = os.path.relpath(path, self.root_dir) cmd = ( "REPLACE INTO {}(path, inode, mtime) " 'VALUES ("{}", {}, "{}")'.format( self.LINK_STATE_TABLE, relpath, self._to_sqlite(inode), mtime ) ) self._execute(cmd)
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" path = path_info["path"] if not os.path.exists(path): return mtime, _ = get_mtime_and_size(path) inode = get_inode(path) relpath = os.path.relpath(path, self.root_dir) cmd = ( "REPLACE INTO {}(path, inode, mtime) " 'VALUES ("{}", {}, "{}")'.format( self.LINK_STATE_TABLE, relpath, self._to_sqlite(inode), mtime ) ) self._execute(cmd)
[ "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.cursor: relpath, inode, mtime = row inode = self._from_sqlite(inode) path = os.path.join(self.root_dir, relpath) if path in used: continue if not os.path.exists(path): continue actual_inode = get_inode(path) actual_mtime, _ = get_mtime_and_size(path) if inode == actual_inode and mtime == actual_mtime: logger.debug("Removing '{}' as unused link.".format(path)) remove(path) unused.append(relpath) for relpath in unused: cmd = 'DELETE FROM {} WHERE path = "{}"' self._execute(cmd.format(self.LINK_STATE_TABLE, relpath))
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.cursor: relpath, inode, mtime = row inode = self._from_sqlite(inode) path = os.path.join(self.root_dir, relpath) if path in used: continue if not os.path.exists(path): continue actual_inode = get_inode(path) actual_mtime, _ = get_mtime_and_size(path) if inode == actual_inode and mtime == actual_mtime: logger.debug("Removing '{}' as unused link.".format(path)) remove(path) unused.append(relpath) for relpath in unused: cmd = 'DELETE FROM {} WHERE path = "{}"' self._execute(cmd.format(self.LINK_STATE_TABLE, relpath))
[ "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) canvas.itemconfigure(canvas.text, text=text) canvas.place(in_=self._calendar, x=x, y=y)
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) canvas.itemconfigure(canvas.text, text=text) canvas.place(in_=self._calendar, x=x, y=y)
[ "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._date.year, self._date.month, 1) self._build_calendar()
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._date.year, self._date.month, 1) self._build_calendar()
[ "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 the elements to a row ------------------------- # for i, element in enumerate(args): # Loop through list of elements and add them to the row element.Position = (CurrentRowNumber, i) element.ParentContainer = self CurrentRow.append(element) # ------------------------- Append the row to list of Rows ------------------------- # self.Rows.append(CurrentRow)
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 the elements to a row ------------------------- # for i, element in enumerate(args): # Loop through list of elements and add them to the row element.Position = (CurrentRowNumber, i) element.ParentContainer = self CurrentRow.append(element) # ------------------------- Append the row to list of Rows ------------------------- # self.Rows.append(CurrentRow)
[ "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.colorCode = self.colors['red'] self.colorCodeDark = self.colors['dred'] elif color == 'yellow': self.color = 'yellow' self.colorCode = self.colors['yellow'] self.colorCodeDark = self.colors['dyellow'] elif color == 'green': self.color = 'green' self.colorCode = self.colors['green'] self.colorCodeDark = self.colors['dgreen'] elif color == 'wild': # No color modification self.wild = True self.color = 'wild' self.colorCodeDark = self.colors['dwild'] self.colorCode = self.colors['wild']
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.colorCode = self.colors['red'] self.colorCodeDark = self.colors['dred'] elif color == 'yellow': self.color = 'yellow' self.colorCode = self.colors['yellow'] self.colorCodeDark = self.colors['dyellow'] elif color == 'green': self.color = 'green' self.colorCode = self.colors['green'] self.colorCodeDark = self.colors['dgreen'] elif color == 'wild': # No color modification self.wild = True self.color = 'wild' self.colorCodeDark = self.colors['dwild'] self.colorCode = self.colors['wild']
[ "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 return bio.getvalue() return ImageTk.PhotoImage(img)
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 return bio.getvalue() return ImageTk.PhotoImage(img)
[ "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.gethostbyname(hostname) except socket.gaierror as e: return 0,0,0,0 myStats.thisIP = destIP # This will send packet that we dont care about 0.5 seconds before it starts # acrutally pinging. This is needed in big MAN/LAN networks where you sometimes # loose the first packet. (while the switches find the way... :/ ) if path_finder: fakeStats = MyStats() do_one(fakeStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=True) time.sleep(0.5) for i in range(count): delay = do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=True) if delay == None: delay = 0 mySeqNumber += 1 # Pause for the remainder of the MAX_SLEEP period (if applicable) if (MAX_SLEEP > delay): time.sleep((MAX_SLEEP - delay)/1000) if myStats.pktsSent > 0: myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)/myStats.pktsSent if myStats.pktsRcvd > 0: myStats.avrgTime = myStats.totTime / myStats.pktsRcvd # return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost) return myStats.maxTime, myStats.minTime, myStats.avrgTime, myStats.fracLoss
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.gethostbyname(hostname) except socket.gaierror as e: return 0,0,0,0 myStats.thisIP = destIP # This will send packet that we dont care about 0.5 seconds before it starts # acrutally pinging. This is needed in big MAN/LAN networks where you sometimes # loose the first packet. (while the switches find the way... :/ ) if path_finder: fakeStats = MyStats() do_one(fakeStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=True) time.sleep(0.5) for i in range(count): delay = do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=True) if delay == None: delay = 0 mySeqNumber += 1 # Pause for the remainder of the MAX_SLEEP period (if applicable) if (MAX_SLEEP > delay): time.sleep((MAX_SLEEP - delay)/1000) if myStats.pktsSent > 0: myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)/myStats.pktsSent if myStats.pktsRcvd > 0: myStats.avrgTime = myStats.totTime / myStats.pktsRcvd # return tuple(max_rtt, min_rtt, avrg_rtt, percent_lost) return myStats.maxTime, myStats.minTime, myStats.avrgTime, myStats.fracLoss
[ "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_tab[pno] r = dlist.rect # the page rectangle clip = r # ensure image fits screen: # exploit, but do not exceed width or height zoom_0 = 1 if max_size: zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height) if zoom_0 == 1: zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height) mat_0 = fitz.Matrix(zoom_0, zoom_0) if not zoom: # show total page pix = dlist.getPixmap(matrix = mat_0, alpha=False) else: mp = r.tl + (r.br - r.tl) * 0.5 # page rect center w2 = r.width / 2 h2 = r.height / 2 clip = r * 0.5 tl = zoom[0] # old top-left tl.x += zoom[1] * (w2 / 2) tl.x = max(0, tl.x) tl.x = min(w2, tl.x) tl.y += zoom[2] * (h2 / 2) tl.y = max(0, tl.y) tl.y = min(h2, tl.y) clip = fitz.Rect(tl, tl.x + w2, tl.y + h2) mat = mat_0 * fitz.Matrix(2, 2) # zoom matrix pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip) if first: # first call: tkinter still inactive img = pix.getPNGData() # so use fitz png output else: # else take tk photo image pilimg = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) img = ImageTk.PhotoImage(pilimg) return img, clip.tl
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_tab[pno] r = dlist.rect # the page rectangle clip = r # ensure image fits screen: # exploit, but do not exceed width or height zoom_0 = 1 if max_size: zoom_0 = min(1, max_size[0] / r.width, max_size[1] / r.height) if zoom_0 == 1: zoom_0 = min(max_size[0] / r.width, max_size[1] / r.height) mat_0 = fitz.Matrix(zoom_0, zoom_0) if not zoom: # show total page pix = dlist.getPixmap(matrix = mat_0, alpha=False) else: mp = r.tl + (r.br - r.tl) * 0.5 # page rect center w2 = r.width / 2 h2 = r.height / 2 clip = r * 0.5 tl = zoom[0] # old top-left tl.x += zoom[1] * (w2 / 2) tl.x = max(0, tl.x) tl.x = min(w2, tl.x) tl.y += zoom[2] * (h2 / 2) tl.y = max(0, tl.y) tl.y = min(h2, tl.y) clip = fitz.Rect(tl, tl.x + w2, tl.y + h2) mat = mat_0 * fitz.Matrix(2, 2) # zoom matrix pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip) if first: # first call: tkinter still inactive img = pix.getPNGData() # so use fitz png output else: # else take tk photo image pilimg = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) img = ImageTk.PhotoImage(pilimg) return img, clip.tl
[ "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. for i in range(self.N): for j in range(self.N): live = self.live_neighbours(i, j) if (self.old_grid[i][j] == 1 and live < 2): self.new_grid[i][j] = 0 # Dead from starvation. elif (self.old_grid[i][j] == 1 and (live == 2 or live == 3)): self.new_grid[i][j] = 1 # Continue living. elif (self.old_grid[i][j] == 1 and live > 3): self.new_grid[i][j] = 0 # Dead from overcrowding. elif (self.old_grid[i][j] == 0 and live == 3): self.new_grid[i][j] = 1 # Alive from reproduction. # Output the new configuration. # The new configuration becomes the old configuration for the next generation. self.old_grid = self.new_grid.copy() self.draw_board() # Move on to the next time level self.t += 1
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. for i in range(self.N): for j in range(self.N): live = self.live_neighbours(i, j) if (self.old_grid[i][j] == 1 and live < 2): self.new_grid[i][j] = 0 # Dead from starvation. elif (self.old_grid[i][j] == 1 and (live == 2 or live == 3)): self.new_grid[i][j] = 1 # Continue living. elif (self.old_grid[i][j] == 1 and live > 3): self.new_grid[i][j] = 0 # Dead from overcrowding. elif (self.old_grid[i][j] == 0 and live == 3): self.new_grid[i][j] = 1 # Alive from reproduction. # Output the new configuration. # The new configuration becomes the old configuration for the next generation. self.old_grid = self.new_grid.copy() self.draw_board() # Move on to the next time level self.t += 1
[ "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) howLongInSelect = (default_timer() - startedSelect) if whatReady[0] == []: # Timeout return None, 0, 0, 0, 0 timeReceived = default_timer() recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV) ipHeader = recPacket[:20] iphVersion, iphTypeOfSvc, iphLength, \ iphID, iphFlags, iphTTL, iphProtocol, \ iphChecksum, iphSrcIP, iphDestIP = struct.unpack( "!BBHHHBBHII", ipHeader ) icmpHeader = recPacket[20:28] icmpType, icmpCode, icmpChecksum, \ icmpPacketID, icmpSeqNumber = struct.unpack( "!BBHHH", icmpHeader ) if icmpPacketID == myID: # Our packet dataSize = len(recPacket) - 28 #print (len(recPacket.encode())) return timeReceived, (dataSize+8), iphSrcIP, icmpSeqNumber, iphTTL timeLeft = timeLeft - howLongInSelect if timeLeft <= 0: return None, 0, 0, 0, 0
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) howLongInSelect = (default_timer() - startedSelect) if whatReady[0] == []: # Timeout return None, 0, 0, 0, 0 timeReceived = default_timer() recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV) ipHeader = recPacket[:20] iphVersion, iphTypeOfSvc, iphLength, \ iphID, iphFlags, iphTTL, iphProtocol, \ iphChecksum, iphSrcIP, iphDestIP = struct.unpack( "!BBHHHBBHII", ipHeader ) icmpHeader = recPacket[20:28] icmpType, icmpCode, icmpChecksum, \ icmpPacketID, icmpSeqNumber = struct.unpack( "!BBHHH", icmpHeader ) if icmpPacketID == myID: # Our packet dataSize = len(recPacket) - 28 #print (len(recPacket.encode())) return timeReceived, (dataSize+8), iphSrcIP, icmpSeqNumber, iphTTL timeLeft = timeLeft - howLongInSelect if timeLeft <= 0: return None, 0, 0, 0, 0
[ "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 variables to the intended values. Example usage: ```python spec = hub.create_module_spec(module_fn) spec.export("/path/to/export_module", checkpoint_path="/path/to/training_model") ``` In some cases, the variable name in the checkpoint does not match the variable name in the module. It is possible to work around that by providing a checkpoint_map_fn that performs the variable mapping. For example with: `name_transform_fn = lambda x: "extra_scope/" + x`. Args: path: path where to export the module to. _sentinel: used to prevent positional arguments besides `path`. checkpoint_path: path where to load the weights for the module. Mandatory parameter and must be passed by name. name_transform_fn: optional function to provide mapping between variable name in the module and the variable name in the checkpoint. Raises: ValueError: if missing mandatory `checkpoint_path` parameter. """ from tensorflow_hub.module import export_module_spec # pylint: disable=g-import-not-at-top if not checkpoint_path: raise ValueError("Missing mandatory `checkpoint_path` parameter") name_transform_fn = name_transform_fn or (lambda x: x) export_module_spec(self, path, checkpoint_path, name_transform_fn)
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 variables to the intended values. Example usage: ```python spec = hub.create_module_spec(module_fn) spec.export("/path/to/export_module", checkpoint_path="/path/to/training_model") ``` In some cases, the variable name in the checkpoint does not match the variable name in the module. It is possible to work around that by providing a checkpoint_map_fn that performs the variable mapping. For example with: `name_transform_fn = lambda x: "extra_scope/" + x`. Args: path: path where to export the module to. _sentinel: used to prevent positional arguments besides `path`. checkpoint_path: path where to load the weights for the module. Mandatory parameter and must be passed by name. name_transform_fn: optional function to provide mapping between variable name in the module and the variable name in the checkpoint. Raises: ValueError: if missing mandatory `checkpoint_path` parameter. """ from tensorflow_hub.module import export_module_spec # pylint: disable=g-import-not-at-top if not checkpoint_path: raise ValueError("Missing mandatory `checkpoint_path` parameter") name_transform_fn = name_transform_fn or (lambda x: x) export_module_spec(self, path, checkpoint_path, name_transform_fn)
[ "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/to/export_module", checkpoint_path="/path/to/training_model") ``` In some cases, the variable name in the checkpoint does not match the variable name in the module. It is possible to work around that by providing a checkpoint_map_fn that performs the variable mapping. For example with: `name_transform_fn = lambda x: "extra_scope/" + x`. Args: path: path where to export the module to. _sentinel: used to prevent positional arguments besides `path`. checkpoint_path: path where to load the weights for the module. Mandatory parameter and must be passed by name. name_transform_fn: optional function to provide mapping between variable name in the module and the variable name in the checkpoint. Raises: ValueError: if missing mandatory `checkpoint_path` parameter.
[ "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 usage or provenance (see see hub.attach_message()). A typical use would be to store a small set of named values with modules of a certain type so that a support library for consumers of such modules can be parametric in those values. This method can also be called on a Module instantiated from a ModuleSpec, then `tags` are set to those used in module instatiation. Args: key: A string with the key of an attached message. message_type: A concrete protocol message class (*not* object) used to parse the attached message from its serialized representation. The message type for a particular key must be advertised with the key. tags: Optional set of strings, specifying the graph variant from which to read the attached message. required: An optional boolean. Setting it true changes the effect of an unknown `key` from returning None to raising a KeyError with text about attached messages. Returns: An instance of `message_type` with the message contents attached to the module, or `None` if `key` is unknown and `required` is False. Raises: KeyError: if `key` is unknown and `required` is True. """ attached_bytes = self._get_attached_bytes(key, tags) if attached_bytes is None: if required: raise KeyError("No attached message for key '%s' in graph version %s " "of Hub Module" % (key, sorted(tags or []))) else: return None message = message_type() message.ParseFromString(attached_bytes) return message
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 usage or provenance (see see hub.attach_message()). A typical use would be to store a small set of named values with modules of a certain type so that a support library for consumers of such modules can be parametric in those values. This method can also be called on a Module instantiated from a ModuleSpec, then `tags` are set to those used in module instatiation. Args: key: A string with the key of an attached message. message_type: A concrete protocol message class (*not* object) used to parse the attached message from its serialized representation. The message type for a particular key must be advertised with the key. tags: Optional set of strings, specifying the graph variant from which to read the attached message. required: An optional boolean. Setting it true changes the effect of an unknown `key` from returning None to raising a KeyError with text about attached messages. Returns: An instance of `message_type` with the message contents attached to the module, or `None` if `key` is unknown and `required` is False. Raises: KeyError: if `key` is unknown and `required` is True. """ attached_bytes = self._get_attached_bytes(key, tags) if attached_bytes is None: if required: raise KeyError("No attached message for key '%s' in graph version %s " "of Hub Module" % (key, sorted(tags or []))) else: return None message = message_type() message.ParseFromString(attached_bytes) return message
[ "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 store a small set of named values with modules of a certain type so that a support library for consumers of such modules can be parametric in those values. This method can also be called on a Module instantiated from a ModuleSpec, then `tags` are set to those used in module instatiation. Args: key: A string with the key of an attached message. message_type: A concrete protocol message class (*not* object) used to parse the attached message from its serialized representation. The message type for a particular key must be advertised with the key. tags: Optional set of strings, specifying the graph variant from which to read the attached message. required: An optional boolean. Setting it true changes the effect of an unknown `key` from returning None to raising a KeyError with text about attached messages. Returns: An instance of `message_type` with the message contents attached to the module, or `None` if `key` is unknown and `required` is False. Raises: KeyError: if `key` is unknown and `required` is True.
[ "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 for each label and their paths. Args: image_dir: String path to a folder containing subfolders of images. testing_percentage: Integer percentage of the images to reserve for tests. validation_percentage: Integer percentage of images reserved for validation. Returns: An OrderedDict containing an entry for each label subfolder, with images split into training, testing, and validation sets within each label. The order of items defines the class indices. """ if not tf.gfile.Exists(image_dir): tf.logging.error("Image directory '" + image_dir + "' not found.") return None result = collections.OrderedDict() sub_dirs = sorted(x[0] for x in tf.gfile.Walk(image_dir)) # The root directory comes first, so skip it. is_root_dir = True for sub_dir in sub_dirs: if is_root_dir: is_root_dir = False continue extensions = sorted(set(os.path.normcase(ext) # Smash case on Windows. for ext in ['JPEG', 'JPG', 'jpeg', 'jpg', 'png'])) file_list = [] dir_name = os.path.basename( # tf.gfile.Walk() returns sub-directory with trailing '/' when it is in # Google Cloud Storage, which confuses os.path.basename(). sub_dir[:-1] if sub_dir.endswith('/') else sub_dir) if dir_name == image_dir: continue tf.logging.info("Looking for images in '" + dir_name + "'") for extension in extensions: file_glob = os.path.join(image_dir, dir_name, '*.' + extension) file_list.extend(tf.gfile.Glob(file_glob)) if not file_list: tf.logging.warning('No files found') continue if len(file_list) < 20: tf.logging.warning( 'WARNING: Folder has less than 20 images, which may cause issues.') elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS: tf.logging.warning( 'WARNING: Folder {} has more than {} images. Some images will ' 'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS)) label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower()) training_images = [] testing_images = [] validation_images = [] for file_name in file_list: base_name = os.path.basename(file_name) # We want to ignore anything after '_nohash_' in the file name when # deciding which set to put an image in, the data set creator has a way of # grouping photos that are close variations of each other. For example # this is used in the plant disease data set to group multiple pictures of # the same leaf. hash_name = re.sub(r'_nohash_.*$', '', file_name) # This looks a bit magical, but we need to decide whether this file should # go into the training, testing, or validation sets, and we want to keep # existing files in the same set even if more files are subsequently # added. # To do that, we need a stable way of deciding based on just the file name # itself, so we do a hash of that and then use that to generate a # probability value that we use to assign it. hash_name_hashed = hashlib.sha1(tf.compat.as_bytes(hash_name)).hexdigest() percentage_hash = ((int(hash_name_hashed, 16) % (MAX_NUM_IMAGES_PER_CLASS + 1)) * (100.0 / MAX_NUM_IMAGES_PER_CLASS)) if percentage_hash < validation_percentage: validation_images.append(base_name) elif percentage_hash < (testing_percentage + validation_percentage): testing_images.append(base_name) else: training_images.append(base_name) result[label_name] = { 'dir': dir_name, 'training': training_images, 'testing': testing_images, 'validation': validation_images, } return result
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 for each label and their paths. Args: image_dir: String path to a folder containing subfolders of images. testing_percentage: Integer percentage of the images to reserve for tests. validation_percentage: Integer percentage of images reserved for validation. Returns: An OrderedDict containing an entry for each label subfolder, with images split into training, testing, and validation sets within each label. The order of items defines the class indices. """ if not tf.gfile.Exists(image_dir): tf.logging.error("Image directory '" + image_dir + "' not found.") return None result = collections.OrderedDict() sub_dirs = sorted(x[0] for x in tf.gfile.Walk(image_dir)) # The root directory comes first, so skip it. is_root_dir = True for sub_dir in sub_dirs: if is_root_dir: is_root_dir = False continue extensions = sorted(set(os.path.normcase(ext) # Smash case on Windows. for ext in ['JPEG', 'JPG', 'jpeg', 'jpg', 'png'])) file_list = [] dir_name = os.path.basename( # tf.gfile.Walk() returns sub-directory with trailing '/' when it is in # Google Cloud Storage, which confuses os.path.basename(). sub_dir[:-1] if sub_dir.endswith('/') else sub_dir) if dir_name == image_dir: continue tf.logging.info("Looking for images in '" + dir_name + "'") for extension in extensions: file_glob = os.path.join(image_dir, dir_name, '*.' + extension) file_list.extend(tf.gfile.Glob(file_glob)) if not file_list: tf.logging.warning('No files found') continue if len(file_list) < 20: tf.logging.warning( 'WARNING: Folder has less than 20 images, which may cause issues.') elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS: tf.logging.warning( 'WARNING: Folder {} has more than {} images. Some images will ' 'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS)) label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower()) training_images = [] testing_images = [] validation_images = [] for file_name in file_list: base_name = os.path.basename(file_name) # We want to ignore anything after '_nohash_' in the file name when # deciding which set to put an image in, the data set creator has a way of # grouping photos that are close variations of each other. For example # this is used in the plant disease data set to group multiple pictures of # the same leaf. hash_name = re.sub(r'_nohash_.*$', '', file_name) # This looks a bit magical, but we need to decide whether this file should # go into the training, testing, or validation sets, and we want to keep # existing files in the same set even if more files are subsequently # added. # To do that, we need a stable way of deciding based on just the file name # itself, so we do a hash of that and then use that to generate a # probability value that we use to assign it. hash_name_hashed = hashlib.sha1(tf.compat.as_bytes(hash_name)).hexdigest() percentage_hash = ((int(hash_name_hashed, 16) % (MAX_NUM_IMAGES_PER_CLASS + 1)) * (100.0 / MAX_NUM_IMAGES_PER_CLASS)) if percentage_hash < validation_percentage: validation_images.append(base_name) elif percentage_hash < (testing_percentage + validation_percentage): testing_images.append(base_name) else: training_images.append(base_name) result[label_name] = { 'dir': dir_name, 'training': training_images, 'testing': testing_images, 'validation': validation_images, } return result
[ "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 containing subfolders of images. testing_percentage: Integer percentage of the images to reserve for tests. validation_percentage: Integer percentage of images reserved for validation. Returns: An OrderedDict containing an entry for each label subfolder, with images split into training, testing, and validation sets within each label. The order of items defines the class indices.
[ "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 will be moduloed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of set to pull images from - training, testing, or validation. Returns: File system path string to an image that meets the requested parameters. """ if label_name not in image_lists: tf.logging.fatal('Label does not exist %s.', label_name) label_lists = image_lists[label_name] if category not in label_lists: tf.logging.fatal('Category does not exist %s.', category) category_list = label_lists[category] if not category_list: tf.logging.fatal('Label %s has no images in the category %s.', label_name, category) mod_index = index % len(category_list) base_name = category_list[mod_index] sub_dir = label_lists['dir'] full_path = os.path.join(image_dir, sub_dir, base_name) return full_path
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 will be moduloed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of set to pull images from - training, testing, or validation. Returns: File system path string to an image that meets the requested parameters. """ if label_name not in image_lists: tf.logging.fatal('Label does not exist %s.', label_name) label_lists = image_lists[label_name] if category not in label_lists: tf.logging.fatal('Category does not exist %s.', category) category_list = label_lists[category] if not category_list: tf.logging.fatal('Label %s has no images in the category %s.', label_name, category) mod_index = index % len(category_list) base_name = category_list[mod_index] sub_dir = label_lists['dir'] full_path = os.path.join(image_dir, sub_dir, base_name) return full_path
[ "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 be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of set to pull images from - training, testing, or validation. Returns: File system path string to an image that meets the requested parameters.
[ "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 for. index: Integer offset of the image we want. This will be moduloed by the available number of images for the label, so it can be arbitrarily large. bottleneck_dir: Folder string holding cached files of bottleneck values. category: Name string of set to pull images from - training, testing, or validation. module_name: The name of the image module being used. Returns: File system path string to an image that meets the requested parameters. """ module_name = (module_name.replace('://', '~') # URL scheme. .replace('/', '~') # URL and Unix paths. .replace(':', '~').replace('\\', '~')) # Windows paths. return get_image_path(image_lists, label_name, index, bottleneck_dir, category) + '_' + module_name + '.txt'
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 for. index: Integer offset of the image we want. This will be moduloed by the available number of images for the label, so it can be arbitrarily large. bottleneck_dir: Folder string holding cached files of bottleneck values. category: Name string of set to pull images from - training, testing, or validation. module_name: The name of the image module being used. Returns: File system path string to an image that meets the requested parameters. """ module_name = (module_name.replace('://', '~') # URL scheme. .replace('/', '~') # URL and Unix paths. .replace(':', '~').replace('\\', '~')) # Windows paths. return get_image_path(image_lists, label_name, index, bottleneck_dir, category) + '_' + module_name + '.txt'
[ "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, so it can be arbitrarily large. bottleneck_dir: Folder string holding cached files of bottleneck values. category: Name string of set to pull images from - training, testing, or validation. module_name: The name of the image module being used. Returns: File system path string to an image that meets the requested parameters.
[ "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 input images, resized as expected by the module. wants_quantization: a boolean, whether the module has been instrumented with fake quantization ops. """ height, width = hub.get_expected_image_size(module_spec) with tf.Graph().as_default() as graph: resized_input_tensor = tf.placeholder(tf.float32, [None, height, width, 3]) m = hub.Module(module_spec) bottleneck_tensor = m(resized_input_tensor) wants_quantization = any(node.op in FAKE_QUANT_OPS for node in graph.as_graph_def().node) return graph, bottleneck_tensor, resized_input_tensor, wants_quantization
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 input images, resized as expected by the module. wants_quantization: a boolean, whether the module has been instrumented with fake quantization ops. """ height, width = hub.get_expected_image_size(module_spec) with tf.Graph().as_default() as graph: resized_input_tensor = tf.placeholder(tf.float32, [None, height, width, 3]) m = hub.Module(module_spec) bottleneck_tensor = m(resized_input_tensor) wants_quantization = any(node.op in FAKE_QUANT_OPS for node in graph.as_graph_def().node) return graph, bottleneck_tensor, resized_input_tensor, wants_quantization
[ "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 module. wants_quantization: a boolean, whether the module has been instrumented with fake quantization ops.
[ "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. 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_tensor: The input node of the recognition graph. bottleneck_tensor: Layer before the final softmax. Returns: Numpy array of bottleneck values. """ # First decode the JPEG image, resize it, and rescale the pixel values. resized_input_values = sess.run(decoded_image_tensor, {image_data_tensor: image_data}) # Then run it through the recognition network. bottleneck_values = sess.run(bottleneck_tensor, {resized_input_tensor: resized_input_values}) bottleneck_values = np.squeeze(bottleneck_values) return bottleneck_values
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. 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_tensor: The input node of the recognition graph. bottleneck_tensor: Layer before the final softmax. Returns: Numpy array of bottleneck values. """ # First decode the JPEG image, resize it, and rescale the pixel values. resized_input_values = sess.run(decoded_image_tensor, {image_data_tensor: image_data}) # Then run it through the recognition network. bottleneck_values = sess.run(bottleneck_tensor, {resized_input_tensor: resized_input_values}) bottleneck_values = np.squeeze(bottleneck_values) return bottleneck_values
[ "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_tensor: The input node of the recognition graph. bottleneck_tensor: Layer before the final softmax. Returns: Numpy array of bottleneck values.
[ "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.debug('Creating bottleneck at ' + bottleneck_path) image_path = get_image_path(image_lists, label_name, index, image_dir, category) if not tf.gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) image_data = tf.gfile.GFile(image_path, 'rb').read() try: bottleneck_values = run_bottleneck_on_image( sess, image_data, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor) except Exception as e: raise RuntimeError('Error during processing file %s (%s)' % (image_path, str(e))) bottleneck_string = ','.join(str(x) for x in bottleneck_values) with open(bottleneck_path, 'w') as bottleneck_file: bottleneck_file.write(bottleneck_string)
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.debug('Creating bottleneck at ' + bottleneck_path) image_path = get_image_path(image_lists, label_name, index, image_dir, category) if not tf.gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) image_data = tf.gfile.GFile(image_path, 'rb').read() try: bottleneck_values = run_bottleneck_on_image( sess, image_data, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor) except Exception as e: raise RuntimeError('Error during processing file %s (%s)' % (image_path, str(e))) bottleneck_string = ','.join(str(x) for x in bottleneck_values) with open(bottleneck_path, 'w') as bottleneck_file: bottleneck_file.write(bottleneck_string)
[ "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 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. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be modulo-ed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of which set to pull images from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: The tensor to feed loaded jpeg data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The output tensor for the bottleneck values. module_name: The name of the image module being used. Returns: Numpy array of values produced by the bottleneck layer for the image. """ label_lists = image_lists[label_name] sub_dir = label_lists['dir'] sub_dir_path = os.path.join(bottleneck_dir, sub_dir) ensure_dir_exists(sub_dir_path) bottleneck_path = get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category, module_name) if not os.path.exists(bottleneck_path): 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) with open(bottleneck_path, 'r') as bottleneck_file: bottleneck_string = bottleneck_file.read() did_hit_error = False try: bottleneck_values = [float(x) for x in bottleneck_string.split(',')] except ValueError: tf.logging.warning('Invalid float found, recreating bottleneck') did_hit_error = True if did_hit_error: 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) with open(bottleneck_path, 'r') as bottleneck_file: bottleneck_string = bottleneck_file.read() # Allow exceptions to propagate here, since they shouldn't happen after a # fresh creation bottleneck_values = [float(x) for x in bottleneck_string.split(',')] return bottleneck_values
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 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. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be modulo-ed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of which set to pull images from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: The tensor to feed loaded jpeg data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The output tensor for the bottleneck values. module_name: The name of the image module being used. Returns: Numpy array of values produced by the bottleneck layer for the image. """ label_lists = image_lists[label_name] sub_dir = label_lists['dir'] sub_dir_path = os.path.join(bottleneck_dir, sub_dir) ensure_dir_exists(sub_dir_path) bottleneck_path = get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category, module_name) if not os.path.exists(bottleneck_path): 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) with open(bottleneck_path, 'r') as bottleneck_file: bottleneck_string = bottleneck_file.read() did_hit_error = False try: bottleneck_values = [float(x) for x in bottleneck_string.split(',')] except ValueError: tf.logging.warning('Invalid float found, recreating bottleneck') did_hit_error = True if did_hit_error: 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) with open(bottleneck_path, 'r') as bottleneck_file: bottleneck_string = bottleneck_file.read() # Allow exceptions to propagate here, since they shouldn't happen after a # fresh creation bottleneck_values = [float(x) for x in bottleneck_string.split(',')] return bottleneck_values
[ "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. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be modulo-ed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of which set to pull images from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: The tensor to feed loaded jpeg data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The output tensor for the bottleneck values. module_name: The name of the image module being used. Returns: Numpy array of values produced by the bottleneck layer for the image.
[ "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 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 just read those cached values repeatedly during training. Here we go through all the images we've found, calculate those values, and save them off. Args: sess: The current active TensorFlow Session. image_lists: OrderedDict of training images for each label. image_dir: Root folder string of the subfolders containing the training images. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: Input tensor for jpeg data from file. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The penultimate output layer of the graph. module_name: The name of the image module being used. Returns: Nothing. """ how_many_bottlenecks = 0 ensure_dir_exists(bottleneck_dir) for label_name, label_lists in image_lists.items(): for category in ['training', 'testing', 'validation']: category_list = label_lists[category] for index, unused_base_name in enumerate(category_list): 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) how_many_bottlenecks += 1 if how_many_bottlenecks % 100 == 0: tf.logging.info( str(how_many_bottlenecks) + ' bottleneck files created.')
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 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 just read those cached values repeatedly during training. Here we go through all the images we've found, calculate those values, and save them off. Args: sess: The current active TensorFlow Session. image_lists: OrderedDict of training images for each label. image_dir: Root folder string of the subfolders containing the training images. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: Input tensor for jpeg data from file. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The penultimate output layer of the graph. module_name: The name of the image module being used. Returns: Nothing. """ how_many_bottlenecks = 0 ensure_dir_exists(bottleneck_dir) for label_name, label_lists in image_lists.items(): for category in ['training', 'testing', 'validation']: category_list = label_lists[category] for index, unused_base_name in enumerate(category_list): 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) how_many_bottlenecks += 1 if how_many_bottlenecks % 100 == 0: tf.logging.info( str(how_many_bottlenecks) + ' bottleneck files created.')
[ "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 just read those cached values repeatedly during training. Here we go through all the images we've found, calculate those values, and save them off. Args: sess: The current active TensorFlow Session. image_lists: OrderedDict of training images for each label. image_dir: Root folder string of the subfolders containing the training images. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: Input tensor for jpeg data from file. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The penultimate output layer of the graph. module_name: The name of the image module being used. Returns: Nothing.
[ "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 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 training images for each label. how_many: If positive, a random sample of this size will be chosen. If negative, all bottlenecks will be retrieved. category: Name string of which set to pull from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. image_dir: Root folder string of the subfolders containing the training images. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. module_name: The name of the image module being used. Returns: List of bottleneck arrays, their corresponding ground truths, and the relevant filenames. """ class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] filenames = [] if how_many >= 0: # Retrieve a random sample of bottlenecks. for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) image_name = get_image_path(image_lists, label_name, image_index, image_dir, category) bottleneck = get_or_create_bottleneck( sess, image_lists, label_name, image_index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name) bottlenecks.append(bottleneck) ground_truths.append(label_index) filenames.append(image_name) else: # Retrieve all bottlenecks. for label_index, label_name in enumerate(image_lists.keys()): for image_index, image_name in enumerate( image_lists[label_name][category]): image_name = get_image_path(image_lists, label_name, image_index, image_dir, category) bottleneck = get_or_create_bottleneck( sess, image_lists, label_name, image_index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name) bottlenecks.append(bottleneck) ground_truths.append(label_index) filenames.append(image_name) return bottlenecks, ground_truths, filenames
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 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 training images for each label. how_many: If positive, a random sample of this size will be chosen. If negative, all bottlenecks will be retrieved. category: Name string of which set to pull from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. image_dir: Root folder string of the subfolders containing the training images. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. module_name: The name of the image module being used. Returns: List of bottleneck arrays, their corresponding ground truths, and the relevant filenames. """ class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] filenames = [] if how_many >= 0: # Retrieve a random sample of bottlenecks. for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) image_name = get_image_path(image_lists, label_name, image_index, image_dir, category) bottleneck = get_or_create_bottleneck( sess, image_lists, label_name, image_index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name) bottlenecks.append(bottleneck) ground_truths.append(label_index) filenames.append(image_name) else: # Retrieve all bottlenecks. for label_index, label_name in enumerate(image_lists.keys()): for image_index, image_name in enumerate( image_lists[label_name][category]): image_name = get_image_path(image_lists, label_name, image_index, image_dir, category) bottleneck = get_or_create_bottleneck( sess, image_lists, label_name, image_index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name) bottlenecks.append(bottleneck) ground_truths.append(label_index) filenames.append(image_name) return bottlenecks, ground_truths, filenames
[ "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 training images for each label. how_many: If positive, a random sample of this size will be chosen. If negative, all bottlenecks will be retrieved. category: Name string of which set to pull from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. image_dir: Root folder string of the subfolders containing the training images. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. module_name: The name of the image module being used. Returns: List of bottleneck arrays, their corresponding ground truths, and the relevant filenames.
[ "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 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 the distortion graph, and then the full graph to get the bottleneck results for each. Args: sess: Current TensorFlow Session. image_lists: OrderedDict of training images for each label. how_many: The integer number of bottleneck values to return. category: Name string of which set of images to fetch - training, testing, or validation. image_dir: Root folder string of the subfolders containing the training images. input_jpeg_tensor: The input layer we feed the image data to. distorted_image: The output node of the distortion graph. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. Returns: List of bottleneck arrays and their corresponding ground truths. """ class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) image_path = get_image_path(image_lists, label_name, image_index, image_dir, category) if not tf.gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) jpeg_data = tf.gfile.GFile(image_path, 'rb').read() # Note that we materialize the distorted_image_data as a numpy array before # sending running inference on the image. This involves 2 memory copies and # might be optimized in other implementations. distorted_image_data = sess.run(distorted_image, {input_jpeg_tensor: jpeg_data}) bottleneck_values = sess.run(bottleneck_tensor, {resized_input_tensor: distorted_image_data}) bottleneck_values = np.squeeze(bottleneck_values) bottlenecks.append(bottleneck_values) ground_truths.append(label_index) return bottlenecks, ground_truths
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 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 the distortion graph, and then the full graph to get the bottleneck results for each. Args: sess: Current TensorFlow Session. image_lists: OrderedDict of training images for each label. how_many: The integer number of bottleneck values to return. category: Name string of which set of images to fetch - training, testing, or validation. image_dir: Root folder string of the subfolders containing the training images. input_jpeg_tensor: The input layer we feed the image data to. distorted_image: The output node of the distortion graph. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. Returns: List of bottleneck arrays and their corresponding ground truths. """ class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) image_path = get_image_path(image_lists, label_name, image_index, image_dir, category) if not tf.gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) jpeg_data = tf.gfile.GFile(image_path, 'rb').read() # Note that we materialize the distorted_image_data as a numpy array before # sending running inference on the image. This involves 2 memory copies and # might be optimized in other implementations. distorted_image_data = sess.run(distorted_image, {input_jpeg_tensor: jpeg_data}) bottleneck_values = sess.run(bottleneck_tensor, {resized_input_tensor: distorted_image_data}) bottleneck_values = np.squeeze(bottleneck_values) bottlenecks.append(bottleneck_values) ground_truths.append(label_index) return bottlenecks, ground_truths
[ "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 the distortion graph, and then the full graph to get the bottleneck results for each. Args: sess: Current TensorFlow Session. image_lists: OrderedDict of training images for each label. how_many: The integer number of bottleneck values to return. category: Name string of which set of images to fetch - training, testing, or validation. image_dir: Root folder string of the subfolders containing the training images. input_jpeg_tensor: The input layer we feed the image data to. distorted_image: The output node of the distortion graph. resized_input_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. Returns: List of bottleneck arrays and their corresponding ground truths.
[ "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 flips. These reflect the kind of variations we expect in the real world, and so can help train the model to cope with natural data more effectively. Here we take the supplied parameters and construct a network of operations to apply them to an image. Cropping ~~~~~~~~ Cropping is done by placing a bounding box at a random position in the full image. The cropping parameter controls the size of that box relative to the input image. If it's zero, then the box is the same size as the input and no cropping is performed. If the value is 50%, then the crop box will be half the width and height of the input. In a diagram it looks like this: < width > +---------------------+ | | | width - crop% | | < > | | +------+ | | | | | | | | | | | | | | +------+ | | | | | +---------------------+ Scaling ~~~~~~~ Scaling is a lot like cropping, except that the bounding box is always centered and its size varies randomly within the given range. For example if the scale percentage is zero, then the bounding box is the same size as the input and no scaling is applied. If it's 50%, then the bounding box will be in a random range between half the width and height and full size. Args: flip_left_right: Boolean whether to randomly mirror images horizontally. random_crop: Integer percentage setting the total margin used around the crop box. random_scale: Integer percentage of how much to vary the scale by. random_brightness: Integer range to randomly multiply the pixel values by. graph. module_spec: The hub.ModuleSpec for the image module being used. Returns: The jpeg input layer and the distorted result tensor. """ input_height, input_width = hub.get_expected_image_size(module_spec) input_depth = hub.get_num_image_channels(module_spec) jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) # Convert from full range of uint8 to range [0,1] of float32. decoded_image_as_float = tf.image.convert_image_dtype(decoded_image, tf.float32) decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0) margin_scale = 1.0 + (random_crop / 100.0) resize_scale = 1.0 + (random_scale / 100.0) margin_scale_value = tf.constant(margin_scale) resize_scale_value = tf.random_uniform(shape=[], minval=1.0, maxval=resize_scale) scale_value = tf.multiply(margin_scale_value, resize_scale_value) precrop_width = tf.multiply(scale_value, input_width) precrop_height = tf.multiply(scale_value, input_height) precrop_shape = tf.stack([precrop_height, precrop_width]) precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32) precropped_image = tf.image.resize_bilinear(decoded_image_4d, precrop_shape_as_int) precropped_image_3d = tf.squeeze(precropped_image, axis=[0]) cropped_image = tf.random_crop(precropped_image_3d, [input_height, input_width, input_depth]) if flip_left_right: flipped_image = tf.image.random_flip_left_right(cropped_image) else: flipped_image = cropped_image brightness_min = 1.0 - (random_brightness / 100.0) brightness_max = 1.0 + (random_brightness / 100.0) brightness_value = tf.random_uniform(shape=[], minval=brightness_min, maxval=brightness_max) brightened_image = tf.multiply(flipped_image, brightness_value) distort_result = tf.expand_dims(brightened_image, 0, name='DistortResult') return jpeg_data, distort_result
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 flips. These reflect the kind of variations we expect in the real world, and so can help train the model to cope with natural data more effectively. Here we take the supplied parameters and construct a network of operations to apply them to an image. Cropping ~~~~~~~~ Cropping is done by placing a bounding box at a random position in the full image. The cropping parameter controls the size of that box relative to the input image. If it's zero, then the box is the same size as the input and no cropping is performed. If the value is 50%, then the crop box will be half the width and height of the input. In a diagram it looks like this: < width > +---------------------+ | | | width - crop% | | < > | | +------+ | | | | | | | | | | | | | | +------+ | | | | | +---------------------+ Scaling ~~~~~~~ Scaling is a lot like cropping, except that the bounding box is always centered and its size varies randomly within the given range. For example if the scale percentage is zero, then the bounding box is the same size as the input and no scaling is applied. If it's 50%, then the bounding box will be in a random range between half the width and height and full size. Args: flip_left_right: Boolean whether to randomly mirror images horizontally. random_crop: Integer percentage setting the total margin used around the crop box. random_scale: Integer percentage of how much to vary the scale by. random_brightness: Integer range to randomly multiply the pixel values by. graph. module_spec: The hub.ModuleSpec for the image module being used. Returns: The jpeg input layer and the distorted result tensor. """ input_height, input_width = hub.get_expected_image_size(module_spec) input_depth = hub.get_num_image_channels(module_spec) jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) # Convert from full range of uint8 to range [0,1] of float32. decoded_image_as_float = tf.image.convert_image_dtype(decoded_image, tf.float32) decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0) margin_scale = 1.0 + (random_crop / 100.0) resize_scale = 1.0 + (random_scale / 100.0) margin_scale_value = tf.constant(margin_scale) resize_scale_value = tf.random_uniform(shape=[], minval=1.0, maxval=resize_scale) scale_value = tf.multiply(margin_scale_value, resize_scale_value) precrop_width = tf.multiply(scale_value, input_width) precrop_height = tf.multiply(scale_value, input_height) precrop_shape = tf.stack([precrop_height, precrop_width]) precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32) precropped_image = tf.image.resize_bilinear(decoded_image_4d, precrop_shape_as_int) precropped_image_3d = tf.squeeze(precropped_image, axis=[0]) cropped_image = tf.random_crop(precropped_image_3d, [input_height, input_width, input_depth]) if flip_left_right: flipped_image = tf.image.random_flip_left_right(cropped_image) else: flipped_image = cropped_image brightness_min = 1.0 - (random_brightness / 100.0) brightness_max = 1.0 + (random_brightness / 100.0) brightness_value = tf.random_uniform(shape=[], minval=brightness_min, maxval=brightness_max) brightened_image = tf.multiply(flipped_image, brightness_value) distort_result = tf.expand_dims(brightened_image, 0, name='DistortResult') return jpeg_data, distort_result
[ "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 data more effectively. Here we take the supplied parameters and construct a network of operations to apply them to an image. Cropping ~~~~~~~~ Cropping is done by placing a bounding box at a random position in the full image. The cropping parameter controls the size of that box relative to the input image. If it's zero, then the box is the same size as the input and no cropping is performed. If the value is 50%, then the crop box will be half the width and height of the input. In a diagram it looks like this: < width > +---------------------+ | | | width - crop% | | < > | | +------+ | | | | | | | | | | | | | | +------+ | | | | | +---------------------+ Scaling ~~~~~~~ Scaling is a lot like cropping, except that the bounding box is always centered and its size varies randomly within the given range. For example if the scale percentage is zero, then the bounding box is the same size as the input and no scaling is applied. If it's 50%, then the bounding box will be in a random range between half the width and height and full size. Args: flip_left_right: Boolean whether to randomly mirror images horizontally. random_crop: Integer percentage setting the total margin used around the crop box. random_scale: Integer percentage of how much to vary the scale by. random_brightness: Integer range to randomly multiply the pixel values by. graph. module_spec: The hub.ModuleSpec for the image module being used. Returns: The jpeg input layer and the distorted result tensor.
[ "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 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 softmax and fully-connected layers is based on: https://www.tensorflow.org/tutorials/mnist/beginners/index.html Args: class_count: Integer of how many categories of things we're trying to recognize. final_tensor_name: Name string for the new final node that produces results. bottleneck_tensor: The output of the main CNN graph. quantize_layer: Boolean, specifying whether the newly added layer should be instrumented for quantization with TF-Lite. is_training: Boolean, specifying whether the newly add layer is for training or eval. Returns: The tensors for the training and cross entropy results, and tensors for the bottleneck input and ground truth input. """ batch_size, bottleneck_tensor_size = bottleneck_tensor.get_shape().as_list() assert batch_size is None, 'We want to work with arbitrary batch size.' with tf.name_scope('input'): bottleneck_input = tf.placeholder_with_default( bottleneck_tensor, shape=[batch_size, bottleneck_tensor_size], name='BottleneckInputPlaceholder') ground_truth_input = tf.placeholder( tf.int64, [batch_size], name='GroundTruthInput') # Organizing the following ops so they are easier to see in TensorBoard. layer_name = 'final_retrain_ops' with tf.name_scope(layer_name): with tf.name_scope('weights'): initial_value = tf.truncated_normal( [bottleneck_tensor_size, class_count], stddev=0.001) layer_weights = tf.Variable(initial_value, name='final_weights') variable_summaries(layer_weights) with tf.name_scope('biases'): layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases') variable_summaries(layer_biases) with tf.name_scope('Wx_plus_b'): logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases tf.summary.histogram('pre_activations', logits) final_tensor = tf.nn.softmax(logits, name=final_tensor_name) # The tf.contrib.quantize functions rewrite the graph in place for # quantization. The imported model graph has already been rewritten, so upon # calling these rewrites, only the newly added final layer will be # transformed. if quantize_layer: if is_training: tf.contrib.quantize.create_training_graph() else: tf.contrib.quantize.create_eval_graph() tf.summary.histogram('activations', final_tensor) # If this is an eval graph, we don't need to add loss ops or an optimizer. if not is_training: return None, None, bottleneck_input, ground_truth_input, final_tensor with tf.name_scope('cross_entropy'): cross_entropy_mean = tf.losses.sparse_softmax_cross_entropy( labels=ground_truth_input, logits=logits) tf.summary.scalar('cross_entropy', cross_entropy_mean) with tf.name_scope('train'): optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate) train_step = optimizer.minimize(cross_entropy_mean) return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input, final_tensor)
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 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 softmax and fully-connected layers is based on: https://www.tensorflow.org/tutorials/mnist/beginners/index.html Args: class_count: Integer of how many categories of things we're trying to recognize. final_tensor_name: Name string for the new final node that produces results. bottleneck_tensor: The output of the main CNN graph. quantize_layer: Boolean, specifying whether the newly added layer should be instrumented for quantization with TF-Lite. is_training: Boolean, specifying whether the newly add layer is for training or eval. Returns: The tensors for the training and cross entropy results, and tensors for the bottleneck input and ground truth input. """ batch_size, bottleneck_tensor_size = bottleneck_tensor.get_shape().as_list() assert batch_size is None, 'We want to work with arbitrary batch size.' with tf.name_scope('input'): bottleneck_input = tf.placeholder_with_default( bottleneck_tensor, shape=[batch_size, bottleneck_tensor_size], name='BottleneckInputPlaceholder') ground_truth_input = tf.placeholder( tf.int64, [batch_size], name='GroundTruthInput') # Organizing the following ops so they are easier to see in TensorBoard. layer_name = 'final_retrain_ops' with tf.name_scope(layer_name): with tf.name_scope('weights'): initial_value = tf.truncated_normal( [bottleneck_tensor_size, class_count], stddev=0.001) layer_weights = tf.Variable(initial_value, name='final_weights') variable_summaries(layer_weights) with tf.name_scope('biases'): layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases') variable_summaries(layer_biases) with tf.name_scope('Wx_plus_b'): logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases tf.summary.histogram('pre_activations', logits) final_tensor = tf.nn.softmax(logits, name=final_tensor_name) # The tf.contrib.quantize functions rewrite the graph in place for # quantization. The imported model graph has already been rewritten, so upon # calling these rewrites, only the newly added final layer will be # transformed. if quantize_layer: if is_training: tf.contrib.quantize.create_training_graph() else: tf.contrib.quantize.create_eval_graph() tf.summary.histogram('activations', final_tensor) # If this is an eval graph, we don't need to add loss ops or an optimizer. if not is_training: return None, None, bottleneck_input, ground_truth_input, final_tensor with tf.name_scope('cross_entropy'): cross_entropy_mean = tf.losses.sparse_softmax_cross_entropy( labels=ground_truth_input, logits=logits) tf.summary.scalar('cross_entropy', cross_entropy_mean) with tf.name_scope('train'): optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate) train_step = optimizer.minimize(cross_entropy_mean) return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input, final_tensor)
[ "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 softmax and fully-connected layers is based on: https://www.tensorflow.org/tutorials/mnist/beginners/index.html Args: class_count: Integer of how many categories of things we're trying to recognize. final_tensor_name: Name string for the new final node that produces results. bottleneck_tensor: The output of the main CNN graph. quantize_layer: Boolean, specifying whether the newly added layer should be instrumented for quantization with TF-Lite. is_training: Boolean, specifying whether the newly add layer is for training or eval. Returns: The tensors for the training and cross entropy results, and tensors for the bottleneck input and ground truth input.
[ "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, prediction). """ with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): prediction = tf.argmax(result_tensor, 1) correct_prediction = tf.equal(prediction, ground_truth_tensor) with tf.name_scope('accuracy'): evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', evaluation_step) return evaluation_step, prediction
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, prediction). """ with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): prediction = tf.argmax(result_tensor, 1) correct_prediction = tf.equal(prediction, ground_truth_tensor) with tf.name_scope('accuracy'): evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', evaluation_step) return evaluation_step, prediction
[ "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 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. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_image_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. """ test_bottlenecks, test_ground_truth, test_filenames = ( get_random_cached_bottlenecks(train_session, image_lists, FLAGS.test_batch_size, 'testing', FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor, FLAGS.tfhub_module)) (eval_session, _, bottleneck_input, ground_truth_input, evaluation_step, prediction) = build_eval_session(module_spec, class_count) test_accuracy, predictions = eval_session.run( [evaluation_step, prediction], feed_dict={ bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth }) tf.logging.info('Final test accuracy = %.1f%% (N=%d)' % (test_accuracy * 100, len(test_bottlenecks))) if FLAGS.print_misclassified_test_images: tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===') for i, test_filename in enumerate(test_filenames): if predictions[i] != test_ground_truth[i]: tf.logging.info('%70s %s' % (test_filename, list(image_lists.keys())[predictions[i]]))
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 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. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_image_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph. """ test_bottlenecks, test_ground_truth, test_filenames = ( get_random_cached_bottlenecks(train_session, image_lists, FLAGS.test_batch_size, 'testing', FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor, FLAGS.tfhub_module)) (eval_session, _, bottleneck_input, ground_truth_input, evaluation_step, prediction) = build_eval_session(module_spec, class_count) test_accuracy, predictions = eval_session.run( [evaluation_step, prediction], feed_dict={ bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth }) tf.logging.info('Final test accuracy = %.1f%% (N=%d)' % (test_accuracy * 100, len(test_bottlenecks))) if FLAGS.print_misclassified_test_images: tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===') for i, test_filename in enumerate(test_filenames): if predictions[i] != test_ground_truth[i]: tf.logging.info('%70s %s' % (test_filename, list(image_lists.keys())[predictions[i]]))
[ "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. jpeg_data_tensor: The layer to feed jpeg image data into. decoded_image_tensor: The output of decoding and resizing the image. resized_image_tensor: The input node of the recognition graph. bottleneck_tensor: The bottleneck output layer of the CNN graph.
[ "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 bottleneck input, ground truth, eval step, and prediction tensors. """ # If quantized, we need to create the correct eval graph for exporting. eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization = ( create_module_graph(module_spec)) eval_sess = tf.Session(graph=eval_graph) with eval_graph.as_default(): # Add the new layer for exporting. (_, _, bottleneck_input, ground_truth_input, final_tensor) = add_final_retrain_ops( class_count, FLAGS.final_tensor_name, bottleneck_tensor, wants_quantization, is_training=False) # Now we need to restore the values from the training graph to the eval # graph. tf.train.Saver().restore(eval_sess, CHECKPOINT_NAME) evaluation_step, prediction = add_evaluation_step(final_tensor, ground_truth_input) return (eval_sess, resized_input_tensor, bottleneck_input, ground_truth_input, evaluation_step, prediction)
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 bottleneck input, ground truth, eval step, and prediction tensors. """ # If quantized, we need to create the correct eval graph for exporting. eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization = ( create_module_graph(module_spec)) eval_sess = tf.Session(graph=eval_graph) with eval_graph.as_default(): # Add the new layer for exporting. (_, _, bottleneck_input, ground_truth_input, final_tensor) = add_final_retrain_ops( class_count, FLAGS.final_tensor_name, bottleneck_tensor, wants_quantization, is_training=False) # Now we need to restore the values from the training graph to the eval # graph. tf.train.Saver().restore(eval_sess, CHECKPOINT_NAME) evaluation_step, prediction = add_evaluation_step(final_tensor, ground_truth_input) return (eval_sess, resized_input_tensor, bottleneck_input, ground_truth_input, evaluation_step, prediction)
[ "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 tensors.
[ "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.as_graph_def(), [FLAGS.final_tensor_name]) with tf.gfile.GFile(graph_file_name, 'wb') as f: f.write(output_graph_def.SerializeToString())
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.as_graph_def(), [FLAGS.final_tensor_name]) with tf.gfile.GFile(graph_file_name, 'wb') as f: f.write(output_graph_def.SerializeToString())
[ "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, input_width = hub.get_expected_image_size(module_spec) input_depth = hub.get_num_image_channels(module_spec) jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) # Convert from full range of uint8 to range [0,1] of float32. decoded_image_as_float = tf.image.convert_image_dtype(decoded_image, tf.float32) decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0) resize_shape = tf.stack([input_height, input_width]) resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32) resized_image = tf.image.resize_bilinear(decoded_image_4d, resize_shape_as_int) return jpeg_data, resized_image
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, input_width = hub.get_expected_image_size(module_spec) input_depth = hub.get_num_image_channels(module_spec) jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) # Convert from full range of uint8 to range [0,1] of float32. decoded_image_as_float = tf.image.convert_image_dtype(decoded_image, tf.float32) decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0) resize_shape = tf.stack([input_height, input_width]) resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32) resized_image = tf.image.resize_bilinear(decoded_image_4d, resize_shape_as_int) return jpeg_data, resized_image
[ "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 hold the eval graph. sess, in_image, _, _, _, _ = build_eval_session(module_spec, class_count) with sess.graph.as_default() as graph: tf.saved_model.simple_save( sess, saved_model_dir, inputs={'image': in_image}, outputs={'prediction': graph.get_tensor_by_name('final_result:0')}, legacy_init_op=tf.group(tf.tables_initializer(), name='legacy_init_op') )
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 hold the eval graph. sess, in_image, _, _, _, _ = build_eval_session(module_spec, class_count) with sess.graph.as_default() as graph: tf.saved_model.simple_save( sess, saved_model_dir, inputs={'image': in_image}, outputs={'prediction': graph.get_tensor_by_name('final_result:0')}, legacy_init_op=tf.group(tf.tables_initializer(), name='legacy_init_op') )
[ "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, 'WARN': tf.logging.WARN, 'INFO': tf.logging.INFO, 'DEBUG': tf.logging.DEBUG } try: return name_to_level[logging_verbosity] except Exception as e: raise RuntimeError('Not supported logs verbosity (%s). Use one of %s.' % (str(e), list(name_to_level)))
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, 'WARN': tf.logging.WARN, 'INFO': tf.logging.INFO, 'DEBUG': tf.logging.DEBUG } try: return name_to_level[logging_verbosity] except Exception as e: raise RuntimeError('Not supported logs verbosity (%s). Use one of %s.' % (str(e), list(name_to_level)))
[ "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 ModuleSpec that accepts image inputs. signature: a string with the key of the signature in question. If None, the default signature is used. input_name: a string with the input name for images. If None, the conventional input name `images` for the default signature is used. Returns: An integer with the number of input channels to the module. Raises: ValueError: If the channel information is missing or malformed. """ if input_name is None: input_name = "images" input_info_dict = module_or_spec.get_input_info_dict(signature) try: shape = input_info_dict[input_name].get_shape() except KeyError: raise ValueError("Module is missing input '%s' in signature '%s'." % (input_name, signature or "default")) try: _, _, _, num_channels = shape.as_list() if num_channels is None: raise ValueError except ValueError: raise ValueError( "Shape of module input is %s, " "expected [batch_size, height, width, num_channels] " "with known num_channels" % shape) return num_channels
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 ModuleSpec that accepts image inputs. signature: a string with the key of the signature in question. If None, the default signature is used. input_name: a string with the input name for images. If None, the conventional input name `images` for the default signature is used. Returns: An integer with the number of input channels to the module. Raises: ValueError: If the channel information is missing or malformed. """ if input_name is None: input_name = "images" input_info_dict = module_or_spec.get_input_info_dict(signature) try: shape = input_info_dict[input_name].get_shape() except KeyError: raise ValueError("Module is missing input '%s' in signature '%s'." % (input_name, signature or "default")) try: _, _, _, num_channels = shape.as_list() if num_channels is None: raise ValueError except ValueError: raise ValueError( "Shape of module input is %s, " "expected [batch_size, height, width, num_channels] " "with known num_channels" % shape) return num_channels
[ "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 signature in question. If None, the default signature is used. input_name: a string with the input name for images. If None, the conventional input name `images` for the default signature is used. Returns: An integer with the number of input channels to the module. Raises: ValueError: If the channel information is missing or malformed.
[ "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=shape, is_sparse=False) elif encoding == "coo_sparse": return ParsedTensorInfo(dtype=dtype, shape=shape, is_sparse=True) else: raise ValueError("Unsupported TensorInfo encoding %r" % encoding)
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=shape, is_sparse=False) elif encoding == "coo_sparse": return ParsedTensorInfo(dtype=dtype, shape=shape, is_sparse=True) else: raise ValueError("Unsupported TensorInfo encoding %r" % encoding)
[ "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 TypeErrors. Raises: TypeError: If it fails to convert. Returns: A Tensor or SparseTensor compatible with tensor_info. """ try: tensor = tf_v1.convert_to_tensor_or_indexed_slices(value, target.dtype) except TypeError as e: raise TypeError("%s: %s" % (error_prefix, e)) if _is_sparse(tensor) != _is_sparse(target): if _is_sparse(tensor): raise TypeError("%s: Is sparse. Expected dense." % error_prefix) else: raise TypeError("%s: Is dense. Expected sparse." % error_prefix) if not tensor.get_shape().is_compatible_with(target.get_shape()): raise TypeError("%s: Shape %r is incompatible with %r" % (error_prefix, tensor.get_shape(), target.get_shape())) return tensor
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 TypeErrors. Raises: TypeError: If it fails to convert. Returns: A Tensor or SparseTensor compatible with tensor_info. """ try: tensor = tf_v1.convert_to_tensor_or_indexed_slices(value, target.dtype) except TypeError as e: raise TypeError("%s: %s" % (error_prefix, e)) if _is_sparse(tensor) != _is_sparse(target): if _is_sparse(tensor): raise TypeError("%s: Is sparse. Expected dense." % error_prefix) else: raise TypeError("%s: Is dense. Expected sparse." % error_prefix) if not tensor.get_shape().is_compatible_with(target.get_shape()): raise TypeError("%s: Shape %r is incompatible with %r" % (error_prefix, tensor.get_shape(), target.get_shape())) return tensor
[ "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: A Tensor or SparseTensor compatible with tensor_info.
[ "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` but values converted into Tensor/SparseTensors that can be fed into `protomap`. Raises: TypeError: If it fails to convert. """ result = {} for key, value in sorted(values.items()): result[key] = _convert_to_compatible_tensor( value, targets[key], error_prefix="Can't convert %r" % key) return result
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` but values converted into Tensor/SparseTensors that can be fed into `protomap`. Raises: TypeError: If it fails to convert. """ result = {} for key, value in sorted(values.items()): result[key] = _convert_to_compatible_tensor( value, targets[key], error_prefix="Can't convert %r" % key) return result
[ "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 be fed into `protomap`. Raises: TypeError: If it fails to convert.
[ "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 tensors. Raises: ValueError: if a TensorInfo proto is malformed or map keys do not match. """ if set(protomap.keys()) != set(inputs.keys()): raise ValueError("build_input_map: keys do not match.") input_map = {} for key, tensor_info in protomap.items(): arg = inputs[key] encoding = tensor_info.WhichOneof("encoding") if encoding == "name": input_map[tensor_info.name] = arg elif encoding == "coo_sparse": coo_sparse = tensor_info.coo_sparse input_map[coo_sparse.values_tensor_name] = arg.values input_map[coo_sparse.indices_tensor_name] = arg.indices input_map[coo_sparse.dense_shape_tensor_name] = arg.dense_shape else: raise ValueError("Invalid TensorInfo.encoding: %s" % encoding) return input_map
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 tensors. Raises: ValueError: if a TensorInfo proto is malformed or map keys do not match. """ if set(protomap.keys()) != set(inputs.keys()): raise ValueError("build_input_map: keys do not match.") input_map = {} for key, tensor_info in protomap.items(): arg = inputs[key] encoding = tensor_info.WhichOneof("encoding") if encoding == "name": input_map[tensor_info.name] = arg elif encoding == "coo_sparse": coo_sparse = tensor_info.coo_sparse input_map[coo_sparse.values_tensor_name] = arg.values input_map[coo_sparse.indices_tensor_name] = arg.indices input_map[coo_sparse.dense_shape_tensor_name] = arg.dense_shape else: raise ValueError("Invalid TensorInfo.encoding: %s" % encoding) return input_map
[ "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 TensorInfo proto is malformed or map keys do not match.
[ "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 Tensor or SparseTensor instances built from `protomap` and resolving tensors using `get_tensor_by_name()`. Raises: ValueError: if a TensorInfo proto is malformed. """ def get_output_from_tensor_info(tensor_info): encoding = tensor_info.WhichOneof("encoding") if encoding == "name": return get_tensor_by_name(tensor_info.name) elif encoding == "coo_sparse": return tf.SparseTensor( get_tensor_by_name(tensor_info.coo_sparse.indices_tensor_name), get_tensor_by_name(tensor_info.coo_sparse.values_tensor_name), get_tensor_by_name(tensor_info.coo_sparse.dense_shape_tensor_name)) else: raise ValueError("Invalid TensorInfo.encoding: %s" % encoding) return { key: get_output_from_tensor_info(tensor_info) for key, tensor_info in protomap.items() }
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 Tensor or SparseTensor instances built from `protomap` and resolving tensors using `get_tensor_by_name()`. Raises: ValueError: if a TensorInfo proto is malformed. """ def get_output_from_tensor_info(tensor_info): encoding = tensor_info.WhichOneof("encoding") if encoding == "name": return get_tensor_by_name(tensor_info.name) elif encoding == "coo_sparse": return tf.SparseTensor( get_tensor_by_name(tensor_info.coo_sparse.indices_tensor_name), get_tensor_by_name(tensor_info.coo_sparse.values_tensor_name), get_tensor_by_name(tensor_info.coo_sparse.dense_shape_tensor_name)) else: raise ValueError("Invalid TensorInfo.encoding: %s" % encoding) return { key: get_output_from_tensor_info(tensor_info) for key, tensor_info in protomap.items() }
[ "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 resolving tensors using `get_tensor_by_name()`. Raises: ValueError: if a TensorInfo proto is malformed.
[ "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, values
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, values
[ "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: ValueError: if the data in the sstable is inconsistent. """ vocabulary = [] embeddings = [] embeddings_dim = None for line in tf.gfile.GFile(file_path): token, embedding = parse_line_fn(line) if not embeddings_dim: embeddings_dim = len(embedding) elif embeddings_dim != len(embedding): raise ValueError( "Inconsistent embedding dimension detected, %d != %d for token %s", embeddings_dim, len(embedding), token) vocabulary.append(token) embeddings.append(embedding) return vocabulary, np.array(embeddings)
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: ValueError: if the data in the sstable is inconsistent. """ vocabulary = [] embeddings = [] embeddings_dim = None for line in tf.gfile.GFile(file_path): token, embedding = parse_line_fn(line) if not embeddings_dim: embeddings_dim = len(embedding) elif embeddings_dim != len(embedding): raise ValueError( "Inconsistent embedding dimension detected, %d != %d for token %s", embeddings_dim, len(embedding), token) vocabulary.append(token) embeddings.append(embedding) return vocabulary, np.array(embeddings)
[ "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 inconsistent.
[ "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 result is a [T, M] shaped Tensor. Args: vocabulary_file: Text file where each line is a key in the vocabulary. vocab_size: The number of tokens contained in the vocabulary. embeddings_dim: The embedding dimension. num_oov_buckets: The number of out-of-vocabulary buckets. preprocess_text: Whether to preprocess the input tensor by removing punctuation and splitting on spaces. Returns: A module spec object used for constructing a TF-Hub module. """ def module_fn(): """Spec function for a token embedding module.""" tokens = tf.placeholder(shape=[None], dtype=tf.string, name="tokens") embeddings_var = tf.get_variable( initializer=tf.zeros([vocab_size + num_oov_buckets, embeddings_dim]), name=EMBEDDINGS_VAR_NAME, dtype=tf.float32) lookup_table = tf.contrib.lookup.index_table_from_file( vocabulary_file=vocabulary_file, num_oov_buckets=num_oov_buckets, ) ids = lookup_table.lookup(tokens) combined_embedding = tf.nn.embedding_lookup(params=embeddings_var, ids=ids) hub.add_signature("default", {"tokens": tokens}, {"default": combined_embedding}) def module_fn_with_preprocessing(): """Spec function for a full-text embedding module with preprocessing.""" sentences = tf.placeholder(shape=[None], dtype=tf.string, name="sentences") # Perform a minimalistic text preprocessing by removing punctuation and # splitting on spaces. normalized_sentences = tf.regex_replace( input=sentences, pattern=r"\pP", rewrite="") tokens = tf.string_split(normalized_sentences, " ") embeddings_var = tf.get_variable( initializer=tf.zeros([vocab_size + num_oov_buckets, embeddings_dim]), name=EMBEDDINGS_VAR_NAME, dtype=tf.float32) lookup_table = tf.contrib.lookup.index_table_from_file( vocabulary_file=vocabulary_file, num_oov_buckets=num_oov_buckets, ) sparse_ids = tf.SparseTensor( indices=tokens.indices, values=lookup_table.lookup(tokens.values), dense_shape=tokens.dense_shape) # In case some of the input sentences are empty before or after # normalization, we will end up with empty rows. We do however want to # return embedding for every row, so we have to fill in the empty rows with # a default. sparse_ids, _ = tf.sparse_fill_empty_rows( sparse_ids, lookup_table.lookup(tf.constant(""))) # In case all of the input sentences are empty before or after # normalization, we will end up with a SparseTensor with shape [?, 0]. After # filling in the empty rows we must ensure the shape is set properly to # [?, 1]. At this point, there are no empty rows, so the new shape will be # [sparse_ids.dense_shape[0], max(1, sparse_ids.dense_shape[1])]. sparse_ids = tf.sparse_reset_shape(sparse_ids) combined_embedding = tf.nn.embedding_lookup_sparse( params=embeddings_var, sp_ids=sparse_ids, sp_weights=None, combiner="sqrtn") hub.add_signature("default", {"sentences": sentences}, {"default": combined_embedding}) if preprocess_text: return hub.create_module_spec(module_fn_with_preprocessing) else: return hub.create_module_spec(module_fn)
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 result is a [T, M] shaped Tensor. Args: vocabulary_file: Text file where each line is a key in the vocabulary. vocab_size: The number of tokens contained in the vocabulary. embeddings_dim: The embedding dimension. num_oov_buckets: The number of out-of-vocabulary buckets. preprocess_text: Whether to preprocess the input tensor by removing punctuation and splitting on spaces. Returns: A module spec object used for constructing a TF-Hub module. """ def module_fn(): """Spec function for a token embedding module.""" tokens = tf.placeholder(shape=[None], dtype=tf.string, name="tokens") embeddings_var = tf.get_variable( initializer=tf.zeros([vocab_size + num_oov_buckets, embeddings_dim]), name=EMBEDDINGS_VAR_NAME, dtype=tf.float32) lookup_table = tf.contrib.lookup.index_table_from_file( vocabulary_file=vocabulary_file, num_oov_buckets=num_oov_buckets, ) ids = lookup_table.lookup(tokens) combined_embedding = tf.nn.embedding_lookup(params=embeddings_var, ids=ids) hub.add_signature("default", {"tokens": tokens}, {"default": combined_embedding}) def module_fn_with_preprocessing(): """Spec function for a full-text embedding module with preprocessing.""" sentences = tf.placeholder(shape=[None], dtype=tf.string, name="sentences") # Perform a minimalistic text preprocessing by removing punctuation and # splitting on spaces. normalized_sentences = tf.regex_replace( input=sentences, pattern=r"\pP", rewrite="") tokens = tf.string_split(normalized_sentences, " ") embeddings_var = tf.get_variable( initializer=tf.zeros([vocab_size + num_oov_buckets, embeddings_dim]), name=EMBEDDINGS_VAR_NAME, dtype=tf.float32) lookup_table = tf.contrib.lookup.index_table_from_file( vocabulary_file=vocabulary_file, num_oov_buckets=num_oov_buckets, ) sparse_ids = tf.SparseTensor( indices=tokens.indices, values=lookup_table.lookup(tokens.values), dense_shape=tokens.dense_shape) # In case some of the input sentences are empty before or after # normalization, we will end up with empty rows. We do however want to # return embedding for every row, so we have to fill in the empty rows with # a default. sparse_ids, _ = tf.sparse_fill_empty_rows( sparse_ids, lookup_table.lookup(tf.constant(""))) # In case all of the input sentences are empty before or after # normalization, we will end up with a SparseTensor with shape [?, 0]. After # filling in the empty rows we must ensure the shape is set properly to # [?, 1]. At this point, there are no empty rows, so the new shape will be # [sparse_ids.dense_shape[0], max(1, sparse_ids.dense_shape[1])]. sparse_ids = tf.sparse_reset_shape(sparse_ids) combined_embedding = tf.nn.embedding_lookup_sparse( params=embeddings_var, sp_ids=sparse_ids, sp_weights=None, combiner="sqrtn") hub.add_signature("default", {"sentences": sentences}, {"default": combined_embedding}) if preprocess_text: return hub.create_module_spec(module_fn_with_preprocessing) else: return hub.create_module_spec(module_fn)
[ "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_size: The number of tokens contained in the vocabulary. embeddings_dim: The embedding dimension. num_oov_buckets: The number of out-of-vocabulary buckets. preprocess_text: Whether to preprocess the input tensor by removing punctuation and splitting on spaces. Returns: A module spec object used for constructing a TF-Hub module.
[ "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 first N rows are the M dimensional embeddings for the respective tokens and the next K rows are for the K out-of-vocabulary buckets. num_oov_buckets: How many out-of-vocabulary buckets to add. preprocess_text: Whether to preprocess the input tensor by removing punctuation and splitting on spaces. """ # Write temporary vocab file for module construction. tmpdir = tempfile.mkdtemp() vocabulary_file = os.path.join(tmpdir, "tokens.txt") with tf.gfile.GFile(vocabulary_file, "w") as f: f.write("\n".join(vocabulary)) vocab_size = len(vocabulary) embeddings_dim = embeddings.shape[1] spec = make_module_spec(vocabulary_file, vocab_size, embeddings_dim, num_oov_buckets, preprocess_text) try: with tf.Graph().as_default(): m = hub.Module(spec) # The embeddings may be very large (e.g., larger than the 2GB serialized # Tensor limit). To avoid having them frozen as constant Tensors in the # graph we instead assign them through the placeholders and feed_dict # mechanism. p_embeddings = tf.placeholder(tf.float32) load_embeddings = tf.assign(m.variable_map[EMBEDDINGS_VAR_NAME], p_embeddings) with tf.Session() as sess: sess.run([load_embeddings], feed_dict={p_embeddings: embeddings}) m.export(export_path, sess) finally: shutil.rmtree(tmpdir)
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 first N rows are the M dimensional embeddings for the respective tokens and the next K rows are for the K out-of-vocabulary buckets. num_oov_buckets: How many out-of-vocabulary buckets to add. preprocess_text: Whether to preprocess the input tensor by removing punctuation and splitting on spaces. """ # Write temporary vocab file for module construction. tmpdir = tempfile.mkdtemp() vocabulary_file = os.path.join(tmpdir, "tokens.txt") with tf.gfile.GFile(vocabulary_file, "w") as f: f.write("\n".join(vocabulary)) vocab_size = len(vocabulary) embeddings_dim = embeddings.shape[1] spec = make_module_spec(vocabulary_file, vocab_size, embeddings_dim, num_oov_buckets, preprocess_text) try: with tf.Graph().as_default(): m = hub.Module(spec) # The embeddings may be very large (e.g., larger than the 2GB serialized # Tensor limit). To avoid having them frozen as constant Tensors in the # graph we instead assign them through the placeholders and feed_dict # mechanism. p_embeddings = tf.placeholder(tf.float32) load_embeddings = tf.assign(m.variable_map[EMBEDDINGS_VAR_NAME], p_embeddings) with tf.Session() as sess: sess.run([load_embeddings], feed_dict={p_embeddings: embeddings}) m.export(export_path, sess) finally: shutil.rmtree(tmpdir)
[ "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 rows are for the K out-of-vocabulary buckets. num_oov_buckets: How many out-of-vocabulary buckets to add. preprocess_text: Whether to preprocess the input tensor by removing punctuation and splitting on spaces.
[ "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 OOV buckets in the extended embedding. """ num_embeddings = np.shape(embeddings)[0] embedding_dim = np.shape(embeddings)[1] embeddings.resize( [num_embeddings + num_oov_buckets, embedding_dim], refcheck=False)
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 OOV buckets in the extended embedding. """ num_embeddings = np.shape(embeddings)[0] embedding_dim = np.shape(embeddings)[1] embeddings.resize( [num_embeddings + num_oov_buckets, embedding_dim], refcheck=False)
[ "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 graph. It only controls the export subdirectory name and it has no scope effects such as the `name` parameter during Module instantiation. Args: module: Module instance to be exported. export_name: subdirectory name to use when performing the export. Raises: ValueError: if `export_name` is already taken in the current graph. """ for used_name, _ in tf_v1.get_collection(_EXPORT_MODULES_COLLECTION): if used_name == export_name: raise ValueError( "There is already a module registered to be exported as %r" % export_name) tf_v1.add_to_collection(_EXPORT_MODULES_COLLECTION, (export_name, module))
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 graph. It only controls the export subdirectory name and it has no scope effects such as the `name` parameter during Module instantiation. Args: module: Module instance to be exported. export_name: subdirectory name to use when performing the export. Raises: ValueError: if `export_name` is already taken in the current graph. """ for used_name, _ in tf_v1.get_collection(_EXPORT_MODULES_COLLECTION): if used_name == export_name: raise ValueError( "There is already a module registered to be exported as %r" % export_name) tf_v1.add_to_collection(_EXPORT_MODULES_COLLECTION, (export_name, module))
[ "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 it has no scope effects such as the `name` parameter during Module instantiation. Args: module: Module instance to be exported. export_name: subdirectory name to use when performing the export. Raises: ValueError: if `export_name` is already taken in the current graph.
[ "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 replicate how an estimator builds a graph. This code is based on `Estimator.export_savedmodel` (another function that has to replicate how an estimator builds a graph). Args: estimator: tf.Estimator to use when constructing the session. serving_input_fn: A function that takes no arguments and returns a `ServingInputReceiver`. It is used to construct the session. checkpoint_path: The checkpoint path to restore in the session. Must not be None. """ with tf.Graph().as_default() as g: mode = tf_v1.estimator.ModeKeys.PREDICT tf_v1.train.create_global_step(g) tf_v1.set_random_seed(estimator.config.tf_random_seed) serving_input_receiver = serving_input_fn() estimator_spec = estimator.model_fn( features=serving_input_receiver.features, labels=None, mode=mode, config=estimator.config) # pylint: disable=protected-access # Note that MonitoredSession(), despite the name is not a Session, and # can't be used to export Modules as one can't use them with Savers. # As so this must use a raw tf.Session(). session = tf_v1.Session(config=estimator._session_config) # pylint: enable=protected-access with session.as_default(): # TODO(b/71839662): Consider if this needs to support TPUEstimatorSpec # which does not have a scaffold member. saver_for_restore = estimator_spec.scaffold.saver or tf_v1.train.Saver( sharded=True) saver_for_restore.restore(session, checkpoint_path) return session
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 replicate how an estimator builds a graph. This code is based on `Estimator.export_savedmodel` (another function that has to replicate how an estimator builds a graph). Args: estimator: tf.Estimator to use when constructing the session. serving_input_fn: A function that takes no arguments and returns a `ServingInputReceiver`. It is used to construct the session. checkpoint_path: The checkpoint path to restore in the session. Must not be None. """ with tf.Graph().as_default() as g: mode = tf_v1.estimator.ModeKeys.PREDICT tf_v1.train.create_global_step(g) tf_v1.set_random_seed(estimator.config.tf_random_seed) serving_input_receiver = serving_input_fn() estimator_spec = estimator.model_fn( features=serving_input_receiver.features, labels=None, mode=mode, config=estimator.config) # pylint: disable=protected-access # Note that MonitoredSession(), despite the name is not a Session, and # can't be used to export Modules as one can't use them with Savers. # As so this must use a raw tf.Session(). session = tf_v1.Session(config=estimator._session_config) # pylint: enable=protected-access with session.as_default(): # TODO(b/71839662): Consider if this needs to support TPUEstimatorSpec # which does not have a scaffold member. saver_for_restore = estimator_spec.scaffold.saver or tf_v1.train.Saver( sharded=True) saver_for_restore.restore(session, checkpoint_path) return session
[ "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 has to replicate how an estimator builds a graph). Args: estimator: tf.Estimator to use when constructing the session. serving_input_fn: A function that takes no arguments and returns a `ServingInputReceiver`. It is used to construct the session. checkpoint_path: The checkpoint path to restore in the session. Must not be None.
[ "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 # Define a text embedding module. def my_text_module_fn(): text_input = tf.placeholder(dtype=tf.string, shape=[None]) embeddings = compute_embedding(text_input) hub.add_signature(inputs=text_input, outputs=embeddings) ``` See `add_signature()` for documentation on adding multiple input/output signatures. NOTE: In anticipation of future TF-versions, `module_fn` is called on a graph that uses resource variables by default. If you want old-style variables then you can use `with tf.variable_scope("", use_resource=False)` in `module_fn`. Multiple graph variants can be defined by using the `tags_and_args` argument. For example, the code: ```python hub.create_module_spec( module_fn, tags_and_args=[({"train"}, {"is_training":True}), (set(), {"is_training":False})]) ``` calls `module_fn` twice, once as `module_fn(is_training=True)` and once as `module_fn(is_training=False)` to define the respective graph variants: for training with tags {"train"} and for inference with the empty set of tags. Using the empty set aligns the inference case with the default in Module.__init__(). Args: module_fn: a function to build a graph for the Module. tags_and_args: Optional list of tuples (tags, kwargs) of tags and keyword args used to define graph variants. If omitted, it is interpreted as [(set(), {})], meaning `module_fn` is called once with no args. drop_collections: list of collection to drop. Returns: A ModuleSpec. Raises: ValueError: if it fails to construct the ModuleSpec due to bad or unsupported values in the arguments or in the graphs constructed by `module_fn`. """ if not drop_collections: drop_collections = [] report_tags = True if not tags_and_args: tags_and_args = [(set(), {})] report_tags = False saved_model_handler = saved_model_lib.SavedModelHandler() for tags, args in tags_and_args: with tf.Graph().as_default() as graph: with tf_v1.variable_scope("", use_resource=True): module_fn(**args) for collection_key in drop_collections: del tf_v1.get_collection_ref(collection_key)[:] err = find_state_op_colocation_error(graph, tags if report_tags else None) if err: raise ValueError(err) saved_model_handler.add_graph_copy(graph, tags=tags) return _ModuleSpec(saved_model_handler, checkpoint_variables_path=None)
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: ```python # Define a text embedding module. def my_text_module_fn(): text_input = tf.placeholder(dtype=tf.string, shape=[None]) embeddings = compute_embedding(text_input) hub.add_signature(inputs=text_input, outputs=embeddings) ``` See `add_signature()` for documentation on adding multiple input/output signatures. NOTE: In anticipation of future TF-versions, `module_fn` is called on a graph that uses resource variables by default. If you want old-style variables then you can use `with tf.variable_scope("", use_resource=False)` in `module_fn`. Multiple graph variants can be defined by using the `tags_and_args` argument. For example, the code: ```python hub.create_module_spec( module_fn, tags_and_args=[({"train"}, {"is_training":True}), (set(), {"is_training":False})]) ``` calls `module_fn` twice, once as `module_fn(is_training=True)` and once as `module_fn(is_training=False)` to define the respective graph variants: for training with tags {"train"} and for inference with the empty set of tags. Using the empty set aligns the inference case with the default in Module.__init__(). Args: module_fn: a function to build a graph for the Module. tags_and_args: Optional list of tuples (tags, kwargs) of tags and keyword args used to define graph variants. If omitted, it is interpreted as [(set(), {})], meaning `module_fn` is called once with no args. drop_collections: list of collection to drop. Returns: A ModuleSpec. Raises: ValueError: if it fails to construct the ModuleSpec due to bad or unsupported values in the arguments or in the graphs constructed by `module_fn`. """ if not drop_collections: drop_collections = [] report_tags = True if not tags_and_args: tags_and_args = [(set(), {})] report_tags = False saved_model_handler = saved_model_lib.SavedModelHandler() for tags, args in tags_and_args: with tf.Graph().as_default() as graph: with tf_v1.variable_scope("", use_resource=True): module_fn(**args) for collection_key in drop_collections: del tf_v1.get_collection_ref(collection_key)[:] err = find_state_op_colocation_error(graph, tags if report_tags else None) if err: raise ValueError(err) saved_model_handler.add_graph_copy(graph, tags=tags) return _ModuleSpec(saved_model_handler, checkpoint_variables_path=None)
[ "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_input = tf.placeholder(dtype=tf.string, shape=[None]) embeddings = compute_embedding(text_input) hub.add_signature(inputs=text_input, outputs=embeddings) ``` See `add_signature()` for documentation on adding multiple input/output signatures. NOTE: In anticipation of future TF-versions, `module_fn` is called on a graph that uses resource variables by default. If you want old-style variables then you can use `with tf.variable_scope("", use_resource=False)` in `module_fn`. Multiple graph variants can be defined by using the `tags_and_args` argument. For example, the code: ```python hub.create_module_spec( module_fn, tags_and_args=[({"train"}, {"is_training":True}), (set(), {"is_training":False})]) ``` calls `module_fn` twice, once as `module_fn(is_training=True)` and once as `module_fn(is_training=False)` to define the respective graph variants: for training with tags {"train"} and for inference with the empty set of tags. Using the empty set aligns the inference case with the default in Module.__init__(). Args: module_fn: a function to build a graph for the Module. tags_and_args: Optional list of tuples (tags, kwargs) of tags and keyword args used to define graph variants. If omitted, it is interpreted as [(set(), {})], meaning `module_fn` is called once with no args. drop_collections: list of collection to drop. Returns: A ModuleSpec. Raises: ValueError: if it fails to construct the ModuleSpec due to bad or unsupported values in the arguments or in the graphs constructed by `module_fn`.
[ "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.__call__` `signature` is not specified. inputs: A dict from input name to Tensor or SparseTensor to feed when applying the signature. If a single tensor is passed, it is interpreted as a dict with a single 'default' entry. outputs: A dict from output name to Tensor or SparseTensor to return from applying the signature. If a single tensor is passed, it is interpreted as a dict with a single 'default' entry. Raises: ValueError: if the arguments are invalid. """ if not name: name = "default" if inputs is None: inputs = {} if outputs is None: outputs = {} if not isinstance(inputs, dict): inputs = {"default": inputs} if not isinstance(outputs, dict): outputs = {"default": outputs} message = find_signature_inputs_from_multivalued_ops(inputs) if message: logging.error(message) message = find_signature_input_colocation_error(name, inputs) if message: raise ValueError(message) saved_model_lib.add_signature(name, inputs, outputs)
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.__call__` `signature` is not specified. inputs: A dict from input name to Tensor or SparseTensor to feed when applying the signature. If a single tensor is passed, it is interpreted as a dict with a single 'default' entry. outputs: A dict from output name to Tensor or SparseTensor to return from applying the signature. If a single tensor is passed, it is interpreted as a dict with a single 'default' entry. Raises: ValueError: if the arguments are invalid. """ if not name: name = "default" if inputs is None: inputs = {} if outputs is None: outputs = {} if not isinstance(inputs, dict): inputs = {"default": inputs} if not isinstance(outputs, dict): outputs = {"default": outputs} message = find_signature_inputs_from_multivalued_ops(inputs) if message: logging.error(message) message = find_signature_input_colocation_error(name, inputs) if message: raise ValueError(message) saved_model_lib.add_signature(name, inputs, outputs)
[ "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 from input name to Tensor or SparseTensor to feed when applying the signature. If a single tensor is passed, it is interpreted as a dict with a single 'default' entry. outputs: A dict from output name to Tensor or SparseTensor to return from applying the signature. If a single tensor is passed, it is interpreted as a dict with a single 'default' entry. Raises: ValueError: if the arguments are invalid.
[ "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 message: * Select a reasonably descriptive name as a unique key. For now, keys must be valid Python identifiers that start with a letter. Punctuation besides underscores ('_') is reserved for future use in hierarchical names. * Define a Protocol Buffer message type to store the value for the key. (Use generic containers like google.protobuf.Value only if running the protocol compiler is infeasible for your build process.) * For module consumers, consider providing a small library that encapsulates the specific call to get_attached_message() behind a higher-level interface and supplies the right message type for parsing. Attached messages work best for few messages of moderate size. Avoid a large number of messages; use repetition within messages instead. Avoid large messages (megabytes); consider module assets instead. For modules with multiple graph versions, each graph version stores separately what was attached from within the call to `module_fn` that defines its graph. Args: key: A string with the unique key to retrieve this message. Must start with a letter and contain only letters, digits and underscores. If used repeatedly within one invocation of `module_fn`, then only the message from the final call will be returned by `get_attached_message()`. message: A protocol message object, to be stored in serialized form. Raises: ValueError: if `key` is not a string of the form of a Python identifier. """ 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_model_lib.attach_bytes(key, message.SerializeToString())
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 message: * Select a reasonably descriptive name as a unique key. For now, keys must be valid Python identifiers that start with a letter. Punctuation besides underscores ('_') is reserved for future use in hierarchical names. * Define a Protocol Buffer message type to store the value for the key. (Use generic containers like google.protobuf.Value only if running the protocol compiler is infeasible for your build process.) * For module consumers, consider providing a small library that encapsulates the specific call to get_attached_message() behind a higher-level interface and supplies the right message type for parsing. Attached messages work best for few messages of moderate size. Avoid a large number of messages; use repetition within messages instead. Avoid large messages (megabytes); consider module assets instead. For modules with multiple graph versions, each graph version stores separately what was attached from within the call to `module_fn` that defines its graph. Args: key: A string with the unique key to retrieve this message. Must start with a letter and contain only letters, digits and underscores. If used repeatedly within one invocation of `module_fn`, then only the message from the final call will be returned by `get_attached_message()`. message: A protocol message object, to be stored in serialized form. Raises: ValueError: if `key` is not a string of the form of a Python identifier. """ 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_model_lib.attach_bytes(key, message.SerializeToString())
[ "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 descriptive name as a unique key. For now, keys must be valid Python identifiers that start with a letter. Punctuation besides underscores ('_') is reserved for future use in hierarchical names. * Define a Protocol Buffer message type to store the value for the key. (Use generic containers like google.protobuf.Value only if running the protocol compiler is infeasible for your build process.) * For module consumers, consider providing a small library that encapsulates the specific call to get_attached_message() behind a higher-level interface and supplies the right message type for parsing. Attached messages work best for few messages of moderate size. Avoid a large number of messages; use repetition within messages instead. Avoid large messages (megabytes); consider module assets instead. For modules with multiple graph versions, each graph version stores separately what was attached from within the call to `module_fn` that defines its graph. Args: key: A string with the unique key to retrieve this message. Must start with a letter and contain only letters, digits and underscores. If used repeatedly within one invocation of `module_fn`, then only the message from the final call will be returned by `get_attached_message()`. message: A protocol message object, to be stored in serialized form. Raises: ValueError: if `key` is not a string of the form of a Python identifier.
[ "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 for name, op in op_def_registry.get_registered_ops().items() if op.is_stateful and not op.input_arg ])
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 for name, op in op_def_registry.get_registered_ops().items() if op.is_stateful and not op.input_arg ])
[ "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_tensor_by_name(tensor_name) num_outputs = len(tensor.op.outputs) if num_outputs != 1: raise ValueError("Stateful op %s has %d outputs, expected 1" % (node.op, num_outputs)) state_map[tensor_name] = tensor if node.op in unsupported_state_ops: raise ValueError("Unsupported stateful op: %s" % node.op) return state_map
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_tensor_by_name(tensor_name) num_outputs = len(tensor.op.outputs) if num_outputs != 1: raise ValueError("Stateful op %s has %d outputs, expected 1" % (node.op, num_outputs)) state_map[tensor_name] = tensor if node.op in unsupported_state_ops: raise ValueError("Unsupported stateful op: %s" % node.op) return state_map
[ "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 feedmap. if node.op in state_ops and tensor_name in feed_map: node.op = "Placeholder" for key in node.attr: # Only shape and dtype are required for Placeholder. Remove other # attributes. if key != "shape": keys_to_purge.append(key) for key in keys_to_purge: del node.attr[key] node.attr["dtype"].type = types_pb2.DT_RESOURCE
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 feedmap. if node.op in state_ops and tensor_name in feed_map: node.op = "Placeholder" for key in node.attr: # Only shape and dtype are required for Placeholder. Remove other # attributes. if key != "shape": keys_to_purge.append(key) for key in keys_to_purge: del node.attr[key] node.attr["dtype"].type = types_pb2.DT_RESOURCE
[ "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 partitioning. offset: Offset of the variable into the full variable. Raises: RuntimeError: In case of unexpected variable format. """ name, offset, partitioned = None, None, False # pylint: disable=protected-access if variable._save_slice_info: name = variable_key[:variable_key.rfind("/")] if not variable._save_slice_info.full_name.endswith(name): raise RuntimeError("Unexpected handling of partitioned variable.") offset = variable._save_slice_info.var_offset[0] partitioned = True # pylint: enable=protected-access return partitioned, name, offset
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 partitioning. offset: Offset of the variable into the full variable. Raises: RuntimeError: In case of unexpected variable format. """ name, offset, partitioned = None, None, False # pylint: disable=protected-access if variable._save_slice_info: name = variable_key[:variable_key.rfind("/")] if not variable._save_slice_info.full_name.endswith(name): raise RuntimeError("Unexpected handling of partitioned variable.") offset = variable._save_slice_info.var_offset[0] partitioned = True # pylint: enable=protected-access return partitioned, name, offset
[ "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 full variable. Raises: RuntimeError: In case of unexpected variable format.
[ "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.Variables for each PartitionedVariables in `var_node_map`. Raises: RuntimeError: if there are issues recovering the PartitionedVariables. """ offset_variables_map = {} for var_key, var_tensor in var_node_map.items(): match, var_name, offset = _extract_variable_parts(var_key, var_tensor) if not match: # This is a standard variable, so we can safely add it to the output. if var_key in offset_variables_map: raise RuntimeError( "Variable %s exists both as a single and partitioned variable.") offset_variables_map[var_key] = var_tensor continue if var_name not in offset_variables_map: offset_variables_map[var_name] = {} elif not isinstance(offset_variables_map[var_name], dict): raise RuntimeError( "Variable %s exists both as a single and partitioned variable.") # Duplicated variable offsets should not exist. if offset in offset_variables_map[var_name]: raise RuntimeError( "Variable map contains duplicate offset %d for variable [%s]" % (offset, var_name)) offset_variables_map[var_name][offset] = var_tensor variables_map = {} # Use offsets for sorting, then strip them from the dictionary and keep only # a list of variables per each variable name. for var_name, var_value in offset_variables_map.items(): if not isinstance(var_value, dict): variables_map[var_name] = var_value continue shapes = [var_tensor.shape[1:] for var_tensor in var_value.values()] if not all(shape == shapes[0] for shape in shapes): raise RuntimeError("Shapes not compatible: %s" % (shapes)) for _, tensor in sorted(var_value.items()): variables_map[var_name] = [ tensor for _, tensor in sorted(var_value.items()) ] return variables_map
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.Variables for each PartitionedVariables in `var_node_map`. Raises: RuntimeError: if there are issues recovering the PartitionedVariables. """ offset_variables_map = {} for var_key, var_tensor in var_node_map.items(): match, var_name, offset = _extract_variable_parts(var_key, var_tensor) if not match: # This is a standard variable, so we can safely add it to the output. if var_key in offset_variables_map: raise RuntimeError( "Variable %s exists both as a single and partitioned variable.") offset_variables_map[var_key] = var_tensor continue if var_name not in offset_variables_map: offset_variables_map[var_name] = {} elif not isinstance(offset_variables_map[var_name], dict): raise RuntimeError( "Variable %s exists both as a single and partitioned variable.") # Duplicated variable offsets should not exist. if offset in offset_variables_map[var_name]: raise RuntimeError( "Variable map contains duplicate offset %d for variable [%s]" % (offset, var_name)) offset_variables_map[var_name][offset] = var_tensor variables_map = {} # Use offsets for sorting, then strip them from the dictionary and keep only # a list of variables per each variable name. for var_name, var_value in offset_variables_map.items(): if not isinstance(var_value, dict): variables_map[var_name] = var_value continue shapes = [var_tensor.shape[1:] for var_tensor in var_value.values()] if not all(shape == shapes[0] for shape in shapes): raise RuntimeError("Shapes not compatible: %s" % (shapes)) for _, tensor in sorted(var_value.items()): variables_map[var_name] = [ tensor for _, tensor in sorted(var_value.items()) ] return variables_map
[ "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_map`. Raises: RuntimeError: if there are issues recovering the PartitionedVariables.
[ "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 unsupported: raise ValueError("Unsupported collections in graph: %s\n" "Use hub.create_module_spec(..., drop_collections=[...])" " as appropriate." % list(unsupported))
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 unsupported: raise ValueError("Unsupported collections in graph: %s\n" "Use hub.create_module_spec(..., drop_collections=[...])" " as appropriate." % list(unsupported))
[ "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 - set(op_def_registry.get_registered_ops().keys()) if not missing_ops: return p_buffer = c_api.TF_GetAllOpList() cpp_op_list = op_def_pb2.OpList() cpp_op_list.ParseFromString(c_api.TF_GetBuffer(p_buffer)) cpp_registry_ops = {op.name: op for op in cpp_op_list.op} missing_op_list = op_def_pb2.OpList() for missing_op in missing_ops: if missing_op not in cpp_registry_ops: logging.info( "Op %s is missing from both the python and C++ registry.", missing_op) else: missing_op_list.op.extend([cpp_registry_ops[missing_op]]) logging.info( "Adding op %s from c++ registry to python registry.", missing_op) op_def_registry.register_op_list(missing_op_list) # Note: Only raise missing op ValueError after trying to load ops. # This allows the test to exercise all the calls into TensorFlow # without having to write a C + python test. if not missing_ops <= set(cpp_registry_ops.keys()): raise RuntimeError( "Graph ops missing from the python registry (%s) are also absent from " "the c++ registry." % missing_ops.difference(set(cpp_registry_ops.keys())))
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 - set(op_def_registry.get_registered_ops().keys()) if not missing_ops: return p_buffer = c_api.TF_GetAllOpList() cpp_op_list = op_def_pb2.OpList() cpp_op_list.ParseFromString(c_api.TF_GetBuffer(p_buffer)) cpp_registry_ops = {op.name: op for op in cpp_op_list.op} missing_op_list = op_def_pb2.OpList() for missing_op in missing_ops: if missing_op not in cpp_registry_ops: logging.info( "Op %s is missing from both the python and C++ registry.", missing_op) else: missing_op_list.op.extend([cpp_registry_ops[missing_op]]) logging.info( "Adding op %s from c++ registry to python registry.", missing_op) op_def_registry.register_op_list(missing_op_list) # Note: Only raise missing op ValueError after trying to load ops. # This allows the test to exercise all the calls into TensorFlow # without having to write a C + python test. if not missing_ops <= set(cpp_registry_ops.keys()): raise RuntimeError( "Graph ops missing from the python registry (%s) are also absent from " "the c++ registry." % missing_ops.difference(set(cpp_registry_ops.keys())))
[ "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 import. It also updates devices accordingly. The nodes in the given import scope of the current default graph have their colocation attributes (that is, the "loc:@..." values in the "_class" attr) rewritten as follows: If, before the call, op x has attribute loc:@y, and `input_map` replaces an output of y with an output of z, then loc:@y gets replaced by the colocation attributes of z (that is, loc:@z, if no other constraints are in play). This style of rewriting imposes the following requirements: * If an output of node y is an input tensor in a signature of the module, y must not have any colocation attributes on it, such that colocations with y are expressed by loc:@y and can be adjusted with a rewriting rule for it. Function `find_signature_input_colocation_error()` checks this during module creation. * If y1 is a state node, its colocation constraints must only reference other state nodes, say, y2. Since all outputs of state nodes are mapped the same way, all their rewriting rules together will do the same thing. Function `find_state_op_colocation_error()` checks this during module creation. * Other nodes may have arbitrary colocation attributes. Mapping of inputs works with tensors, while colocation constraints work with ops. Issues may arise when mapping tensors from ops with multiple outputs. If the outputs of y are replaced by outputs of distinct ops z1, z2, ..., rewriting of loc:@y becomes ambiguous unless z1, z2, ... have equal colocation_groups) If some but not all outputs of y are replaced, it becomes ambiguous whether to rewrite loc:@y at all. For now, this is handled conservatively by raising an error (instead of rewriting to the union of all applicable constraints). This should be very rare: all state ops so far have single outputs (and even if not, the rewriting would be consistent); input ops usually are placeholders, which have single outputs. Args: input_map: a dict mapping from tensor names in the imported graph to existing Tensors, typically the same as passed to tf.import_graph_def(). absolute_import_scope: a string with the full name of the import scope, comprising the current scope when import_graph_def() as called plus the import_scope passed to it. Raises: ValueError: if one imported op has its multiple outputs and they are remapped in a way that causes conflicting colocation rewrites. """ attr_map = _build_colocation_attr_map(input_map, absolute_import_scope) _apply_colocation_attr_map(attr_map, absolute_import_scope)
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 import. It also updates devices accordingly. The nodes in the given import scope of the current default graph have their colocation attributes (that is, the "loc:@..." values in the "_class" attr) rewritten as follows: If, before the call, op x has attribute loc:@y, and `input_map` replaces an output of y with an output of z, then loc:@y gets replaced by the colocation attributes of z (that is, loc:@z, if no other constraints are in play). This style of rewriting imposes the following requirements: * If an output of node y is an input tensor in a signature of the module, y must not have any colocation attributes on it, such that colocations with y are expressed by loc:@y and can be adjusted with a rewriting rule for it. Function `find_signature_input_colocation_error()` checks this during module creation. * If y1 is a state node, its colocation constraints must only reference other state nodes, say, y2. Since all outputs of state nodes are mapped the same way, all their rewriting rules together will do the same thing. Function `find_state_op_colocation_error()` checks this during module creation. * Other nodes may have arbitrary colocation attributes. Mapping of inputs works with tensors, while colocation constraints work with ops. Issues may arise when mapping tensors from ops with multiple outputs. If the outputs of y are replaced by outputs of distinct ops z1, z2, ..., rewriting of loc:@y becomes ambiguous unless z1, z2, ... have equal colocation_groups) If some but not all outputs of y are replaced, it becomes ambiguous whether to rewrite loc:@y at all. For now, this is handled conservatively by raising an error (instead of rewriting to the union of all applicable constraints). This should be very rare: all state ops so far have single outputs (and even if not, the rewriting would be consistent); input ops usually are placeholders, which have single outputs. Args: input_map: a dict mapping from tensor names in the imported graph to existing Tensors, typically the same as passed to tf.import_graph_def(). absolute_import_scope: a string with the full name of the import scope, comprising the current scope when import_graph_def() as called plus the import_scope passed to it. Raises: ValueError: if one imported op has its multiple outputs and they are remapped in a way that causes conflicting colocation rewrites. """ attr_map = _build_colocation_attr_map(input_map, absolute_import_scope) _apply_colocation_attr_map(attr_map, absolute_import_scope)
[ "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 import scope of the current default graph have their colocation attributes (that is, the "loc:@..." values in the "_class" attr) rewritten as follows: If, before the call, op x has attribute loc:@y, and `input_map` replaces an output of y with an output of z, then loc:@y gets replaced by the colocation attributes of z (that is, loc:@z, if no other constraints are in play). This style of rewriting imposes the following requirements: * If an output of node y is an input tensor in a signature of the module, y must not have any colocation attributes on it, such that colocations with y are expressed by loc:@y and can be adjusted with a rewriting rule for it. Function `find_signature_input_colocation_error()` checks this during module creation. * If y1 is a state node, its colocation constraints must only reference other state nodes, say, y2. Since all outputs of state nodes are mapped the same way, all their rewriting rules together will do the same thing. Function `find_state_op_colocation_error()` checks this during module creation. * Other nodes may have arbitrary colocation attributes. Mapping of inputs works with tensors, while colocation constraints work with ops. Issues may arise when mapping tensors from ops with multiple outputs. If the outputs of y are replaced by outputs of distinct ops z1, z2, ..., rewriting of loc:@y becomes ambiguous unless z1, z2, ... have equal colocation_groups) If some but not all outputs of y are replaced, it becomes ambiguous whether to rewrite loc:@y at all. For now, this is handled conservatively by raising an error (instead of rewriting to the union of all applicable constraints). This should be very rare: all state ops so far have single outputs (and even if not, the rewriting would be consistent); input ops usually are placeholders, which have single outputs. Args: input_map: a dict mapping from tensor names in the imported graph to existing Tensors, typically the same as passed to tf.import_graph_def(). absolute_import_scope: a string with the full name of the import scope, comprising the current scope when import_graph_def() as called plus the import_scope passed to it. Raises: ValueError: if one imported op has its multiple outputs and they are remapped in a way that causes conflicting colocation rewrites.
[ "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:@" + absolute_import_scope + "/foo"` to _ConsistentValues set to the lists of bytes `["loc:@...", ...]` according to the rewriting scheme of fix_colocation_after_import. In case of an inconsistent rewriting, _ConsistentValue.has_error is true. """ colocation_attr_map = collections.defaultdict(_ConsistentValue) used_outputs_of_imported_ops = collections.defaultdict(set) # Collect mappings from the input_map. for imported_tensor_name, mapped_tensor in input_map.items(): imported_tensor_name = absolute_import_scope + "/" + imported_tensor_name imported_op_name, imported_index = _split_tensor_name(imported_tensor_name) key = tf.compat.as_bytes("loc:@" + imported_op_name) colocation_attr_map[key].Set( mapped_tensor.op.colocation_groups(), {"reason": "input '%s' is substituted by '%s'" % ( imported_tensor_name, mapped_tensor.name)}) used_outputs_of_imported_ops[imported_op_name].add(imported_index) # Add unchanged mappings for additional, non-remapped outputs of ops touched # by the input_map. For now, these just signal inconsistency when used. for imported_op_name, used_outputs in used_outputs_of_imported_ops.items(): imported_op = tf_v1.get_default_graph().get_operation_by_name( imported_op_name) unused_outputs = set(range(len(imported_op.outputs))) - used_outputs if not unused_outputs: continue key = tf.compat.as_bytes("loc:@" + imported_op_name) if imported_op.colocation_groups() != [key]: # This should never happen: state nodes are remapped fully, input nodes # are prevented from having colocation attributes. raise ValueError( "Internal error: tensors from op '%s' are partially remapped in " "import but op.colocation_groups=%s cannot be captured in a " "simple rewrite rule." % (imported_op_name, imported_op.colocation_groups())) colocation_attr_map[key].Set( [key], {"reason": "tensor '%s:%s' is not substituted by inputs" % ( imported_op_name, ",".join(str(i) for i in sorted(unused_outputs)))}) return colocation_attr_map
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:@" + absolute_import_scope + "/foo"` to _ConsistentValues set to the lists of bytes `["loc:@...", ...]` according to the rewriting scheme of fix_colocation_after_import. In case of an inconsistent rewriting, _ConsistentValue.has_error is true. """ colocation_attr_map = collections.defaultdict(_ConsistentValue) used_outputs_of_imported_ops = collections.defaultdict(set) # Collect mappings from the input_map. for imported_tensor_name, mapped_tensor in input_map.items(): imported_tensor_name = absolute_import_scope + "/" + imported_tensor_name imported_op_name, imported_index = _split_tensor_name(imported_tensor_name) key = tf.compat.as_bytes("loc:@" + imported_op_name) colocation_attr_map[key].Set( mapped_tensor.op.colocation_groups(), {"reason": "input '%s' is substituted by '%s'" % ( imported_tensor_name, mapped_tensor.name)}) used_outputs_of_imported_ops[imported_op_name].add(imported_index) # Add unchanged mappings for additional, non-remapped outputs of ops touched # by the input_map. For now, these just signal inconsistency when used. for imported_op_name, used_outputs in used_outputs_of_imported_ops.items(): imported_op = tf_v1.get_default_graph().get_operation_by_name( imported_op_name) unused_outputs = set(range(len(imported_op.outputs))) - used_outputs if not unused_outputs: continue key = tf.compat.as_bytes("loc:@" + imported_op_name) if imported_op.colocation_groups() != [key]: # This should never happen: state nodes are remapped fully, input nodes # are prevented from having colocation attributes. raise ValueError( "Internal error: tensors from op '%s' are partially remapped in " "import but op.colocation_groups=%s cannot be captured in a " "simple rewrite rule." % (imported_op_name, imported_op.colocation_groups())) colocation_attr_map[key].Set( [key], {"reason": "tensor '%s:%s' is not substituted by inputs" % ( imported_op_name, ",".join(str(i) for i in sorted(unused_outputs)))}) return colocation_attr_map
[ "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 of bytes `["loc:@...", ...]` according to the rewriting scheme of fix_colocation_after_import. In case of an inconsistent rewriting, _ConsistentValue.has_error is true.
[ "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 values (with deduplication). The node's device is updated accordingly. Args: colocation_attr_map: as returned by _build_colocation_attr_map. absolute_import_scope: as for fix_colocation_after_import. Raises: ValueError: if rewriting runs into an inconsistent value in `colocation_attr_map`. """ graph = tf_v1.get_default_graph() for op in graph.get_operations(): # Rewrite the values of the "_class" attr that store colocation constraints. # NOTE: The colocation_group loc:@X of a node with itself is not stored # explicitly as an attr, so rewrite errors for loc:@X are not triggered # by the mere existence of X. if not op.name.startswith(absolute_import_scope + "/"): continue try: class_values = op.get_attr("_class") except ValueError: continue # No _class attr found; nothing to do. new_attr_value = tf_v1.AttrValue() new_coloc_groups = [] for class_value in class_values: if class_value.startswith(tf.compat.as_bytes("loc:@")): if class_value not in colocation_attr_map: rewritten_class_value = [class_value] else: rewritten_class_value = (colocation_attr_map[ class_value].GetConsistentValueOrRaise( "Failed to rewrite colocation constraints while applying " "hub.Module:\n" "The module graph contains a node {op!r} " "that has a colocation constraint {class_value!r} " "with ambiguous rewriting {old_value!r} vs {new_value!r} " "because {old_reason} and {new_reason}, respectively.\n" "To fix, avoid publishing a module with inputs comprising " "multiple outputs of one op that is referenced in " "tf.colocate_with(...) constraints on other ops.", {"op": op.name, "class_value": class_value})) new_coloc_groups.extend(rewritten_class_value) else: new_attr_value.list.s.append(class_value) new_coloc_groups = sorted(set(new_coloc_groups)) new_attr_value.list.s.extend(new_coloc_groups) op._set_attr("_class", new_attr_value) # pylint: disable=protected-access # Mimic the code of tf.import_graph_def(): If there are colocation # constraints, use any of them to set the device (overriding what the # device function stack would do), without attempting to merge or check for # equality. If they were inconsistent, TensorFlow's C++ runtime would fail # anyways due to conflicting colocation constraints. # Note that Hub imports GraphDefs with devices cleared, so this code deals # with the result of import_graph_def, not a setting saved in the module. if new_coloc_groups: new_coloc_device = "" for new_coloc_group in new_coloc_groups: assert new_coloc_group.startswith(tf.compat.as_bytes("loc:@")) new_coloc_target_op = graph.get_operation_by_name( tf.compat.as_str_any(new_coloc_group[5:])) new_coloc_device = new_coloc_target_op.device if new_coloc_device: break # Set this, even if empty, to avoid retaining an outdated value. op._set_device(new_coloc_device)
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 values (with deduplication). The node's device is updated accordingly. Args: colocation_attr_map: as returned by _build_colocation_attr_map. absolute_import_scope: as for fix_colocation_after_import. Raises: ValueError: if rewriting runs into an inconsistent value in `colocation_attr_map`. """ graph = tf_v1.get_default_graph() for op in graph.get_operations(): # Rewrite the values of the "_class" attr that store colocation constraints. # NOTE: The colocation_group loc:@X of a node with itself is not stored # explicitly as an attr, so rewrite errors for loc:@X are not triggered # by the mere existence of X. if not op.name.startswith(absolute_import_scope + "/"): continue try: class_values = op.get_attr("_class") except ValueError: continue # No _class attr found; nothing to do. new_attr_value = tf_v1.AttrValue() new_coloc_groups = [] for class_value in class_values: if class_value.startswith(tf.compat.as_bytes("loc:@")): if class_value not in colocation_attr_map: rewritten_class_value = [class_value] else: rewritten_class_value = (colocation_attr_map[ class_value].GetConsistentValueOrRaise( "Failed to rewrite colocation constraints while applying " "hub.Module:\n" "The module graph contains a node {op!r} " "that has a colocation constraint {class_value!r} " "with ambiguous rewriting {old_value!r} vs {new_value!r} " "because {old_reason} and {new_reason}, respectively.\n" "To fix, avoid publishing a module with inputs comprising " "multiple outputs of one op that is referenced in " "tf.colocate_with(...) constraints on other ops.", {"op": op.name, "class_value": class_value})) new_coloc_groups.extend(rewritten_class_value) else: new_attr_value.list.s.append(class_value) new_coloc_groups = sorted(set(new_coloc_groups)) new_attr_value.list.s.extend(new_coloc_groups) op._set_attr("_class", new_attr_value) # pylint: disable=protected-access # Mimic the code of tf.import_graph_def(): If there are colocation # constraints, use any of them to set the device (overriding what the # device function stack would do), without attempting to merge or check for # equality. If they were inconsistent, TensorFlow's C++ runtime would fail # anyways due to conflicting colocation constraints. # Note that Hub imports GraphDefs with devices cleared, so this code deals # with the result of import_graph_def, not a setting saved in the module. if new_coloc_groups: new_coloc_device = "" for new_coloc_group in new_coloc_groups: assert new_coloc_group.startswith(tf.compat.as_bytes("loc:@")) new_coloc_target_op = graph.get_operation_by_name( tf.compat.as_str_any(new_coloc_group[5:])) new_coloc_device = new_coloc_target_op.device if new_coloc_device: break # Set this, even if empty, to avoid retaining an outdated value. op._set_device(new_coloc_device)
[ "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: colocation_attr_map: as returned by _build_colocation_attr_map. absolute_import_scope: as for fix_colocation_after_import. Raises: ValueError: if rewriting runs into an inconsistent value in `colocation_attr_map`.
[ "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 op in state_op_map.values(): for colocation_group in op.colocation_groups(): if not (colocation_group.startswith(tf.compat.as_bytes("loc:@")) and tf.compat.as_str_any(colocation_group[5:]) in state_op_map): tags_prefix = ("" if reported_tags is None else "in the graph for tags %s, " % reported_tags) return ( "A state-holding node x of a module's graph (e.g., a Variable op) " "must not be subject to a tf.colocate_with(y) constraint " "unless y is also a state-holding node.\n" "Details: %snode '%s' has op '%s', which counts as state-holding, " "but Operation.colocation_groups() == %s. " % (tags_prefix, op.name, op.type, op.colocation_groups())) return None
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 op in state_op_map.values(): for colocation_group in op.colocation_groups(): if not (colocation_group.startswith(tf.compat.as_bytes("loc:@")) and tf.compat.as_str_any(colocation_group[5:]) in state_op_map): tags_prefix = ("" if reported_tags is None else "in the graph for tags %s, " % reported_tags) return ( "A state-holding node x of a module's graph (e.g., a Variable op) " "must not be subject to a tf.colocate_with(y) constraint " "unless y is also a state-holding node.\n" "Details: %snode '%s' has op '%s', which counts as state-holding, " "but Operation.colocation_groups() == %s. " % (tags_prefix, op.name, op.type, op.colocation_groups())) return None
[ "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_colocation_groups: return ( "A tensor x used as input in a signature must not be subject to a " "tf.colocate_with(y) constraint. (The reverse would be allowed.)\n" "Details: tensor '%s' appears as input '%s' of signature '%s' " "but has Tensor.op.colocation_groups() == %s" % (tensor, input_name, signature_name, tensor.op.colocation_groups())) return None
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_colocation_groups: return ( "A tensor x used as input in a signature must not be subject to a " "tf.colocate_with(y) constraint. (The reverse would be allowed.)\n" "Details: tensor '%s' appears as input '%s' of signature '%s' " "but has Tensor.op.colocation_groups() == %s" % (tensor, input_name, signature_name, tensor.op.colocation_groups())) return None
[ "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_inputs.extend(("%s.%s" % (name, attr), getattr(tensor, attr)) for attr in ("indices", "values", "dense_shape")) else: dense_inputs.append((name, tensor)) warnings = [(name, tensor.name) for name, tensor in dense_inputs if len(tensor.op.outputs) != 1] if warnings: return ( "WARNING: The inputs declared in hub.add_signature() should be tensors " "from ops with a single output, or else uses of tf.colocate_with() on " "that op can trigger fatal errors when the module is applied and " "colocation constraints have to be rewritten.\nAffected inputs: %s" % ", ".join("%s='%s'" % pair for pair in warnings)) return None
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_inputs.extend(("%s.%s" % (name, attr), getattr(tensor, attr)) for attr in ("indices", "values", "dense_shape")) else: dense_inputs.append((name, tensor)) warnings = [(name, tensor.name) for name, tensor in dense_inputs if len(tensor.op.outputs) != 1] if warnings: return ( "WARNING: The inputs declared in hub.add_signature() should be tensors " "from ops with a single output, or else uses of tf.colocate_with() on " "that op can trigger fatal errors when the module is applied and " "colocation constraints have to be rewritten.\nAffected inputs: %s" % ", ".join("%s='%s'" % pair for pair in warnings)) return None
[ "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 Variables objects. state_map: a map from tensors names in the original graph def to the instantiated tensors to be used as a state_map. """ import_collections = [ tf_v1.GraphKeys.GLOBAL_VARIABLES, tf_v1.GraphKeys.MODEL_VARIABLES, tf_v1.GraphKeys.TABLE_INITIALIZERS, tf_v1.GraphKeys.ASSET_FILEPATHS, # Typically used to initialize tables. tf_v1.GraphKeys.COND_CONTEXT, tf_v1.GraphKeys.WHILE_CONTEXT, ] if self._trainable: # TODO(b/64049014): Import UPDATE_OPS which do not depend on inputs. import_collections.extend([tf_v1.GraphKeys.TRAINABLE_VARIABLES, tf_v1.GraphKeys.REGULARIZATION_LOSSES]) absolute_scope_name = tf_v1.get_default_graph().unique_name( name, mark_as_used=False) relative_scope_name = absolute_scope_name.split("/")[-1] assert relative_scope_name == name # verify name scope was indeed unused. meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.CopyFrom(self._meta_graph) meta_graph_lib.filter_collections(meta_graph, import_collections) meta_graph_lib.prefix_shared_name_attributes(meta_graph, absolute_scope_name) tf_v1.train.import_meta_graph( meta_graph, input_map={}, import_scope=relative_scope_name) # Build a list from the variable name in the module definition to the actual # instantiated variables. variables_tensor_map = {} for var in tf_v1.global_variables(): if var.op.name.startswith(absolute_scope_name + "/"): variables_tensor_map[var.name[len(absolute_scope_name)+1:]] = var # Build a map of tensors to feed from the state-graph into subsequent # apply-graphs. def _get_tensor(tensor_name): return tf_v1.get_default_graph().get_tensor_by_name( meta_graph_lib.prepend_name_scope( tensor_name, import_scope=absolute_scope_name)) state_op_names = list_registered_stateful_ops_without_inputs() state_map = get_state_map(meta_graph, state_op_names, set(), _get_tensor) return variables_tensor_map, state_map
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 Variables objects. state_map: a map from tensors names in the original graph def to the instantiated tensors to be used as a state_map. """ import_collections = [ tf_v1.GraphKeys.GLOBAL_VARIABLES, tf_v1.GraphKeys.MODEL_VARIABLES, tf_v1.GraphKeys.TABLE_INITIALIZERS, tf_v1.GraphKeys.ASSET_FILEPATHS, # Typically used to initialize tables. tf_v1.GraphKeys.COND_CONTEXT, tf_v1.GraphKeys.WHILE_CONTEXT, ] if self._trainable: # TODO(b/64049014): Import UPDATE_OPS which do not depend on inputs. import_collections.extend([tf_v1.GraphKeys.TRAINABLE_VARIABLES, tf_v1.GraphKeys.REGULARIZATION_LOSSES]) absolute_scope_name = tf_v1.get_default_graph().unique_name( name, mark_as_used=False) relative_scope_name = absolute_scope_name.split("/")[-1] assert relative_scope_name == name # verify name scope was indeed unused. meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.CopyFrom(self._meta_graph) meta_graph_lib.filter_collections(meta_graph, import_collections) meta_graph_lib.prefix_shared_name_attributes(meta_graph, absolute_scope_name) tf_v1.train.import_meta_graph( meta_graph, input_map={}, import_scope=relative_scope_name) # Build a list from the variable name in the module definition to the actual # instantiated variables. variables_tensor_map = {} for var in tf_v1.global_variables(): if var.op.name.startswith(absolute_scope_name + "/"): variables_tensor_map[var.name[len(absolute_scope_name)+1:]] = var # Build a map of tensors to feed from the state-graph into subsequent # apply-graphs. def _get_tensor(tensor_name): return tf_v1.get_default_graph().get_tensor_by_name( meta_graph_lib.prepend_name_scope( tensor_name, import_scope=absolute_scope_name)) state_op_names = list_registered_stateful_ops_without_inputs() state_map = get_state_map(meta_graph, state_op_names, set(), _get_tensor) return variables_tensor_map, state_map
[ "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 tensors names in the original graph def to the instantiated tensors to be used as a state_map.
[ "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_map = tensor_info.build_input_map(signature_def.inputs, input_tensors) # Build a input map to feed when importing the apply-graph by augmenting the # state_map with the input args. This allows an input to override a tensor # from the state-graph. feed_map = dict(self._state_map) # If we are applying the module in a function with a TPUReplicateContext, we # must capture the state tensors in generating our feedmap and prune out # assign ops. Function graph semantics are different in that all ops are # executed regardless of dependency. # TODO(b/112575006): The following adds functionality of function call # within a TPU context. Work to generalize this for all function calls is # ongoing. if self._is_tpu_graph_function(): for k, v in self._state_map.items(): feed_map[k] = apply_graph.capture(v) meta_graph_lib.prune_unused_nodes(meta_graph, signature_def) # After we prune the metagraph def, we might need to prune away # infeeds which no longer exist. meta_graph_lib.prune_feed_map(meta_graph, infeed_map) elif apply_graph.building_function: raise NotImplementedError( "Using TF-Hub module within a TensorFlow defined function " "is currently not supported.") # As state ops in the apply graph are unused, replace them with Placeholders # so that in a heirarchical instantiation, apply_graph state ops are # ignored. replace_apply_state(meta_graph, list_registered_stateful_ops_without_inputs(), feed_map) feed_map.update(infeed_map) # Make state tensors enter the current context. This way the Module can be # applied inside a control flow structure such as a while_loop. control_flow = apply_graph._get_control_flow_context() # pylint: disable=protected-access if control_flow: for key, value in sorted(feed_map.items()): feed_map[key] = control_flow.AddValue(value) # Don't mark the name as used at this point - import_scoped_meta_graph will # start using it. absolute_scope_name = apply_graph.unique_name(name, mark_as_used=False) relative_scope_name = absolute_scope_name.split("/")[-1] import_collections = [ # In most cases ASSET_FILEPATHS are only used for the TABLE_INITIALIZERS # ops, however one could create a graph that uses an asset at any other # time. As so everytime we bring the tensor with that has the asset # filename we must annotate it as so, so later re-exports have that # semantic information and can handle it. tf_v1.GraphKeys.ASSET_FILEPATHS, tf_v1.GraphKeys.COND_CONTEXT, tf_v1.GraphKeys.WHILE_CONTEXT, ] if self._trainable: import_collections.extend([tf_v1.GraphKeys.UPDATE_OPS]) meta_graph_lib.filter_collections(meta_graph, import_collections) meta_graph_lib.prefix_shared_name_attributes(meta_graph, absolute_scope_name) if len(meta_graph.collection_def) and self._is_tpu_graph_function(): raise NotImplementedError( "Applying modules with collections inside TPU functions is not " "supported.") tf_v1.train.import_meta_graph( meta_graph, input_map=feed_map, import_scope=relative_scope_name) fix_colocation_after_import(input_map=feed_map, absolute_import_scope=absolute_scope_name) def get_tensor(name): # When trying to output an input tensor there are no nodes created within # the apply scope. So one must look into the input map. try: return feed_map[name] except KeyError: return apply_graph.get_tensor_by_name( meta_graph_lib.prepend_name_scope( name, import_scope=absolute_scope_name)) return tensor_info.build_output_map(signature_def.outputs, get_tensor)
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_map = tensor_info.build_input_map(signature_def.inputs, input_tensors) # Build a input map to feed when importing the apply-graph by augmenting the # state_map with the input args. This allows an input to override a tensor # from the state-graph. feed_map = dict(self._state_map) # If we are applying the module in a function with a TPUReplicateContext, we # must capture the state tensors in generating our feedmap and prune out # assign ops. Function graph semantics are different in that all ops are # executed regardless of dependency. # TODO(b/112575006): The following adds functionality of function call # within a TPU context. Work to generalize this for all function calls is # ongoing. if self._is_tpu_graph_function(): for k, v in self._state_map.items(): feed_map[k] = apply_graph.capture(v) meta_graph_lib.prune_unused_nodes(meta_graph, signature_def) # After we prune the metagraph def, we might need to prune away # infeeds which no longer exist. meta_graph_lib.prune_feed_map(meta_graph, infeed_map) elif apply_graph.building_function: raise NotImplementedError( "Using TF-Hub module within a TensorFlow defined function " "is currently not supported.") # As state ops in the apply graph are unused, replace them with Placeholders # so that in a heirarchical instantiation, apply_graph state ops are # ignored. replace_apply_state(meta_graph, list_registered_stateful_ops_without_inputs(), feed_map) feed_map.update(infeed_map) # Make state tensors enter the current context. This way the Module can be # applied inside a control flow structure such as a while_loop. control_flow = apply_graph._get_control_flow_context() # pylint: disable=protected-access if control_flow: for key, value in sorted(feed_map.items()): feed_map[key] = control_flow.AddValue(value) # Don't mark the name as used at this point - import_scoped_meta_graph will # start using it. absolute_scope_name = apply_graph.unique_name(name, mark_as_used=False) relative_scope_name = absolute_scope_name.split("/")[-1] import_collections = [ # In most cases ASSET_FILEPATHS are only used for the TABLE_INITIALIZERS # ops, however one could create a graph that uses an asset at any other # time. As so everytime we bring the tensor with that has the asset # filename we must annotate it as so, so later re-exports have that # semantic information and can handle it. tf_v1.GraphKeys.ASSET_FILEPATHS, tf_v1.GraphKeys.COND_CONTEXT, tf_v1.GraphKeys.WHILE_CONTEXT, ] if self._trainable: import_collections.extend([tf_v1.GraphKeys.UPDATE_OPS]) meta_graph_lib.filter_collections(meta_graph, import_collections) meta_graph_lib.prefix_shared_name_attributes(meta_graph, absolute_scope_name) if len(meta_graph.collection_def) and self._is_tpu_graph_function(): raise NotImplementedError( "Applying modules with collections inside TPU functions is not " "supported.") tf_v1.train.import_meta_graph( meta_graph, input_map=feed_map, import_scope=relative_scope_name) fix_colocation_after_import(input_map=feed_map, absolute_import_scope=absolute_scope_name) def get_tensor(name): # When trying to output an input tensor there are no nodes created within # the apply scope. So one must look into the input map. try: return feed_map[name] except KeyError: return apply_graph.get_tensor_by_name( meta_graph_lib.prepend_name_scope( name, import_scope=absolute_scope_name)) return tensor_info.build_output_map(signature_def.outputs, get_tensor)
[ "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.value != value: self.has_error = True self._context["new_value"] = value self._context.update({"new_" + k: v for k, v in context.items()})
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.value != value: self.has_error = True self._context["new_value"] = value self._context.update({"new_" + k: v for k, v in context.items()})
[ "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)) return self.value
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)) return self.value
[ "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 Tensor, but Variable.value() is.) Raises: TypeError: if the arguments have the wrong types. """ _check_dict_maps_to_tensors_or_sparse_tensors(inputs) _check_dict_maps_to_tensors_or_sparse_tensors(outputs) input_info = { input_name: tf_v1.saved_model.utils.build_tensor_info(tensor) for input_name, tensor in inputs.items() } output_info = { output_name: tf_v1.saved_model.utils.build_tensor_info(tensor) for output_name, tensor in outputs.items() } signature = tf_v1.saved_model.signature_def_utils.build_signature_def( input_info, output_info) tf_v1.add_to_collection(_SIGNATURE_COLLECTION, (key, signature))
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 Tensor, but Variable.value() is.) Raises: TypeError: if the arguments have the wrong types. """ _check_dict_maps_to_tensors_or_sparse_tensors(inputs) _check_dict_maps_to_tensors_or_sparse_tensors(outputs) input_info = { input_name: tf_v1.saved_model.utils.build_tensor_info(tensor) for input_name, tensor in inputs.items() } output_info = { output_name: tf_v1.saved_model.utils.build_tensor_info(tensor) for output_name, tensor in outputs.items() } signature = tf_v1.saved_model.signature_def_utils.build_signature_def( input_info, output_info) tf_v1.add_to_collection(_SIGNATURE_COLLECTION, (key, signature))
[ "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: TypeError: if the arguments have the wrong types.
[ "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 module_fn.") for key, signature in named_signatures: meta_graph.signature_def[key].CopyFrom(signature)
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 module_fn.") for key, signature in named_signatures: meta_graph.signature_def[key].CopyFrom(signature)
[ "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.ModuleAttachment(key=key, value=the_bytes))
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.ModuleAttachment(key=key, value=the_bytes))
[ "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 indeterminism. (attachment.key, attachment) for attachment in added_attachments) meta_graph.collection_def[ATTACHMENT_COLLECTION_SAVED].bytes_list.value[:] = [ attachment.SerializeToString() for attachment in unique_attachments.values()]
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 indeterminism. (attachment.key, attachment) for attachment in added_attachments) meta_graph.collection_def[ATTACHMENT_COLLECTION_SAVED].bytes_list.value[:] = [ attachment.SerializeToString() for attachment in unique_attachments.values()]
[ "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 graph had been built. Raises: ValueError: if `meta-graph` is malformed. """ result = {} if ATTACHMENT_COLLECTION_SAVED not in meta_graph.collection_def: return result collection_def = meta_graph.collection_def[ATTACHMENT_COLLECTION_SAVED] if collection_def.WhichOneof("kind") != "bytes_list": raise ValueError( "Internal CollectionDef for attached messages has kind %s, " "expected bytes_list" % collection_def.WhichOneof("kind")) attachment = module_attachment_pb2.ModuleAttachment() for value in collection_def.bytes_list.value: attachment.ParseFromString(value) result[attachment.key] = attachment.value # Immutable; needs no copy. return result
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 graph had been built. Raises: ValueError: if `meta-graph` is malformed. """ result = {} if ATTACHMENT_COLLECTION_SAVED not in meta_graph.collection_def: return result collection_def = meta_graph.collection_def[ATTACHMENT_COLLECTION_SAVED] if collection_def.WhichOneof("kind") != "bytes_list": raise ValueError( "Internal CollectionDef for attached messages has kind %s, " "expected bytes_list" % collection_def.WhichOneof("kind")) attachment = module_attachment_pb2.ModuleAttachment() for value in collection_def.bytes_list.value: attachment.ParseFromString(value) result[attachment.key] = attachment.value # Immutable; needs no copy. return result
[ "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: if `meta-graph` is malformed.
[ "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.") if len(node_def.attr["value"].tensor.string_val) != 1: raise TypeError("Asset node must be a scalar.")
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.") if len(node_def.attr["value"].tensor.string_val) != 1: raise TypeError("Asset node must be a scalar.")
[ "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, the SavedModel GraphDefs can be used without feeding asset tensors. Args: saved_model_proto: SavedModel proto to be modified. path: path where the SavedModel is being loaded from. """ for meta_graph in saved_model_proto.meta_graphs: node_asset_map = {} if tf_v1.saved_model.constants.ASSETS_KEY in meta_graph.collection_def: assets_any_proto = meta_graph.collection_def[ tf_v1.saved_model.constants.ASSETS_KEY].any_list.value for asset_any_proto in assets_any_proto: asset_proto = meta_graph_pb2.AssetFileDef() asset_any_proto.Unpack(asset_proto) asset_filename = _get_asset_filename(path, asset_proto.filename) node_asset_map[_get_node_name_from_tensor( asset_proto.tensor_info.name)] = asset_filename del meta_graph.collection_def[tf_v1.saved_model.constants.ASSETS_KEY] for node in meta_graph.graph_def.node: asset_filepath = node_asset_map.get(node.name) if asset_filepath: _check_asset_node_def(node) node.attr["value"].tensor.string_val[0] = asset_filepath
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, the SavedModel GraphDefs can be used without feeding asset tensors. Args: saved_model_proto: SavedModel proto to be modified. path: path where the SavedModel is being loaded from. """ for meta_graph in saved_model_proto.meta_graphs: node_asset_map = {} if tf_v1.saved_model.constants.ASSETS_KEY in meta_graph.collection_def: assets_any_proto = meta_graph.collection_def[ tf_v1.saved_model.constants.ASSETS_KEY].any_list.value for asset_any_proto in assets_any_proto: asset_proto = meta_graph_pb2.AssetFileDef() asset_any_proto.Unpack(asset_proto) asset_filename = _get_asset_filename(path, asset_proto.filename) node_asset_map[_get_node_name_from_tensor( asset_proto.tensor_info.name)] = asset_filename del meta_graph.collection_def[tf_v1.saved_model.constants.ASSETS_KEY] for node in meta_graph.graph_def.node: asset_filepath = node_asset_map.get(node.name) if asset_filepath: _check_asset_node_def(node) node.attr["value"].tensor.string_val[0] = asset_filepath
[ "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 tensors. Args: saved_model_proto: SavedModel proto to be modified. path: path where the SavedModel is being loaded from.
[ "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`. This is roughly the inverse operation of `_merge_assets_key_collection`. Args: saved_model_proto: SavedModel proto to be modified. export_path: string with path where the saved_model_proto will be exported. Returns: A map from original asset filename to asset filename when exporting the SavedModel to path. Raises: ValueError: on unsuported/unexpected SavedModel. """ asset_filenames = {} used_asset_filenames = set() def _make_asset_filename(original_filename): """Returns the asset filename to use for the file.""" if original_filename in asset_filenames: return asset_filenames[original_filename] basename = os.path.basename(original_filename) suggestion = basename index = 0 while suggestion in used_asset_filenames: suggestion = "%s%d" % (basename, index) index += 1 asset_filenames[original_filename] = suggestion used_asset_filenames.add(suggestion) return suggestion for meta_graph in saved_model_proto.meta_graphs: collection_def = meta_graph.collection_def.get( tf_v1.GraphKeys.ASSET_FILEPATHS) if collection_def is None: continue if collection_def.WhichOneof("kind") != "node_list": raise ValueError( "MetaGraph collection ASSET_FILEPATHS is not a list of tensors.") for tensor in collection_def.node_list.value: if not tensor.endswith(":0"): raise ValueError("Unexpected tensor in ASSET_FILEPATHS collection.") asset_nodes = set([ _get_node_name_from_tensor(tensor) for tensor in collection_def.node_list.value ]) tensor_filename_map = {} for node in meta_graph.graph_def.node: if node.name in asset_nodes: _check_asset_node_def(node) filename = node.attr["value"].tensor.string_val[0] tensor_filename_map[node.name + ":0"] = filename # Clear value to avoid leaking the original path. node.attr["value"].tensor.string_val[0] = ( tf.compat.as_bytes("SAVEDMODEL-ASSET")) if tensor_filename_map: assets_key_collection = meta_graph.collection_def[ tf_v1.saved_model.constants.ASSETS_KEY] for tensor, filename in sorted(tensor_filename_map.items()): asset_proto = meta_graph_pb2.AssetFileDef() asset_proto.filename = _make_asset_filename(filename) asset_proto.tensor_info.name = tensor assets_key_collection.any_list.value.add().Pack(asset_proto) return { original_filename: _get_asset_filename(export_path, asset_filename) for original_filename, asset_filename in asset_filenames.items() }
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`. This is roughly the inverse operation of `_merge_assets_key_collection`. Args: saved_model_proto: SavedModel proto to be modified. export_path: string with path where the saved_model_proto will be exported. Returns: A map from original asset filename to asset filename when exporting the SavedModel to path. Raises: ValueError: on unsuported/unexpected SavedModel. """ asset_filenames = {} used_asset_filenames = set() def _make_asset_filename(original_filename): """Returns the asset filename to use for the file.""" if original_filename in asset_filenames: return asset_filenames[original_filename] basename = os.path.basename(original_filename) suggestion = basename index = 0 while suggestion in used_asset_filenames: suggestion = "%s%d" % (basename, index) index += 1 asset_filenames[original_filename] = suggestion used_asset_filenames.add(suggestion) return suggestion for meta_graph in saved_model_proto.meta_graphs: collection_def = meta_graph.collection_def.get( tf_v1.GraphKeys.ASSET_FILEPATHS) if collection_def is None: continue if collection_def.WhichOneof("kind") != "node_list": raise ValueError( "MetaGraph collection ASSET_FILEPATHS is not a list of tensors.") for tensor in collection_def.node_list.value: if not tensor.endswith(":0"): raise ValueError("Unexpected tensor in ASSET_FILEPATHS collection.") asset_nodes = set([ _get_node_name_from_tensor(tensor) for tensor in collection_def.node_list.value ]) tensor_filename_map = {} for node in meta_graph.graph_def.node: if node.name in asset_nodes: _check_asset_node_def(node) filename = node.attr["value"].tensor.string_val[0] tensor_filename_map[node.name + ":0"] = filename # Clear value to avoid leaking the original path. node.attr["value"].tensor.string_val[0] = ( tf.compat.as_bytes("SAVEDMODEL-ASSET")) if tensor_filename_map: assets_key_collection = meta_graph.collection_def[ tf_v1.saved_model.constants.ASSETS_KEY] for tensor, filename in sorted(tensor_filename_map.items()): asset_proto = meta_graph_pb2.AssetFileDef() asset_proto.filename = _make_asset_filename(filename) asset_proto.tensor_info.name = tensor assets_key_collection.any_list.value.add().Pack(asset_proto) return { original_filename: _get_asset_filename(export_path, asset_filename) for original_filename, asset_filename in asset_filenames.items() }
[ "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_collection`. Args: saved_model_proto: SavedModel proto to be modified. export_path: string with path where the saved_model_proto will be exported. Returns: A map from original asset filename to asset filename when exporting the SavedModel to path. Raises: ValueError: on unsuported/unexpected SavedModel.
[ "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: saved_model.ParseFromString(file_content) except message.DecodeError as e: raise IOError("Cannot parse file %s: %s." % (path_to_pb, str(e))) return saved_model
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: saved_model.ParseFromString(file_content) except message.DecodeError as e: raise IOError("Cannot parse file %s: %s." % (path_to_pb, str(e))) return saved_model
[ "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