Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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
... | [] |
Please provide a description of the function: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
... | [] |
Please provide a description of the function:def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha
if self._AlphaChannel is not None:
self.Q... | [] |
Please provide a description of the function:def convert_tkinter_size_to_Wx(size):
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pixels (roughly)
qtsize = size[0]*DEFAULT_PIXELS_TO_CHARS_SCALING[0], size[1]*DEFAULT_PIX... | [
"\n Converts size in characters to size in pixels\n :param size: size in characters, rows\n :return: size in pixels, pixels\n "
] |
Please provide a description of the function:def font_to_wx_font(font):
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
name = _font[0]
family = _font[0]
point_size = int(_font[1])
# style = _font[2]
underline =... | [
"\n Convert from font string/tyuple into a Qt style sheet string\n :param font: \"Arial 10 Bold\" or ('Arial', 10, 'Bold)\n :return: style string that can be combined with other style strings\n "
] |
Please provide a description of the function:def PopupError(*args, button_color=DEFAULT_ERROR_BUTTON_COLOR, background_color=None, text_color=None, auto_close=False,
auto_close_duration=None, non_blocking=False, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None,
no_titlebar=False, grab_... | [
"\n Popup with colored button and 'Error' as button text\n :param args:\n :param button_color:\n :param background_color:\n :param text_color:\n :param auto_close:\n :param auto_close_duration:\n :param non_blocking:\n :param icon:\n :param line_width:\n :param font:\n :param no_... |
Please provide a description of the function:def PopupGetFolder(message, title=None, 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_... | [
"\n Display popup with text entry field and browse button. Browse for folder\n :param message:\n :param default_path:\n :param no_window:\n :param size:\n :param button_color:\n :param background_color:\n :param text_color:\n :param icon:\n :param font:\n :param no_titlebar:\n :p... |
Please provide a description of the function: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_... | [
"\n Display popup with text entry field and browse button. Browse for file\n :param message:\n :param default_path:\n :param default_extension:\n :param save_as:\n :param file_types:\n :param no_window:\n :param size:\n :param button_color:\n :param background_color:\n :param te... |
Please provide a description of the function: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.Tr... | [] |
Please provide a description of the function: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
... | [] |
Please provide a description of the function: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
... | [] |
Please provide a description of the function: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._dragPo... | [] |
Please provide a description of the function: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:
... | [] |
Please provide a description of the function:def worker_thread(thread_name, run_freq, gui_queue):
print('Starting thread - {} that runds every {} ms'.format(thread_name, run_freq))
for i in itertools.count(): # loop forever, keeping count in i as it loops
time.sleep(run... | [
"\n A worker thrread that communicates with the GUI\n These threads can call functions that block withouth affecting the GUI (a good thing)\n Note that this function is the code started as each thread. All threads are identical in this way\n :param thread_name: Text name used for displaying info\n :... |
Please provide a description of the function:def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size):
#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
myChecksum = 0
... | [
"\n Send one ping to the given >destIP<.\n "
] |
Please provide a description of the function:def receive_one_ping(mySocket, myID, timeout):
timeLeft = timeout/1000
while True: # Loop while waiting for packet or timeout
startedSelect = default_timer()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (defa... | [
"\n Receive the ping from the socket. Timeout = in ms\n "
] |
Please provide a description of the function:def runCommand(cmd, timeout=None, window=None):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
for line in p.stdout:
line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backsla... | [
" run shell command\n\t@param cmd: command to execute\n\t@param timeout: timeout for command execution\n\t@param window: the PySimpleGUI window that the output is going to (needed to do refresh on)\n\t@return: (return code from command, command output)\n\t"
] |
Please provide a description of the function:def font_parse_string(font):
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
family = _font[0]
point_size = int(_font[1])
style = _font[2:] if len(_font) > 1 else None
# ... | [
"\n Convert from font string/tyuple into a Qt style sheet string\n :param font: \"Arial 10 Bold\" or ('Arial', 10, 'Bold)\n :return: style string that can be combined with other style strings\n "
] |
Please provide a description of the function: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:
... | [] |
Please provide a description of the function: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: retur... | [] |
Please provide a description of the function: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 ... | [] |
Please provide a description of the function: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,... | [
"\n Show Popup box and immediately return (does not block)\n :param args:\n :param button_type:\n :param button_color:\n :param background_color:\n :param text_color:\n :param auto_close:\n :param auto_close_duration:\n :param non_blocking:\n :param icon:\n :param line_width:\n :... |
Please provide a description of the function: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, l... | [
"\n Display popup with text entry field and browse button. Browse for folder\n :param message:\n :param default_path:\n :param no_window:\n :param size:\n :param button_color:\n :param background_color:\n :param text_color:\n :param icon:\n :param font:\n :param no_titlebar:\n :p... |
Please provide a description of the function: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... | [
"\n Display popup with text entry field and browse button. Browse for file\n :param message:\n :param default_path:\n :param default_extension:\n :param save_as:\n :param file_types:\n :param no_window:\n :param size:\n :param button_color:\n :param background_color:\n :param te... |
Please provide a description of the function:def TableSimulation():
sg.SetOptions(element_padding=(0,0))
menu_def = [['File', ['Open', 'Save', 'Exit']],
['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
['Help', 'About...'],]
columm_layout = [[]]
MAX_ROWS = 20... | [
"\n Display data in a table format\n "
] |
Please provide a description of the function: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 - The... | [] |
Please provide a description of the function: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: not... | [] |
Please provide a description of the function: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 # pylint: disable=g-import-not-at-top
if not checkpoint_path:
raise Val... | [
"Exports a ModuleSpec with weights taken from a checkpoint.\n\n This is an helper to export modules directly from a ModuleSpec\n without having to create a session and set the variables to the\n intended values.\n\n Example usage:\n\n ```python\n spec = hub.create_module_spec(module_fn)\n spec.... |
Please provide a description of the function:def get_attached_message(self, key, message_type, tags=None, required=False):
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 "
... | [
"Returns the message attached to the module under the given key, or None.\n\n Module publishers can attach protocol messages to modules at creation time\n to provide module consumers with additional information, e.g., on module\n usage or provenance (see see hub.attach_message()). A typical use would be\n ... |
Please provide a description of the function:def create_image_lists(image_dir, testing_percentage, validation_percentage):
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... | [
"Builds a list of training images from the file system.\n\n Analyzes the sub folders in the image directory, splits them into stable\n training, testing, and validation sets, and returns a data structure\n describing the lists of images for each label and their paths.\n\n Args:\n image_dir: String path to a ... |
Please provide a description of the function: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_name)
label_lists = image_lists[label_name]
if category not in label_lists:
tf.logging.fatal('Catego... | [
"Returns a path to an image for a label at the given index.\n\n Args:\n image_lists: OrderedDict of training images for each label.\n label_name: Label string we want to get an image for.\n index: Int offset of the image we want. This will be moduloed by the\n available number of images for the label, ... |
Please provide a description of the function:def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,
category, module_name):
module_name = (module_name.replace('://', '~') # URL scheme.
.replace('/', '~') # URL and Unix paths.
.replace(':'... | [
"Returns a path to a bottleneck file for a label at the given index.\n\n Args:\n image_lists: OrderedDict of training images for each label.\n label_name: Label string we want to get an image for.\n index: Integer offset of the image we want. This will be moduloed by the\n available number of images fo... |
Please provide a description of the function:def create_module_graph(module_spec):
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 ... | [
"Creates a graph and loads Hub Module into it.\n\n Args:\n module_spec: the hub.ModuleSpec for the image module being used.\n\n Returns:\n graph: the tf.Graph that was created.\n bottleneck_tensor: the bottleneck values output by the module.\n resized_input_tensor: the input images, resized as expecte... |
Please provide a description of the function: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_inp... | [
"Runs inference on an image to extract the 'bottleneck' summary layer.\n\n Args:\n sess: Current active TensorFlow Session.\n image_data: String of raw JPEG data.\n image_data_tensor: Input data layer in the graph.\n decoded_image_tensor: Output of initial image resizing and preprocessing.\n resized... |
Please provide a description of the function: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):
tf.l... | [
"Create a single bottleneck file."
] |
Please provide a description of the function: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, mod... | [
"Retrieves or calculates bottleneck values for an image.\n\n If a cached version of the bottleneck data exists on-disk, return that,\n otherwise calculate the data and save it to disk for future use.\n\n Args:\n sess: The current active TensorFlow Session.\n image_lists: OrderedDict of training images for ... |
Please provide a description of the function: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 = 0
ensure_dir_exists(bottleneck_dir)
... | [
"Ensures all the training, testing, and validation bottlenecks are cached.\n\n Because we're likely to read the same image multiple times (if there are no\n distortions applied during training) it can speed things up a lot if we\n calculate the bottleneck layer values once for each image during\n preprocessing,... |
Please provide a description of the function: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_... | [
"Retrieves bottleneck values for cached images.\n\n If no distortions are being applied, this function can retrieve the cached\n bottleneck values directly from disk for images. It picks a random set of\n images from the specified category.\n\n Args:\n sess: Current TensorFlow Session.\n image_lists: Orde... |
Please provide a description of the function: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(image_lists.keys())
bottlenecks = []
ground_truths = []
for unused_i in ... | [
"Retrieves bottleneck values for training images, after distortions.\n\n If we're training with distortions like crops, scales, or flips, we have to\n recalculate the full model for every image, and so we can't use cached\n bottleneck values. Instead we find random images for the requested category,\n run them ... |
Please provide a description of the function: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_depth = hub.get_num_image_channels(module_spec)
jpeg_data = tf... | [
"Creates the operations to apply the specified distortions.\n\n During training it can help to improve the results if we run the images\n through simple distortions like crops, scales, and flips. These reflect the\n kind of variations we expect in the real world, and so can help train the\n model to cope with n... |
Please provide a description of the function:def variable_summaries(var):
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.scalar('stddev', stddev)
t... | [
"Attach a lot of summaries to a Tensor (for TensorBoard visualization)."
] |
Please provide a description of the function: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_list()
assert batch_size is None, 'We want to work with arbitrary... | [
"Adds a new softmax and fully-connected layer for training and eval.\n\n We need to retrain the top layer to identify our new classes, so this function\n adds the right operations to the graph, along with some variables to hold the\n weights, and then sets up all the gradients for the backward pass.\n\n The set... |
Please provide a description of the function:def add_evaluation_step(result_tensor, ground_truth_tensor):
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.nam... | [
"Inserts the operations we need to evaluate the accuracy of our results.\n\n Args:\n result_tensor: The new final node that produces results.\n ground_truth_tensor: The node we feed ground truth data\n into.\n\n Returns:\n Tuple of (evaluation step, prediction).\n "
] |
Please provide a description of the function: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, test_filenames = (
get_random_cach... | [
"Runs a final evaluation on an eval graph using the test data set.\n\n Args:\n train_session: Session for the train graph with the tensors below.\n module_spec: The hub.ModuleSpec for the image module being used.\n class_count: Number of classes\n image_lists: OrderedDict of training images for each la... |
Please provide a description of the function: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(module_spec))
eval_sess = tf.Session(grap... | [
"Builds an restored eval session without train operations for exporting.\n\n Args:\n module_spec: The hub.ModuleSpec for the image module being used.\n class_count: Number of classes\n\n Returns:\n Eval session containing the restored eval graph.\n The bottleneck input, ground truth, eval step, and pr... |
Please provide a description of the function:def save_graph_to_file(graph_file_name, module_spec, class_count):
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_... | [
"Saves an graph to file, creating a valid quantized one if necessary."
] |
Please provide a description of the function: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 = tf.placeholder(tf.string, name='DecodeJPGInput')
decoded_image = tf.image.decode_jpeg(jpeg_da... | [
"Adds operations that perform JPEG decoding and resizing to the graph..\n\n Args:\n module_spec: The hub.ModuleSpec for the image module being used.\n\n Returns:\n Tensors for the node to feed JPEG data into, and the output of the\n preprocessing steps.\n "
] |
Please provide a description of the function: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, class_count)
with sess.graph.as_default() as graph:
tf.saved_model.simple_save(
sess,
... | [
"Exports model for serving.\n\n Args:\n module_spec: The hub.ModuleSpec for the image module being used.\n class_count: The number of classes.\n saved_model_dir: Directory in which to save exported model and variables.\n "
] |
Please provide a description of the function:def logging_level_verbosity(logging_verbosity):
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... | [
"Converts logging_level into TensorFlow logging verbosity value\n\n Args:\n logging_level: String value representing logging level: 'DEBUG', 'INFO',\n 'WARN', 'ERROR', 'FATAL'\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def get_expected_image_size(module_or_spec, signature=None, input_name=None):
# First see if an attached ImageModuleInfo provides this information.
image_module_info = get_image_module_info(module_or_spec)
if image_module_info:
size = image_module_info.default_i... | [
"Returns expected [height, width] dimensions of an image input.\n\n Args:\n module_or_spec: a Module or ModuleSpec that accepts image inputs.\n signature: a string with the key of the signature in question.\n If None, the default signature is used.\n input_name: a string with the input name for image... |
Please provide a description of the function: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_dict(signature)
try:
shape = input_info_dict[input_name].get_shape()
except KeyError:
... | [
"Returns expected num_channels dimensions of an image input.\n\n This is for advanced users only who expect to handle modules with\n image inputs that might not have the 3 usual RGB channels.\n\n Args:\n module_or_spec: a Module or ModuleSpec that accepts image inputs.\n signature: a string with the key of... |
Please provide a description of the function:def _parse_tensor_info_proto(tensor_info):
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=Fal... | [
"Returns a ParsedTensorInfo instance from a TensorInfo proto."
] |
Please provide a description of the function:def _is_sparse(x):
return (
isinstance(x, (tf.SparseTensor, tf_v1.SparseTensorValue)) or
(hasattr(x, "is_sparse") and x.is_sparse)) | [
"Returns whether x is a SparseTensor or a parsed sparse tensor info."
] |
Please provide a description of the function: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:
raise TypeError("%s: %s" % (error_prefix, e))
if _is_sparse(tensor) != _is_sparse(target):
... | [
"Converts `value` into a tensor that can be feed into `tensor_info`.\n\n Args:\n value: A value to convert into Tensor or SparseTensor.\n target: An object returned by `parse_tensor_info_map`.\n error_prefix: A string to prefix on raised TypeErrors.\n\n Raises:\n TypeError: If it fails to convert.\n\n... |
Please provide a description of the function:def convert_dict_to_compatible_tensor(values, targets):
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 | [
"Converts dict `values` in tensors that are compatible with `targets`.\n\n Args:\n values: A dict to objects to convert with same keys as `targets`.\n targets: A dict returned by `parse_tensor_info_map`.\n\n Returns:\n A map with the same keys as `values` but values converted into\n Tensor/SparseTenso... |
Please provide a description of the function:def build_input_map(protomap, inputs):
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("en... | [
"Builds a map to feed tensors in `protomap` using `inputs`.\n\n Args:\n protomap: A proto map<string,TensorInfo>.\n inputs: A map with same keys as `protomap` of Tensors and SparseTensors.\n\n Returns:\n A map from nodes refered by TensorInfo protos to corresponding input\n tensors.\n\n Raises:\n ... |
Please provide a description of the function: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":
return get_tensor_by_name(tensor_info.name)
elif encoding == "coo_sparse":
ret... | [
"Builds a map of tensors from `protomap` using `get_tensor_by_name`.\n\n Args:\n protomap: A proto map<string,TensorInfo>.\n get_tensor_by_name: A lambda that receives a tensor name and returns a\n Tensor instance.\n\n Returns:\n A map from string to Tensor or SparseTensor instances built from `prot... |
Please provide a description of the function:def tensor_info_proto_maps_match(map_a, map_b):
iter_a = sorted(parse_tensor_info_map(map_a).items())
iter_b = sorted(parse_tensor_info_map(map_b).items())
if len(iter_a) != len(iter_b):
return False # Mismatch count.
for info_a, info_b in zip(iter_a, iter_b)... | [
"Whether two signature inputs/outputs match in dtype, shape and sparsity.\n\n Args:\n map_a: A proto map<string,TensorInfo>.\n map_b: A proto map<string,TensorInfo>.\n\n Returns:\n A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and\n sparsity.\n "
] |
Please provide a description of the function:def parse_line(line):
columns = line.split()
token = columns.pop(0)
values = [float(column) for column in columns]
return token, values | [
"Parses a line of a text embedding file.\n\n Args:\n line: (str) One line of the text embedding file.\n\n Returns:\n A token string and its embedding vector in floats.\n "
] |
Please provide a description of the function:def load(file_path, parse_line_fn):
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 != ... | [
"Loads a text embedding into memory as a numpy matrix.\n\n Args:\n file_path: Path to the text embedding file.\n parse_line_fn: callback function to parse each file line.\n\n Returns:\n A tuple of (list of vocabulary tokens, numpy matrix of embedding vectors).\n\n Raises:\n ValueError: if the data in... |
Please provide a description of the function:def make_module_spec(vocabulary_file, vocab_size, embeddings_dim,
num_oov_buckets, preprocess_text):
def module_fn():
tokens = tf.placeholder(shape=[None], dtype=tf.string, name="tokens")
embeddings_var = tf.get_variable(
init... | [
"Makes a module spec to simply perform token to embedding lookups.\n\n Input of this module is a 1-D list of string tokens. For T tokens input and\n an M dimensional embedding table, the lookup result is a [T, M] shaped Tensor.\n\n Args:\n vocabulary_file: Text file where each line is a key in the vocabulary.... |
Please provide a description of the function:def export(export_path, vocabulary, embeddings, num_oov_buckets,
preprocess_text):
# Write temporary vocab file for module construction.
tmpdir = tempfile.mkdtemp()
vocabulary_file = os.path.join(tmpdir, "tokens.txt")
with tf.gfile.GFile(vocabulary_file... | [
"Exports a TF-Hub module that performs embedding lookups.\n\n Args:\n export_path: Location to export the module.\n vocabulary: List of the N tokens in the vocabulary.\n embeddings: Numpy array of shape [N+K,M] the first N rows are the\n M dimensional embeddings for the respective tokens and the next... |
Please provide a description of the function:def maybe_append_oov_vectors(embeddings, num_oov_buckets):
num_embeddings = np.shape(embeddings)[0]
embedding_dim = np.shape(embeddings)[1]
embeddings.resize(
[num_embeddings + num_oov_buckets, embedding_dim], refcheck=False) | [
"Adds zero vectors for oov buckets if num_oov_buckets > 0.\n\n Since we are assigning zero vectors, adding more that one oov bucket is only\n meaningful if we perform fine-tuning.\n\n Args:\n embeddings: Embeddings to extend.\n num_oov_buckets: Number of OOV buckets in the extended embedding.\n "
] |
Please provide a description of the function:def create_module_spec_from_saved_model(saved_model_path,
drop_collections=None):
saved_model_handler = saved_model_lib.load(saved_model_path)
checkpoint_filename = saved_model_lib.get_variables_path(saved_model_path)
drop_co... | [
"Experimental: Create a ModuleSpec out of a SavedModel.\n\n Define a ModuleSpec from a SavedModel. Note that this is not guaranteed to\n work in all cases and it assumes the SavedModel has followed some conventions:\n\n - The serialized SaverDef can be ignored and instead can be reconstructed.\n - The init op a... |
Please provide a description of the function: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(
"There is already a module registered to be exported as %r"
% export_n... | [
"Register a Module to be exported under `export_name`.\n\n\n This function registers `module` to be exported by `LatestModuleExporter`\n under a subdirectory named `export_name`.\n\n Note that `export_name` must be unique for each module exported from the\n current graph. It only controls the export subdirector... |
Please provide a description of the function:def _make_estimator_serving_session(estimator, serving_input_fn,
checkpoint_path):
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(estimato... | [
"Returns a session constructed using `estimator` and `serving_input_fn`.\n\n The Estimator API does not provide an API to construct a graph and session,\n making it necessary for this function to replicate how an estimator builds\n a graph.\n\n This code is based on `Estimator.export_savedmodel` (another functi... |
Please provide a description of the function: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:
tags_and_args = [(set(), {})]
report_tags = False
saved_model_handler = saved_model_... | [
"Creates a ModuleSpec from a function that builds the module's graph.\n\n The `module_fn` is called on a new graph (not the current one) to build the\n graph of the module and define its signatures via `hub.add_signature()`.\n Example:\n\n ```python\n # Define a text embedding module.\n def my_text_module_fn(... |
Please provide a description of the function:def add_signature(name=None, inputs=None, outputs=None):
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):... | [
"Adds a signature to the module definition.\n\n NOTE: This must be called within a `module_fn` that is defining a Module.\n\n Args:\n name: Signature name as a string. If omitted, it is interpreted as 'default'\n and is the signature used when `Module.__call__` `signature` is not\n specified.\n in... |
Please provide a description of the function: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_model_lib.attach_bytes(key, message.SerializeToString()) | [
"Adds an attached message to the module definition.\n\n NOTE: This must be called within a `module_fn` that is defining a Module.\n\n See ModuleSpec.get_attached_message() for an introduction to attached messages\n and the API for module consumers.\n\n To define a new type of attached message:\n\n * Select a... |
Please provide a description of the function: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 not op.input_arg
]) | [
"Returns set of registered stateful ops that do not expect inputs.\n\n This list is used to identify the ops to be included in the state-graph and\n that are subsequently fed into the apply-graphs.\n\n Returns:\n A set of strings.\n "
] |
Please provide a description of the function: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 state_ops:
tensor_name = node.name + ":0"
tensor = get_tensor_by_name(tensor_name... | [
"Returns a map from tensor names to tensors that hold the state."
] |
Please provide a description of the function: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"
# Verify that the node is a state op and that its due to be rewired
# in the feedmap.
if node.op in sta... | [
"Replaces state ops with non state Placeholder ops for the apply graph."
] |
Please provide a description of the function:def _split_tensor_name(tensor_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_name)
return result.group(1), int(resul... | [
"Given a tensor name as node_name:output_number, returns both parts."
] |
Please provide a description of the function:def _extract_variable_parts(variable_key, variable):
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.endsw... | [
"Matches a variable to individual parts.\n\n Args:\n variable_key: String identifier of the variable in the module scope.\n variable: Variable tensor.\n\n Returns:\n partitioned: Whether the variable is partitioned.\n name: Name of the variable up to the partitioning.\n offset: Offset of the variab... |
Please provide a description of the function: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_variable_parts(var_key, var_tensor)
if not match:
# This is a standard variable, so we can ... | [
"Builds a proper variable map if it contains PartitionedVariables.\n\n Args:\n var_node_map: A map to tf.Variables. PartitionedVariables show up in this\n map as N entries with keys \"<var_name>/part_n\".\n\n Returns:\n A map to tf.Variables or to list of tf.Variables for each\n PartitionedVariables... |
Please provide a description of the function: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("Tags %r used repeatedly" % tags)
frozen_tags_seen.add(frozen_tags) | [
"Checks that tag list contains each set of tags only once."
] |
Please provide a description of the function: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())
unsupported = used_collection_keys - supported
if unsupported:
raise Va... | [
"Checks that SavedModelHandler only uses supported collections."
] |
Please provide a description of the function: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_api.TF_GetAllOpList()
cpp_op_list = op_def_pb2.OpList()
cpp_op_list.ParseFromString(c_api.TF_GetBuffer... | [
"Register graph ops absent in op_def_registry, if present in c++ registry.\n\n Args:\n graph_ops: set with graph op names to register.\n\n Raises:\n RuntimeError: if `graph_ops` contains ops that are not in either python or\n c++ registry.\n "
] |
Please provide a description of the function: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.\n\n This function is meant to be called after importing a GraphDef, in order\n to rewrite colocate_with constrains analogous to how inputs to ops\n are rewritten by input_map during import. It also updates devices accordingly.\n\n The nodes in th... |
Please provide a description of the function:def _build_colocation_attr_map(input_map, absolute_import_scope):
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_te... | [
"Returns a dict mapping from pre-import to post-import colocation attrs.\n\n Args:\n input_map: as for fix_colocation_after_import.\n absolute_import_scope: as for fix_colocation_after_import.\n\n Returns:\n A dict that maps bytes `\"loc:@\" + absolute_import_scope + \"/foo\"`\n to _ConsistentValues s... |
Please provide a description of the function: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" attr that store colocation constraints.
# NOTE: The colocation_group loc:@X of ... | [
"Rewrites colocation constraints in the current default graph.\n\n Nodes in `absolute_import_scope` get their \"_class\" attr lists rewritten\n according to `colocation_attr_map`: each entry that matches a key gets\n replaced by the associated values (with deduplication). The node's device\n is updated accordin... |
Please provide a description of the function: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.get_operations()
if op.type in state_op_types}
for op in state_op_map.values()... | [
"Returns error message for colocation of state ops, or None if ok."
] |
Please provide a description of the function:def find_signature_input_colocation_error(signature_name, inputs):
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 ... | [
"Returns error message for colocation of signature inputs, or None if ok."
] |
Please provide a description of the function: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 isinstance(tensor, tf.SparseTensor):
dense_inputs.extend(("%s.%s" % (name, attr)... | [
"Returns error message for module inputs from ops with multiple outputs."
] |
Please provide a description of the function:def _export(self, path, variables_saver):
self._saved_model_handler.export(path, variables_saver=variables_saver)
module_def_proto = module_def_pb2.ModuleDef()
module_def_proto.format = module_def_pb2.ModuleDef.FORMAT_V3
module_def_filename = get_module... | [
"Internal.\n\n Args:\n path: string where to export the module to.\n variables_saver: an unary-function that writes the module variables\n checkpoint on the given path.\n "
] |
Please provide a description of the function:def _create_state_graph(self, name):
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... | [
"Creates the graph nodes that hold the state of the Module.\n\n Args:\n name: name scope to create the state graph in.\n\n Returns:\n A tuple consisting of:\n variables_tensor_map: a map from tensor names in the original graph def\n to the created Variables objects.\n state_ma... |
Please provide a description of the function:def create_apply_graph(self, signature, input_tensors, name):
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()
infee... | [
"See `ModuleImpl.create_apply_graph`."
] |
Please provide a description of the function:def export(self, path, session):
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_save... | [
"See `Module.export`."
] |
Please provide a description of the function:def Set(self, value, context=None):
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:
sel... | [
"Receives a value for the object and some context on its source."
] |
Please provide a description of the function:def GetConsistentValueOrRaise(self, error_format, context=None):
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 | [
"Gets consistent value or raises ValueError with formatted contexts."
] |
Please provide a description of the function:def _module_dir(handle):
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 directory where to cache the module."
] |
Please provide a description of the function:def get_variables_path(export_dir):
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)) | [
"Returns the path for storing variables checkpoints."
] |
Please provide a description of the function:def _get_node_name_from_tensor(tensor_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_name)
return result.group(1) | [
"tensor_name must have format node_name:output_number. Returns node_name."
] |
Please provide a description of the function: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.saved_model.utils.build_tensor_info(tensor)
for input_name, tensor in i... | [
"Adds a signature to current graph.\n\n Args:\n key: Signature key as a string.\n inputs: Signature inputs as a map from string to Tensor or SparseTensor.\n outputs: Signature outputs as a map from string to Tensor or SparseTensor.\n (Recall that a Variable is not a Tensor, but Variable.value() is.)\... |
Please provide a description of the function: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(...)"
"at least once in the module_fn.")
for k... | [
"Exports signatures from current graph into a MetaGraphDef."
] |
Please provide a description of the function: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.\n\n Args:\n key: A string with the unique key of the attachment.\n the_bytes: A bytes object with the serialized attachment.\n "
] |
Please provide a description of the function: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 = collections.OrderedDict( # Avoid indeterminism.
(attachmen... | [
"Exports ModuleAttachments from the current tf.Graph into `meta_graph`."
] |
Please provide a description of the function: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[ATTACHMENT_COLLECTION_SAVED]
if collection_def.WhichOneof("kind") != "bytes_list":
... | [
"Returns the dict of ModuleAttachments stored in `meta_graph`.\n\n Args:\n meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy()\n from some graph.\n\n Returns:\n A dict, containing the `(key, bytes)` items passed to `attach_bytes()`\n when the graph had been built.\n\n Raises:... |
Please provide a description of the function: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"].type) != tf.string:
raise TypeError("Asset node must be of dtype string.")
if len(node_def.attr["val... | [
"Raises TypeError if `node_def` does not match the expectations."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.