text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, path_info, checksum): """Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): chec...
assert path_info["scheme"] == "local" assert checksum is not None path = path_info["path"] assert os.path.exists(path) actual_mtime, actual_size = get_mtime_and_size(path) actual_inode = get_inode(path) existing_record = self.get_state_record_for_inode(actual_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, path_info): """Gets the checksum for the specified path info. Checksum will be retrieved from the state database if available. Args: path_info (dic...
assert path_info["scheme"] == "local" path = path_info["path"] if not os.path.exists(path): return None actual_mtime, actual_size = get_mtime_and_size(path) actual_inode = get_inode(path) existing_record = self.get_state_record_for_inode(actual_inode) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_link(self, path_info): """Adds the specified path to the list of links created by dvc. This list is later used on `dvc checkout` to cleanup old links. A...
assert path_info["scheme"] == "local" path = path_info["path"] if not os.path.exists(path): return mtime, _ = get_mtime_and_size(path) inode = get_inode(path) relpath = os.path.relpath(path, self.root_dir) cmd = ( "REPLACE INTO {}(path,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_unused_links(self, used): """Removes all saved links except the ones that are used. Args: used (list): list of used links that should not be removed....
unused = [] self._execute("SELECT * FROM {}".format(self.LINK_STATE_TABLE)) for row in self.cursor: relpath, inode, mtime = row inode = self._from_sqlite(inode) path = os.path.join(self.root_dir, relpath) if path in used: continu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock(self): """Acquire lock for dvc repo."""
try: self._do_lock() return except LockError: time.sleep(self.TIMEOUT) self._do_lock()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_scrollregion(self, event=None): """ Set the scroll region on the canvas"""
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _show_selection(self, text, bbox): """Configure canvas for a new selection."""
x, y, width, height = bbox textw = self._font.measure(text) canvas = self._canvas canvas.configure(width=width, height=height) canvas.coords(canvas.text, width - textw, height / 2 - 1) canvas.itemconfigure(canvas.text, text=text) canvas.place(in_=self._calendar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prev_month(self): """Updated calendar to show the previous month."""
self._canvas.place_forget() self._date = self._date - self.timedelta(days=1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_month(self): """Update calendar to show the next month."""
self._canvas.place_forget() year, month = self._date.year, self._date.month self._date = self._date + self.timedelta( days=calendar.monthrange(year, month)[1] + 1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selection(self): """Return a datetime representing the current selected date."""
if not self._selection: return None year, month = self._date.year, self._date.month return self.datetime(year, month, int(self._selection[0]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AddRow(self, *args): ''' Parms are a variable number of Elements ''' NumRows = len(self.Rows) # number of existing rows is our row number CurrentRowNumber = NumRows # this row's number CurrentRow = [] # start with a blank row and build up # ------------------------- Add t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setColor(self, color): '''Sets Card's color and escape code.''' if color == 'blue': self.color = 'blue' self.colorCode = self.colors['blue'] self.colorCodeDark = self.colors['dblue'] elif color == 'red': self.color = 'red' self.colo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_img_data(f, maxsize = (1200, 850), first = False): """Generate image data using PIL """
img = Image.open(f) img.thumbnail(maxsize) if first: # tkinter is inactive the first time bio = io.BytesIO() img.save(bio, format = "PNG") del img return bio.getvalue() return ImageTk.PhotoImage(img)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, packet_size=PACKET_SIZE, path_finder=False): """ Same as verbose_ping, but the results are retu...
myStats = MyStats() # Reset the stats mySeqNumber = 0 # Starting value try: destIP = socket.gethostbyname(hostname) except socket.gaierror as e: return 0,0,0,0 myStats.thisIP = destIP # This will send packet that we dont care about 0.5 seconds before it starts # acrutally...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_page(pno, zoom = False, max_size = None, first = False): """Return a PNG image for a document page number. """
dlist = dlist_tab[pno] # get display list of page number if not dlist: # create if not yet there dlist_tab[pno] = doc[pno].getDisplayList() dlist = dlist_tab[pno] r = dlist.rect # the page rectangle clip = r # ensure image fits screen: # exploit, but do no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play(self): """ Play Conway's Game of Life. """
# Write the initial configuration to file. self.t = 1 # Current time level while self.t <= self.T: # Evolve! # print( "At time level %d" % t) # Loop over each cell of the grid and apply Conway's rules. for i in range(self.N): for j in ran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']): """ Returns a human readable string reprentation of bytes"""
return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_view_on_selected(self, widget, selected_item_key): """ The selection event of the listView, returns a key of the clicked event. You can retrieve the ite...
self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_one_ping(mySocket, myID, timeout): """ Receive the ping from the socket. Timeout = in ms """
timeLeft = timeout/1000 while True: # Loop while waiting for packet or timeout startedSelect = default_timer() whatReady = select.select([mySocket], [], [], timeLeft) howLongInSelect = (default_timer() - startedSelect) if whatReady[0] == []: # Timeout return None, 0...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(self, path, _sentinel=None, # pylint: disable=invalid-name checkpoint_path=None, name_transform_fn=None): """Exports a ModuleSpec with weights taken f...
from tensorflow_hub.module import export_module_spec # pylint: disable=g-import-not-at-top if not checkpoint_path: raise ValueError("Missing mandatory `checkpoint_path` parameter") name_transform_fn = name_transform_fn or (lambda x: x) export_module_spec(self, path, checkpoint_path, name_transfo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
attached_bytes = self._get_attached_bytes(key, tags) if attached_bytes is None: if required: raise KeyError("No attached message for key '%s' in graph version %s " "of Hub Module" % (key, sorted(tags or []))) else: return None message = message_type() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_image_lists(image_dir, testing_percentage, validation_percentage): """Builds a list of training images from the file system. Analyzes the sub folders ...
if not tf.gfile.Exists(image_dir): tf.logging.error("Image directory '" + image_dir + "' not found.") return None result = collections.OrderedDict() sub_dirs = sorted(x[0] for x in tf.gfile.Walk(image_dir)) # The root directory comes first, so skip it. is_root_dir = True for sub_dir in sub_dirs: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Ordered...
if label_name not in image_lists: tf.logging.fatal('Label does not exist %s.', label_name) label_lists = image_lists[label_name] if category not in label_lists: tf.logging.fatal('Category does not exist %s.', category) category_list = label_lists[category] if not category_list: tf.logging.fatal('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 i...
module_name = (module_name.replace('://', '~') # URL scheme. .replace('/', '~') # URL and Unix paths. .replace(':', '~').replace('\\', '~')) # Windows paths. return get_image_path(image_lists, label_name, index, bottleneck_dir, category) + '_' + module_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Ret...
height, width = hub.get_expected_image_size(module_spec) with tf.Graph().as_default() as graph: resized_input_tensor = tf.placeholder(tf.float32, [None, height, width, 3]) m = hub.Module(module_spec) bottleneck_tensor = m(resized_input_tensor) wants_quantization = any(node.op in FAKE_QUANT_OPS ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# First decode the JPEG image, resize it, and rescale the pixel values. resized_input_values = sess.run(decoded_image_tensor, {image_data_tensor: image_data}) # Then run it through the recognition network. bottleneck_values = sess.run(bottleneck_tensor, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tenso...
tf.logging.debug('Creating bottleneck at ' + bottleneck_path) image_path = get_image_path(image_lists, label_name, index, image_dir, category) if not tf.gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) image_data = tf.gfile.GFile(image_path, 'rb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir, category, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tens...
label_lists = image_lists[label_name] sub_dir = label_lists['dir'] sub_dir_path = os.path.join(bottleneck_dir, sub_dir) ensure_dir_exists(sub_dir_path) bottleneck_path = get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category, module_name) if not...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) for label_name, label_lists in image_lists.items(): for category in ['training', 'testing', 'validation']: category_list = label_lists[category] for index, unused_base_name in enumerate(category_list): get_or_create_bottleneck( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_random_cached_bottlenecks(sess, image_lists, how_many, category, bottleneck_dir, image_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, ...
class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] filenames = [] if how_many >= 0: # Retrieve a random sample of bottlenecks. for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_random_distorted_bottlenecks( sess, image_lists, how_many, category, image_dir, input_jpeg_tensor, distorted_image, resized_input_tensor, bottleneck_tenso...
class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] for unused_i in range(how_many): label_index = random.randrange(class_count) label_name = list(image_lists.keys())[label_index] image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1) image_path = get_image_path(imag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_input_distortions(flip_left_right, random_crop, random_scale, random_brightness, module_spec): """Creates the operations to apply the specified distortio...
input_height, input_width = hub.get_expected_image_size(module_spec) input_depth = hub.get_num_image_channels(module_spec) jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) # Convert from full range of uint8 to range [0,1] of f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 tr...
batch_size, bottleneck_tensor_size = bottleneck_tensor.get_shape().as_list() assert batch_size is None, 'We want to work with arbitrary batch size.' with tf.name_scope('input'): bottleneck_input = tf.placeholder_with_default( bottleneck_tensor, shape=[batch_size, bottleneck_tensor_size], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): prediction = tf.argmax(result_tensor, 1) correct_prediction = tf.equal(prediction, ground_truth_tensor) with tf.name_scope('accuracy'): evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.su...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_final_eval(train_session, module_spec, class_count, image_lists, jpeg_data_tensor, decoded_image_tensor, resized_image_tensor, bottleneck_tensor): """Run...
test_bottlenecks, test_ground_truth, test_filenames = ( get_random_cached_bottlenecks(train_session, image_lists, FLAGS.test_batch_size, 'testing', FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_eval_session(module_spec, class_count): """Builds an restored eval session without train operations for exporting. Args: module_spec: The hub.ModuleSpe...
# If quantized, we need to create the correct eval graph for exporting. eval_graph, bottleneck_tensor, resized_input_tensor, wants_quantization = ( create_module_graph(module_spec)) eval_sess = tf.Session(graph=eval_graph) with eval_graph.as_default(): # Add the new layer for exporting. (_, _, b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_graph_to_file(graph_file_name, module_spec, class_count): """Saves an graph to file, creating a valid quantized one if necessary."""
sess, _, _, _, _, _ = build_eval_session(module_spec, class_count) graph = sess.graph output_graph_def = tf.graph_util.convert_variables_to_constants( sess, graph.as_graph_def(), [FLAGS.final_tensor_name]) with tf.gfile.GFile(graph_file_name, 'wb') as f: f.write(output_graph_def.SerializeToString()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
input_height, input_width = hub.get_expected_image_size(module_spec) input_depth = hub.get_num_image_channels(module_spec) jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput') decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth) # Convert from full range of uint8 to range [0,1] of fl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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....
# The SavedModel should hold the eval graph. sess, in_image, _, _, _, _ = build_eval_session(module_spec, class_count) with sess.graph.as_default() as graph: tf.saved_model.simple_save( sess, saved_model_dir, inputs={'image': in_image}, outputs={'prediction': graph.get_tensor_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logging_level_verbosity(logging_verbosity): """Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing ...
name_to_level = { 'FATAL': tf.logging.FATAL, 'ERROR': tf.logging.ERROR, 'WARN': tf.logging.WARN, 'INFO': tf.logging.INFO, 'DEBUG': tf.logging.DEBUG } try: return name_to_level[logging_verbosity] except Exception as e: raise RuntimeError('Not supported logs verbosity (%s). Use one o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if input_name is None: input_name = "images" input_info_dict = module_or_spec.get_input_info_dict(signature) try: shape = input_info_dict[input_name].get_shape() except KeyError: raise ValueError("Module is missing input '%s' in signature '%s'." % (input_name, signature or "def...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_tensor_info_proto(tensor_info): """Returns a ParsedTensorInfo instance from a TensorInfo proto."""
encoding = tensor_info.WhichOneof("encoding") dtype = tf.DType(tensor_info.dtype) shape = tf.TensorShape(tensor_info.tensor_shape) if encoding == "name": return ParsedTensorInfo(dtype=dtype, shape=shape, is_sparse=False) elif encoding == "coo_sparse": return ParsedTensorInfo(dtype=dtype, shape=shape,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 co...
try: tensor = tf_v1.convert_to_tensor_or_indexed_slices(value, target.dtype) except TypeError as e: raise TypeError("%s: %s" % (error_prefix, e)) if _is_sparse(tensor) != _is_sparse(target): if _is_sparse(tensor): raise TypeError("%s: Is sparse. Expected dense." % error_prefix) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_dict_to_compatible_tensor(values, targets): """Converts dict `values` in tensors that are compatible with `targets`. Args: values: A dict to objects ...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ma...
if set(protomap.keys()) != set(inputs.keys()): raise ValueError("build_input_map: keys do not match.") input_map = {} for key, tensor_info in protomap.items(): arg = inputs[key] encoding = tensor_info.WhichOneof("encoding") if encoding == "name": input_map[tensor_info.name] = arg elif e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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,Ten...
def get_output_from_tensor_info(tensor_info): encoding = tensor_info.WhichOneof("encoding") if encoding == "name": return get_tensor_by_name(tensor_info.name) elif encoding == "coo_sparse": return tf.SparseTensor( get_tensor_by_name(tensor_info.coo_sparse.indices_tensor_name), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
columns = line.split() token = columns.pop(0) values = [float(column) for column in columns] return token, values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: cal...
vocabulary = [] embeddings = [] embeddings_dim = None for line in tf.gfile.GFile(file_path): token, embedding = parse_line_fn(line) if not embeddings_dim: embeddings_dim = len(embedding) elif embeddings_dim != len(embedding): raise ValueError( "Inconsistent embedding dimension...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
def module_fn(): """Spec function for a token embedding module.""" tokens = tf.placeholder(shape=[None], dtype=tf.string, name="tokens") embeddings_var = tf.get_variable( initializer=tf.zeros([vocab_size + num_oov_buckets, embeddings_dim]), name=EMBEDDINGS_VAR_NAME, dtype=tf.flo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(export_path, vocabulary, embeddings, num_oov_buckets, preprocess_text): """Exports a TF-Hub module that performs embedding lookups. Args: export_path:...
# Write temporary vocab file for module construction. tmpdir = tempfile.mkdtemp() vocabulary_file = os.path.join(tmpdir, "tokens.txt") with tf.gfile.GFile(vocabulary_file, "w") as f: f.write("\n".join(vocabulary)) vocab_size = len(vocabulary) embeddings_dim = embeddings.shape[1] spec = make_module_sp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, addi...
num_embeddings = np.shape(embeddings)[0] embedding_dim = np.shape(embeddings)[1] embeddings.resize( [num_embeddings + num_oov_buckets, embedding_dim], refcheck=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
for used_name, _ in tf_v1.get_collection(_EXPORT_MODULES_COLLECTION): if used_name == export_name: raise ValueError( "There is already a module registered to be exported as %r" % export_name) tf_v1.add_to_collection(_EXPORT_MODULES_COLLECTION, (export_name, module))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_estimator_serving_session(estimator, serving_input_fn, checkpoint_path): """Returns a session constructed using `estimator` and `serving_input_fn`. The...
with tf.Graph().as_default() as g: mode = tf_v1.estimator.ModeKeys.PREDICT tf_v1.train.create_global_step(g) tf_v1.set_random_seed(estimator.config.tf_random_seed) serving_input_receiver = serving_input_fn() estimator_spec = estimator.model_fn( features=serving_input_receiver.features, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if not drop_collections: drop_collections = [] report_tags = True if not tags_and_args: tags_and_args = [(set(), {})] report_tags = False saved_model_handler = saved_model_lib.SavedModelHandler() for tags, args in tags_and_args: with tf.Graph().as_default() as graph: with tf_v1.variab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 def...
if not name: name = "default" if inputs is None: inputs = {} if outputs is None: outputs = {} if not isinstance(inputs, dict): inputs = {"default": inputs} if not isinstance(outputs, dict): outputs = {"default": outputs} message = find_signature_inputs_from_multivalued_ops(inputs) if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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....
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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
return set([ name for name, op in op_def_registry.get_registered_ops().items() if op.is_stateful and not op.input_arg ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_state_map(meta_graph, state_ops, unsupported_state_ops, get_tensor_by_name): """Returns a map from tensor names to tensors that hold the state."""
state_map = {} for node in meta_graph.graph_def.node: if node.op in state_ops: tensor_name = node.name + ":0" tensor = get_tensor_by_name(tensor_name) num_outputs = len(tensor.op.outputs) if num_outputs != 1: raise ValueError("Stateful op %s has %d outputs, expected 1" % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_apply_state(meta_graph, state_ops, feed_map): """Replaces state ops with non state Placeholder ops for the apply graph."""
for node in meta_graph.graph_def.node: keys_to_purge = [] tensor_name = node.name + ":0" # Verify that the node is a state op and that its due to be rewired # in the feedmap. if node.op in state_ops and tensor_name in feed_map: node.op = "Placeholder" for key in node.attr: # O...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_variable_parts(variable_key, variable): """Matches a variable to individual parts. Args: variable_key: String identifier of the variable in the modu...
name, offset, partitioned = None, None, False # pylint: disable=protected-access if variable._save_slice_info: name = variable_key[:variable_key.rfind("/")] if not variable._save_slice_info.full_name.endswith(name): raise RuntimeError("Unexpected handling of partitioned variable.") offset = var...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.Variable...
offset_variables_map = {} for var_key, var_tensor in var_node_map.items(): match, var_name, offset = _extract_variable_parts(var_key, var_tensor) if not match: # This is a standard variable, so we can safely add it to the output. if var_key in offset_variables_map: raise RuntimeError( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_collections_are_supported(saved_model_handler, supported): """Checks that SavedModelHandler only uses supported collections."""
for meta_graph in saved_model_handler.meta_graphs: used_collection_keys = set(meta_graph.collection_def.keys()) unsupported = used_collection_keys - supported if unsupported: raise ValueError("Unsupported collections in graph: %s\n" "Use hub.create_module_spec(..., drop_colle...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 r...
missing_ops = graph_ops - set(op_def_registry.get_registered_ops().keys()) if not missing_ops: return p_buffer = c_api.TF_GetAllOpList() cpp_op_list = op_def_pb2.OpList() cpp_op_list.ParseFromString(c_api.TF_GetBuffer(p_buffer)) cpp_registry_ops = {op.name: op for op in cpp_op_list.op} missing_op_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_colocation_after_import(input_map, absolute_import_scope): """Fixes colocation attributes after import according to input_map. This function is meant to ...
attr_map = _build_colocation_attr_map(input_map, absolute_import_scope) _apply_colocation_attr_map(attr_map, absolute_import_scope)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
colocation_attr_map = collections.defaultdict(_ConsistentValue) used_outputs_of_imported_ops = collections.defaultdict(set) # Collect mappings from the input_map. for imported_tensor_name, mapped_tensor in input_map.items(): imported_tensor_name = absolute_import_scope + "/" + imported_tensor_name impo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_colocation_attr_map(colocation_attr_map, absolute_import_scope): """Rewrites colocation constraints in the current default graph. Nodes in `absolute_i...
graph = tf_v1.get_default_graph() for op in graph.get_operations(): # Rewrite the values of the "_class" attr that store colocation constraints. # NOTE: The colocation_group loc:@X of a node with itself is not stored # explicitly as an attr, so rewrite errors for loc:@X are not triggered # by the m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_state_op_colocation_error(graph, reported_tags=None): """Returns error message for colocation of state ops, or None if ok."""
state_op_types = list_registered_stateful_ops_without_inputs() state_op_map = {op.name: op for op in graph.get_operations() if op.type in state_op_types} for op in state_op_map.values(): for colocation_group in op.colocation_groups(): if not (colocation_group.startswith(tf.compat.as_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_signature_input_colocation_error(signature_name, inputs): """Returns error message for colocation of signature inputs, or None if ok."""
for input_name, tensor in inputs.items(): expected_colocation_groups = [tf.compat.as_bytes("loc:@" + tensor.op.name)] if tensor.op.colocation_groups() != expected_colocation_groups: return ( "A tensor x used as input in a signature must not be subject to a " "tf.colocate_with(y) con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_signature_inputs_from_multivalued_ops(inputs): """Returns error message for module inputs from ops with multiple outputs."""
dense_inputs = [] # List of (str, Tensor), with SparseTensors decomposed. for name, tensor in sorted(inputs.items()): if isinstance(tensor, tf.SparseTensor): dense_inputs.extend(("%s.%s" % (name, attr), getattr(tensor, attr)) for attr in ("indices", "values", "dense_shape")) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: ...
import_collections = [ tf_v1.GraphKeys.GLOBAL_VARIABLES, tf_v1.GraphKeys.MODEL_VARIABLES, tf_v1.GraphKeys.TABLE_INITIALIZERS, tf_v1.GraphKeys.ASSET_FILEPATHS, # Typically used to initialize tables. tf_v1.GraphKeys.COND_CONTEXT, tf_v1.GraphKeys.WHILE_CONTEXT, ] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_apply_graph(self, signature, input_tensors, name): """See `ModuleImpl.create_apply_graph`."""
signature_def = self._meta_graph.signature_def.get(signature) meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.CopyFrom(self._meta_graph) apply_graph = tf_v1.get_default_graph() infeed_map = tensor_info.build_input_map(signature_def.inputs, input_te...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Set(self, value, context=None): """Receives a value for the object and some context on its source."""
if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.value != value: self.has_error = True self._context["new_value"] = value self._context.updat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetConsistentValueOrRaise(self, error_format, context=None): """Gets consistent value or raises ValueError with formatted contexts."""
if self.has_error: full_context = dict(self._context) if context: full_context.update(context) raise ValueError(error_format.format(**full_context)) return self.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 strin...
_check_dict_maps_to_tensors_or_sparse_tensors(inputs) _check_dict_maps_to_tensors_or_sparse_tensors(outputs) input_info = { input_name: tf_v1.saved_model.utils.build_tensor_info(tensor) for input_name, tensor in inputs.items() } output_info = { output_name: tf_v1.saved_model.utils.build_ten...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _export_signatures(meta_graph): """Exports signatures from current graph into a MetaGraphDef."""
named_signatures = tf_v1.get_collection(_SIGNATURE_COLLECTION) if not named_signatures: raise ValueError("No signatures present. Please call hub.add_signature(...)" "at least once in the module_fn.") for key, signature in named_signatures: meta_graph.signature_def[key].CopyFrom(signa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
tf_v1.add_to_collection( _ATTACHMENT_COLLECTION_INTERNAL, module_attachment_pb2.ModuleAttachment(key=key, value=the_bytes))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _export_module_attachments(meta_graph): """Exports ModuleAttachments from the current tf.Graph into `meta_graph`."""
added_attachments = tf_v1.get_collection(_ATTACHMENT_COLLECTION_INTERNAL) if not added_attachments: return # Don't touch `meta_graph`. unique_attachments = collections.OrderedDict( # Avoid indeterminism. (attachment.key, attachment) for attachment in added_attachments) meta_graph.collection_def[A...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_attached_bytes_map(meta_graph): """Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModel...
result = {} if ATTACHMENT_COLLECTION_SAVED not in meta_graph.collection_def: return result collection_def = meta_graph.collection_def[ATTACHMENT_COLLECTION_SAVED] if collection_def.WhichOneof("kind") != "bytes_list": raise ValueError( "Internal CollectionDef for attached messages has kind %s, "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_asset_node_def(node_def): """Raises TypeError if `node_def` does not match the expectations."""
if node_def.op != "Const": raise TypeError("Asset node must be of type constant.") if tf.as_dtype(node_def.attr["dtype"].type) != tf.string: raise TypeError("Asset node must be of dtype string.") if len(node_def.attr["value"].tensor.string_val) != 1: raise TypeError("Asset node must be a scalar.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 co...
for meta_graph in saved_model_proto.meta_graphs: node_asset_map = {} if tf_v1.saved_model.constants.ASSETS_KEY in meta_graph.collection_def: assets_any_proto = meta_graph.collection_def[ tf_v1.saved_model.constants.ASSETS_KEY].any_list.value for asset_any_proto in assets_any_proto: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 co...
asset_filenames = {} used_asset_filenames = set() def _make_asset_filename(original_filename): """Returns the asset filename to use for the file.""" if original_filename in asset_filenames: return asset_filenames[original_filename] basename = os.path.basename(original_filename) suggestion...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_saved_model(path): """Reads the savedmodel.pb file containing `SavedModel`."""
# Based on tensorflow/python/saved_model/loader.py implementation. path_to_pb = _get_saved_model_proto_path(path) file_content = tf_v1.gfile.Open(path_to_pb, "rb").read() saved_model = saved_model_pb2.SavedModel() try: saved_model.ParseFromString(file_content) except message.DecodeError as e: raise...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 older versions unware of those attributes. meta_graph = tf_v1.train.export_meta_graph(strip_default_a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(self, path, variables_saver=None): """Exports to SavedModel directory. Args: path: path where to export the SavedModel to. variables_saver: lambda tha...
# Operate on a copy of self._proto since it needs to be modified. proto = saved_model_pb2.SavedModel() proto.CopyFrom(self._proto) assets_map = _make_assets_key_collection(proto, path) self._save_all_assets(path, assets_map) self._save_variables(path, variables_saver) self._save_proto(path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_meta_graph(self, tags=None): """Returns the matching MetaGraphDef or raises KeyError."""
matches = [meta_graph for meta_graph in self.meta_graphs if set(meta_graph.meta_info_def.tags) == set(tags or [])] if not matches: raise KeyError("SavedModelHandler has no graph with tags: %r" % tags) if len(matches) != 1: raise KeyError( "SavedModelHandl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_dict_inputs(inputs, tensor_info_map): """Converts from inputs into dict of input tensors. This handles: - putting inputs into a dict, per _prepare_d...
dict_inputs = _prepare_dict_inputs(inputs, tensor_info_map) return tensor_info.convert_dict_to_compatible_tensor(dict_inputs, tensor_info_map)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_function_for_module(spec, tags=None): """Context manager that yields a function to directly evaluate a Module. This creates a separate graph, in which a...
# We create a separate graph and add all the signatures of the module to it. original_graph = tf_v1.get_default_graph() with tf.Graph().as_default(): module = Module(spec, tags=tags) input_tensors_per_signature = {} output_tensors_per_signature = {} for signature in module.get_signature_names(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_input_info_dict(self, signature=None): """Describes the inputs required by a signature. Args: signature: A string with the signature to get inputs inform...
return self._spec.get_input_info_dict(signature=signature, tags=self._tags)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_output_info_dict(self, signature=None): """Describes the outputs provided by a signature. Args: signature: A string with the signature to get ouputs info...
return self._spec.get_output_info_dict(signature=signature, tags=self._tags)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(self, path, session): """Exports the module with the variables from the session in `path`. Note that it is the module definition in the ModuleSpec use...
if self._graph is not tf_v1.get_default_graph(): raise RuntimeError("default graph differs from the graph where the " "module was instantiated.") if self._graph is not session.graph: raise RuntimeError("session graph differs from the graph where the " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variables(self): """Returns the list of all tf.Variables created by module instantiation."""
result = [] for _, value in sorted(self.variable_map.items()): if isinstance(value, list): result.extend(value) else: result.append(value) return result