INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon... | def PopupGetFile(message, title=None, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anyw... |
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return: | def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
'''
# if not self.Shown:
# self.Shown = True
# self.TrayIcon.show()
timeout1 = timeout
... |
Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
:param data: Optional in-ram icon
:param data_base64: Optional base64 icon
:param time: How long to display mess... | def ShowMessage(self, title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000):
'''
Shows a balloon above icon in system tray
:param title: Title shown in balloon
:param message: Message to be displayed
:param filename: Optional icon filename
... |
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return: | def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,):
'''
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param... |
implement dragging | def on_mouse(self, event):
'''
implement dragging
'''
# print('on_mouse')
if not event.Dragging():
self._dragPos = None
return
# self.CaptureMouse()
if not self._dragPos:
self._dragPos = event.GetPosition()
else:
... |
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return: | def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha * 255
if self._AlphaChannel is not None:
self.MasterFrame.SetTransparent(self._AlphaCh... |
A worker thrread that communicates with the GUI
These threads can call functions that block withouth affecting the GUI (a good thing)
Note that this function is the code started as each thread. All threads are identical in this way
:param thread_name: Text name used for displaying info
:param run_freq:... | def worker_thread(thread_name, run_freq, gui_queue):
"""
A worker thrread that communicates with the GUI
These threads can call functions that block withouth affecting the GUI (a good thing)
Note that this function is the code started as each thread. All threads are identical in this way
:param thr... |
Send one ping to the given >destIP<. | def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size):
"""
Send one ping to the given >destIP<.
"""
#destIP = socket.gethostbyname(destIP)
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
# (packet_size - 8) - Remove header size from packet size
myChecks... |
Receive the ping from the socket. Timeout = in ms | def receive_one_ping(mySocket, myID, timeout):
"""
Receive the ping from the socket. Timeout = in ms
"""
timeLeft = timeout/1000
while True: # Loop while waiting for packet or timeout
startedSelect = default_timer()
whatReady = select.select([mySocket], [], [], timeLeft)
how... |
run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@param window: the PySimpleGUI window that the output is going to (needed to do refresh on)
@return: (return code from command, command output) | def runCommand(cmd, timeout=None, window=None):
""" run shell command
@param cmd: command to execute
@param timeout: timeout for command execution
@param window: the PySimpleGUI window that the output is going to (needed to do refresh on)
@return: (return code from command, command output)
"""
p = subproce... |
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings | def font_parse_string(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font ... |
Create and show a form on tbe caller's behalf.
:param title:
:param max_value:
:param args: ANY number of arguments the caller wants to display
:param orientation:
:param bar_color:
:param size:
:param Style:
:param StyleOffset:
:return: ProgressBar object that is in the form | def _ProgressMeter(title, max_value, *args, orientation=None, bar_color=(None, None), button_color=None,
size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None, grab_anywhere=False):
'''
Create and show a form on tbe caller's behalf.
:param title:
:param max_value:
:param args: ANY num... |
Update the progress meter for a form
:param form: class ProgressBar
:param value: int
:return: True if not cancelled, OK....False if Error | def _ProgressMeterUpdate(bar, value, text_elem, *args):
'''
Update the progress meter for a form
:param form: class ProgressBar
:param value: int
:return: True if not cancelled, OK....False if Error
'''
global _my_windows
if bar == None: return False
if bar.BarExpired: return False
... |
A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second
function call before your loop. You've got enough code to write!
:param title: Title will be shown on the window
:param current_value: Current count of your items
:param max_value: Max value your count will eve... | def EasyProgressMeter(title, current_value, max_value, *args, orientation=None, bar_color=(None, None),
button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None):
'''
A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second
function call... |
Show Popup box and immediately return (does not block)
:param args:
:param button_type:
:param button_color:
:param background_color:
:param text_color:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param font:
:param... | def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None,
auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON,
line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep... |
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
... | def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
... |
Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon... | def PopupGetFile(message, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*.*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False... |
Display data in a table format | def TableSimulation():
"""
Display data in a table format
"""
sg.SetOptions(element_padding=(0,0))
menu_def = [['File', ['Open', 'Save', 'Exit']],
['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
['Help', 'About...'],]
columm_layout = [[]]
MAX_ROWS = 2... |
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but do... | def HowDoI():
'''
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with... |
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing | def QueryHowDoI(Query, num_answers, full_text):
'''
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing
'''
howdoi_command = HOW_DO_I_CO... |
Exports a ModuleSpec with weights taken from a checkpoint.
This is an helper to export modules directly from a ModuleSpec
without having to create a session and set the variables to the
intended values.
Example usage:
```python
spec = hub.create_module_spec(module_fn)
spec.export("/path/t... | def export(self, path, _sentinel=None, # pylint: disable=invalid-name
checkpoint_path=None, name_transform_fn=None):
"""Exports a ModuleSpec with weights taken from a checkpoint.
This is an helper to export modules directly from a ModuleSpec
without having to create a session and set the vari... |
Returns the message attached to the module under the given key, or None.
Module publishers can attach protocol messages to modules at creation time
to provide module consumers with additional information, e.g., on module
usage or provenance (see see hub.attach_message()). A typical use would be
to stor... | def get_attached_message(self, key, message_type, tags=None, required=False):
"""Returns the message attached to the module under the given key, or None.
Module publishers can attach protocol messages to modules at creation time
to provide module consumers with additional information, e.g., on module
u... |
Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images for each label and their paths.
Args:
image_dir: String path to a folder conta... | def create_image_lists(image_dir, testing_percentage, validation_percentage):
"""Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images fo... |
Returns a path to an image for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Int offset of the image we want. This will be moduloed by the
available number of images for the label, so it can b... | def get_image_path(image_lists, label_name, index, image_dir, category):
"""Returns a path to an image for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image for.
index: Int offset of the image we want. This wil... |
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... | def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,
category, module_name):
"""Returns a path to a bottleneck file for a label at the given index.
Args:
image_lists: OrderedDict of training images for each label.
label_name: Label string we want to get an image f... |
Creates a graph and loads Hub Module into it.
Args:
module_spec: the hub.ModuleSpec for the image module being used.
Returns:
graph: the tf.Graph that was created.
bottleneck_tensor: the bottleneck values output by the module.
resized_input_tensor: the input images, resized as expected by the modu... | def create_module_graph(module_spec):
"""Creates a graph and loads Hub Module into it.
Args:
module_spec: the hub.ModuleSpec for the image module being used.
Returns:
graph: the tf.Graph that was created.
bottleneck_tensor: the bottleneck values output by the module.
resized_input_tensor: the in... |
Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tenso... | def run_bottleneck_on_image(sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
im... |
Create a single 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.... |
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.
... | def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,
category, bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
"""Retrieves or calculates bottl... |
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 ... | def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, module_name):
"""Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read th... |
Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of tr... | def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
"""Retrieves bottlene... |
Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
recalculate the full model for every image, and so we can't use cached
bottleneck values. Instead we find random images for the requested category,
run them through th... | def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we ha... |
Creates the operations to apply the specified distortions.
During training it can help to improve the results if we run the images
through simple distortions like crops, scales, and flips. These reflect the
kind of variations we expect in the real world, and so can help train the
model to cope with natural dat... | 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... |
Attach a lot of summaries to a Tensor (for TensorBoard visualization). | def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary... |
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... | def add_final_retrain_ops(class_count, final_tensor_name, bottleneck_tensor,
quantize_layer, is_training):
"""Adds a new softmax and fully-connected layer for training and eval.
We need to retrain the top layer to identify our new classes, so this function
adds the right operations to t... |
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). | 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,... |
Runs a final evaluation on an eval graph using the test data set.
Args:
train_session: Session for the train graph with the tensors below.
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
image_lists: OrderedDict of training images for each label.
jp... | 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 ... |
Builds an restored eval session without train operations for exporting.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
Returns:
Eval session containing the restored eval graph.
The bottleneck input, ground truth, eval step, and prediction tens... | def build_eval_session(module_spec, class_count):
"""Builds an restored eval session without train operations for exporting.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
Returns:
Eval session containing the restored eval graph.
The bottlen... |
Saves an graph to file, creating a valid quantized one if necessary. | 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.... |
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. | 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... |
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. | 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... |
Converts logging_level into TensorFlow logging verbosity value
Args:
logging_level: String value representing logging level: 'DEBUG', 'INFO',
'WARN', 'ERROR', 'FATAL' | 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,
... |
Returns the module's attached ImageModuleInfo message, or None. | 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) |
Returns expected [height, width] dimensions of an image input.
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,... | def get_expected_image_size(module_or_spec, signature=None, input_name=None):
"""Returns expected [height, width] dimensions of an image input.
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 s... |
Returns expected num_channels dimensions of an image input.
This is for advanced users only who expect to handle modules with
image inputs that might not have the 3 usual RGB channels.
Args:
module_or_spec: a Module or ModuleSpec that accepts image inputs.
signature: a string with the key of the signatu... | def get_num_image_channels(module_or_spec, signature=None, input_name=None):
"""Returns expected num_channels dimensions of an image input.
This is for advanced users only who expect to handle modules with
image inputs that might not have the 3 usual RGB channels.
Args:
module_or_spec: a Module or ModuleS... |
Returns a ParsedTensorInfo instance from a TensorInfo 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... |
Returns whether x is a SparseTensor or a parsed sparse tensor info. | 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)) |
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:
... | def _convert_to_compatible_tensor(value, target, error_prefix):
"""Converts `value` into a tensor that can be feed into `tensor_info`.
Args:
value: A value to convert into Tensor or SparseTensor.
target: An object returned by `parse_tensor_info_map`.
error_prefix: A string to prefix on raised TypeError... |
Converts dict `values` in tensors that are compatible with `targets`.
Args:
values: A dict to objects to convert with same keys as `targets`.
targets: A dict returned by `parse_tensor_info_map`.
Returns:
A map with the same keys as `values` but values converted into
Tensor/SparseTensors that can b... | 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` ... |
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... | 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
... |
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... | def build_output_map(protomap, get_tensor_by_name):
"""Builds a map of tensors from `protomap` using `get_tensor_by_name`.
Args:
protomap: A proto map<string,TensorInfo>.
get_tensor_by_name: A lambda that receives a tensor name and returns a
Tensor instance.
Returns:
A map from string to Tenso... |
Whether two signature inputs/outputs match in dtype, shape and sparsity.
Args:
map_a: A proto map<string,TensorInfo>.
map_b: A proto map<string,TensorInfo>.
Returns:
A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and
sparsity. | def tensor_info_proto_maps_match(map_a, map_b):
"""Whether two signature inputs/outputs match in dtype, shape and sparsity.
Args:
map_a: A proto map<string,TensorInfo>.
map_b: A proto map<string,TensorInfo>.
Returns:
A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and
sp... |
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. | def parse_line(line):
"""Parses a line of a text embedding file.
Args:
line: (str) One line of the text embedding file.
Returns:
A token string and its embedding vector in floats.
"""
columns = line.split()
token = columns.pop(0)
values = [float(column) for column in columns]
return token, val... |
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... | 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:
... |
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_... | def make_module_spec(vocabulary_file, vocab_size, embeddings_dim,
num_oov_buckets, preprocess_text):
"""Makes a module spec to simply perform token to embedding lookups.
Input of this module is a 1-D list of string tokens. For T tokens input and
an M dimensional embedding table, the lookup r... |
Exports a TF-Hub module that performs embedding lookups.
Args:
export_path: Location to export the module.
vocabulary: List of the N tokens in the vocabulary.
embeddings: Numpy array of shape [N+K,M] the first N rows are the
M dimensional embeddings for the respective tokens and the next K
ro... | def export(export_path, vocabulary, embeddings, num_oov_buckets,
preprocess_text):
"""Exports a TF-Hub module that performs embedding lookups.
Args:
export_path: Location to export the module.
vocabulary: List of the N tokens in the vocabulary.
embeddings: Numpy array of shape [N+K,M] the fi... |
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. | 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 ... |
Experimental: Create a ModuleSpec out of a SavedModel.
Define a ModuleSpec from a SavedModel. Note that this is not guaranteed to
work in all cases and it assumes the SavedModel has followed some conventions:
- The serialized SaverDef can be ignored and instead can be reconstructed.
- The init op and main op ... | def create_module_spec_from_saved_model(saved_model_path,
drop_collections=None):
"""Experimental: Create a ModuleSpec out of a SavedModel.
Define a ModuleSpec from a SavedModel. Note that this is not guaranteed to
work in all cases and it assumes the SavedModel has follow... |
Register a Module to be exported under `export_name`.
This function registers `module` to be exported by `LatestModuleExporter`
under a subdirectory named `export_name`.
Note that `export_name` must be unique for each module exported from the
current graph. It only controls the export subdirectory name and i... | 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 ... |
Returns a session constructed using `estimator` and `serving_input_fn`.
The Estimator API does not provide an API to construct a graph and session,
making it necessary for this function to replicate how an estimator builds
a graph.
This code is based on `Estimator.export_savedmodel` (another function that
h... | def _make_estimator_serving_session(estimator, serving_input_fn,
checkpoint_path):
"""Returns a session constructed using `estimator` and `serving_input_fn`.
The Estimator API does not provide an API to construct a graph and session,
making it necessary for this function to re... |
Creates a ModuleSpec from a function that builds the module's graph.
The `module_fn` is called on a new graph (not the current one) to build the
graph of the module and define its signatures via `hub.add_signature()`.
Example:
```python
# Define a text embedding module.
def my_text_module_fn():
text_i... | 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:
... |
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 ... | def add_signature(name=None, inputs=None, outputs=None):
"""Adds a signature to the module definition.
NOTE: This must be called within a `module_fn` that is defining a Module.
Args:
name: Signature name as a string. If omitted, it is interpreted as 'default'
and is the signature used when `Module.__c... |
Adds an attached message to the module definition.
NOTE: This must be called within a `module_fn` that is defining a Module.
See ModuleSpec.get_attached_message() for an introduction to attached messages
and the API for module consumers.
To define a new type of attached message:
* Select a reasonably de... | 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... |
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. | 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
... |
Returns a map from tensor names to tensors that hold the state. | def get_state_map(meta_graph, state_ops, unsupported_state_ops,
get_tensor_by_name):
"""Returns a map from tensor names to tensors that hold the state."""
state_map = {}
for node in meta_graph.graph_def.node:
if node.op in state_ops:
tensor_name = node.name + ":0"
tensor = get_te... |
Replaces state ops with non state Placeholder ops for the apply graph. | 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... |
Given a tensor name as node_name:output_number, returns both parts. | def _split_tensor_name(tensor_name):
"""Given a tensor name as node_name:output_number, returns both parts."""
result = re.match(r"(.*):(\d+)$", tensor_name)
if not result:
raise ValueError(
"Unexpected format for tensor name. Expected node_name:output_number. "
"Got %r" % tensor_name)
retur... |
Matches a variable to individual parts.
Args:
variable_key: String identifier of the variable in the module scope.
variable: Variable tensor.
Returns:
partitioned: Whether the variable is partitioned.
name: Name of the variable up to the partitioning.
offset: Offset of the variable into the fu... | def _extract_variable_parts(variable_key, variable):
"""Matches a variable to individual parts.
Args:
variable_key: String identifier of the variable in the module scope.
variable: Variable tensor.
Returns:
partitioned: Whether the variable is partitioned.
name: Name of the variable up to the pa... |
Builds a proper variable map if it contains PartitionedVariables.
Args:
var_node_map: A map to tf.Variables. PartitionedVariables show up in this
map as N entries with keys "<var_name>/part_n".
Returns:
A map to tf.Variables or to list of tf.Variables for each
PartitionedVariables in `var_node_m... | def recover_partitioned_variable_map(var_node_map):
"""Builds a proper variable map if it contains PartitionedVariables.
Args:
var_node_map: A map to tf.Variables. PartitionedVariables show up in this
map as N entries with keys "<var_name>/part_n".
Returns:
A map to tf.Variables or to list of tf.V... |
Checks that tag list contains each set of tags only once. | 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) |
Checks that SavedModelHandler only uses supported collections. | def check_collections_are_supported(saved_model_handler, supported):
"""Checks that SavedModelHandler only uses supported collections."""
for meta_graph in saved_model_handler.meta_graphs:
used_collection_keys = set(meta_graph.collection_def.keys())
unsupported = used_collection_keys - supported
if unsu... |
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. | 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... |
Fixes colocation attributes after import according to input_map.
This function is meant to be called after importing a GraphDef, in order
to rewrite colocate_with constrains analogous to how inputs to ops
are rewritten by input_map during import. It also updates devices accordingly.
The nodes in the given imp... | def fix_colocation_after_import(input_map, absolute_import_scope):
"""Fixes colocation attributes after import according to input_map.
This function is meant to be called after importing a GraphDef, in order
to rewrite colocate_with constrains analogous to how inputs to ops
are rewritten by input_map during im... |
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... | 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... |
Returns a dict mapping from pre-import to post-import colocation attrs.
Args:
input_map: as for fix_colocation_after_import.
absolute_import_scope: as for fix_colocation_after_import.
Returns:
A dict that maps bytes `"loc:@" + absolute_import_scope + "/foo"`
to _ConsistentValues set to the lists o... | def _build_colocation_attr_map(input_map, absolute_import_scope):
"""Returns a dict mapping from pre-import to post-import colocation attrs.
Args:
input_map: as for fix_colocation_after_import.
absolute_import_scope: as for fix_colocation_after_import.
Returns:
A dict that maps bytes `"loc:@" + abso... |
Returns error message for colocation of state ops, or None if ok. | def find_state_op_colocation_error(graph, reported_tags=None):
"""Returns error message for colocation of state ops, or None if ok."""
state_op_types = list_registered_stateful_ops_without_inputs()
state_op_map = {op.name: op for op in graph.get_operations()
if op.type in state_op_types}
for o... |
Returns error message for colocation of signature inputs, or None if ok. | 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... |
Internal.
Args:
path: string where to export the module to.
variables_saver: an unary-function that writes the module variables
checkpoint on the given path. | def _export(self, path, variables_saver):
"""Internal.
Args:
path: string where to export the module to.
variables_saver: an unary-function that writes the module variables
checkpoint on the given path.
"""
self._saved_model_handler.export(path, variables_saver=variables_saver)
... |
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 ... | def _create_state_graph(self, name):
"""Creates the graph nodes that hold the state of the Module.
Args:
name: name scope to create the state graph in.
Returns:
A tuple consisting of:
variables_tensor_map: a map from tensor names in the original graph def
to the created Varia... |
See `ModuleImpl.create_apply_graph`. | def create_apply_graph(self, signature, input_tensors, name):
"""See `ModuleImpl.create_apply_graph`."""
signature_def = self._meta_graph.signature_def.get(signature)
meta_graph = meta_graph_pb2.MetaGraphDef()
meta_graph.CopyFrom(self._meta_graph)
apply_graph = tf_v1.get_default_graph()
infeed_m... |
See `Module.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) |
Receives a value for the object and some context on its source. | def Set(self, value, context=None):
"""Receives a value for the object and some context on its source."""
if self.has_error: return
if self.value is None:
self.value = value
self._context["old_value"] = value
self._context.update({"old_" + k: v for k, v in context.items()})
elif self.v... |
Gets consistent value or raises ValueError with formatted contexts. | def GetConsistentValueOrRaise(self, error_format, context=None):
"""Gets consistent value or raises ValueError with formatted contexts."""
if self.has_error:
full_context = dict(self._context)
if context: full_context.update(context)
raise ValueError(error_format.format(**full_context))
re... |
Returns the directory where to cache the module. | 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()) |
Returns the path for storing variables checkpoints. | 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)) |
tensor_name must have format node_name:output_number. Returns node_name. | def _get_node_name_from_tensor(tensor_name):
"""tensor_name must have format node_name:output_number. Returns node_name."""
result = re.match(r"([^:]*):\d+$", tensor_name)
if not result:
raise ValueError(
"Unexpected format for tensor name. Expected node_name:output_number. "
"Got %r" % tensor... |
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:
... | 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... |
Exports signatures from current graph into a MetaGraphDef. | def _export_signatures(meta_graph):
"""Exports signatures from current graph into a MetaGraphDef."""
named_signatures = tf_v1.get_collection(_SIGNATURE_COLLECTION)
if not named_signatures:
raise ValueError("No signatures present. Please call hub.add_signature(...)"
"at least once in the m... |
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. | def attach_bytes(key, the_bytes):
"""Adds a ModuleAttachment to the current graph.
Args:
key: A string with the unique key of the attachment.
the_bytes: A bytes object with the serialized attachment.
"""
tf_v1.add_to_collection(
_ATTACHMENT_COLLECTION_INTERNAL,
module_attachment_pb2.ModuleA... |
Exports ModuleAttachments from the current tf.Graph into `meta_graph`. | 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 ... |
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... | def get_attached_bytes_map(meta_graph):
"""Returns the dict of ModuleAttachments stored in `meta_graph`.
Args:
meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy()
from some graph.
Returns:
A dict, containing the `(key, bytes)` items passed to `attach_bytes()`
when the gr... |
Raises TypeError if `node_def` does not match the expectations. | def _check_asset_node_def(node_def):
"""Raises TypeError if `node_def` does not match the expectations."""
if node_def.op != "Const":
raise TypeError("Asset node must be of type constant.")
if tf.as_dtype(node_def.attr["dtype"].type) != tf.string:
raise TypeError("Asset node must be of dtype string.")
i... |
Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto.
Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and
modifies nodes with the assets filenames to point to the assets in `path`.
After this transformation, the SavedModel GraphDefs can be used without
feeding asset t... | 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... |
Creates an ASSETS_KEY collection in the GraphDefs in saved_model_proto.
Adds an ASSETS_KEY collection to the GraphDefs in the SavedModel and returns
a map from original asset filename to filename when exporting the SavedModel
to `export_path`.
This is roughly the inverse operation of `_merge_assets_key_collec... | 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`.... |
Reads the savedmodel.pb file containing `SavedModel`. | 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:... |
Creates a SavedModelHandler from a SavedModel in `path`. | 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 |
Adds a copy of Graph with the specified set of tags. | def add_graph_copy(self, graph, tags=None):
"""Adds a copy of Graph with the specified set of tags."""
with graph.as_default():
# Remove default attrs so that Modules created by a tensorflow version
# with ops that have new attrs that are left to their default values can
# still be loaded by o... |
Returns a copy of a MetaGraph with the identical set of tags. | def get_meta_graph_copy(self, tags=None):
"""Returns a copy of a MetaGraph with the identical set of tags."""
meta_graph = self.get_meta_graph(tags)
copy = tf_v1.MetaGraphDef()
copy.CopyFrom(meta_graph)
return copy |
Returns a list of set of tags. | def get_tags(self):
"""Returns a list of set of tags."""
return sorted([frozenset(meta_graph.meta_info_def.tags)
for meta_graph in self.meta_graphs]) |
Exports to SavedModel directory.
Args:
path: path where to export the SavedModel to.
variables_saver: lambda that receives a directory path where to
export checkpoints of variables. | def export(self, path, variables_saver=None):
"""Exports to SavedModel directory.
Args:
path: path where to export the SavedModel to.
variables_saver: lambda that receives a directory path where to
export checkpoints of variables.
"""
# Operate on a copy of self._proto since it need... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.