response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
str->dict Information for CKPlayer API content.
def ckplayer_get_info_by_xml(ckinfo): """str->dict Information for CKPlayer API content.""" e = ET.XML(ckinfo) video_dict = {'title': '', #'duration': 0, 'links': [], 'size': 0, 'flashvars': '',} dictified = dictify(e)['ckplayer...
Downloads Dailymotion videos by URL.
def dailymotion_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads Dailymotion videos by URL. """ html = get_content(rebuilt_url(url)) info = json.loads(match1(html, r'qualities":({.+?}),"')) title = match1(html, r'"video_title"\s*:\s*"([^"]+)"') or \ mat...
From http://cdn37.atwikiimg.com/sitescript/pub/dksitescript/FC2.site.js Also com.hps.util.fc2.FC2EncrptUtil.makeMimiLocal L110
def makeMimi(upid): """From http://cdn37.atwikiimg.com/sitescript/pub/dksitescript/FC2.site.js Also com.hps.util.fc2.FC2EncrptUtil.makeMimiLocal L110""" strSeed = "gGddgPfeaf_gzyr" prehash = upid + "_" + strSeed return md5(prehash.encode('utf-8')).hexdigest()
wrapper
def fc2video_download(url, output_dir = '.', merge = True, info_only = False, **kwargs): """wrapper""" #'http://video.fc2.com/en/content/20151021bTVKnbEw' #'http://xiaojiadianvideo.asia/content/20151021bTVKnbEw' #'http://video.fc2.com/ja/content/20151021bTVKnbEw' #'http://video.fc2.com/tw/content/20...
Source: Android mobile
def miaopai_download_by_fid(fid, output_dir = '.', merge = False, info_only = False, **kwargs): '''Source: Android mobile''' page_url = 'https://video.weibo.com/show?fid=' + fid + '&type=mp4' mobile_page = get_content(page_url, headers=fake_headers_mobile) url = match1(mobile_page, r'<video id=.*?src=[...
str->list Convert XML to URL List. From Biligrab.
def sina_xml_to_url_list(xml_data): """str->list Convert XML to URL List. From Biligrab. """ rawurl = [] dom = parseString(xml_data) for node in dom.getElementsByTagName('durl'): url = node.getElementsByTagName('url')[0] rawurl.append(url.childNodes[0].data) return rawurl
str->str
def showroom_get_roomid_by_room_url_key(room_url_key): """str->str""" fake_headers_mobile = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'UTF-8,*;q=0.5', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'en-US,en;q=0.8...
Source: Android mobile
def showroom_download_by_room_id(room_id, output_dir = '.', merge = False, info_only = False, **kwargs): '''Source: Android mobile''' while True: timestamp = str(int(time() * 1000)) api_endpoint = 'https://www.showroom-live.com/api/live/streaming_url?room_id={room_id}&_={timestamp}'.format(room_...
Downloads a Sina video by its unique vid. http://video.sina.com.cn/
def sina_download_by_vid(vid, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vid. http://video.sina.com.cn/ """ xml = api_req(vid) urls, name, size = video_info(xml) if urls is None: log.wtf(name) title = name print_info(site_inf...
Downloads a Sina video by its unique vkey. http://video.sina.com/
def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vkey. http://video.sina.com/ """ url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey type, ext, size = url_info(url) print_info(site_info, title, 'flv', size) ...
Downloads Sina videos by URL.
def sina_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads Sina videos by URL. """ if 'news.sina.com.cn/zxt' in url: sina_zxt(url, output_dir=output_dir, merge=merge, info_only=info_only, **kwargs) return vid = match1(url, r'vid=(\d+)') if vid is Non...
http://stackoverflow.com/a/30923963/2946714
def dictify(r,root=True): """http://stackoverflow.com/a/30923963/2946714""" if root: return {r.tag : dictify(r, False)} d=copy(r.attrib) if r.text: d["_text"]=r.text for x in r.findall("./*"): if x.tag not in d: d[x.tag]=[] d[x.tag].append(dictify(x,Fal...
video page
def ucas_download_single(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''video page''' html = get_content(url) # resourceID is UUID resourceID = re.findall( r'resourceID":"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', html)[0] assert resourceID != '', 'Canno...
course page
def ucas_download_playlist(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''course page''' html = get_content(url) parts = re.findall( r'(getplaytitle.do\?.+)"', html) assert parts, 'No part found!' for part_path in parts: ucas_download('http://v.ucas.ac.cn/course/' +...
Get item_id
def veoh_download(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''Get item_id''' if re.match(r'http://www.veoh.com/watch/\w+', url): item_id = match1(url, r'http://www.veoh.com/watch/(\w+)') elif re.match(r'http://www.veoh.com/m/watch.php\?v=\.*', url): item_id = matc...
Source: Android mobile
def veoh_download_by_id(item_id, output_dir = '.', merge = False, info_only = False, **kwargs): """Source: Android mobile""" webpage_url = 'http://www.veoh.com/m/watch.php?v={item_id}&quality=1'.format(item_id = item_id) #grab download URL a = get_content(webpage_url, decoded=True) url = match1(a, ...
str->None
def vimeo_download_by_channel(url, output_dir='.', merge=False, info_only=False, **kwargs): """str->None""" # https://vimeo.com/channels/464686 channel_id = match1(url, r'http://vimeo.com/channels/(\w+)') vimeo_download_by_channel_id(channel_id, output_dir, merge, info_only, **kwargs)
str/int->None
def vimeo_download_by_channel_id(channel_id, output_dir='.', merge=False, info_only=False, **kwargs): """str/int->None""" html = get_content('https://api.vimeo.com/channels/{channel_id}/videos?access_token={access_token}'.format(channel_id=channel_id, access_token=access_token)) data = loads(html) id_li...
try: # normal Vimeo video html = get_content('https://vimeo.com/' + id) cfg_patt = r'clip_page_config\s*=\s*(\{.+?\});' cfg = json.loads(match1(html, cfg_patt)) video_page = get_content(cfg['player']['config_url'], headers=fake_headers) title = cfg['clip']['title'] info = loads(video_page) e...
def vimeo_download_by_id(id, title=None, output_dir='.', merge=True, info_only=False, **kwargs): ''' try: # normal Vimeo video html = get_content('https://vimeo.com/' + id) cfg_patt = r'clip_page_config\s*=\s*(\{.+?\});' cfg = json.loads(match1(html, cfg_patt)) video_page...
int->JSON Return a parsed JSON tree of WanMen's API.
def _wanmen_get_json_api_content_by_courseID(courseID): """int->JSON Return a parsed JSON tree of WanMen's API.""" return loads(get_content('http://api.wanmen.org/course/getCourseNested/{courseID}'.format(courseID = courseID)))
JSON, int, int, int->str Get a proper title with courseid+topicID+partID.
def _wanmen_get_title_by_json_topic_part(json_content, tIndex, pIndex): """JSON, int, int, int->str Get a proper title with courseid+topicID+partID.""" return '_'.join([json_content[0]['name'], json_content[0]['Topics'][tIndex]['name'], json_content[0]['Topics']...
JSON, int, int, int->str Get one BokeCC video ID with courseid+topicID+partID.
def _wanmen_get_boke_id_by_json_topic_part(json_content, tIndex, pIndex): """JSON, int, int, int->str Get one BokeCC video ID with courseid+topicID+partID.""" return json_content[0]['Topics'][tIndex]['Parts'][pIndex]['ccVideoLink']
int->None Download a WHOLE course. Reuse the API call to save time.
def wanmen_download_by_course(json_api_content, output_dir='.', merge=True, info_only=False, **kwargs): """int->None Download a WHOLE course. Reuse the API call to save time.""" for tIndex in range(len(json_api_content[0]['Topics'])): for pIndex in range(len(json_api_content[0]['Topics'][...
int, int->None Download a TOPIC of a course. Reuse the API call to save time.
def wanmen_download_by_course_topic(json_api_content, tIndex, output_dir='.', merge=True, info_only=False, **kwargs): """int, int->None Download a TOPIC of a course. Reuse the API call to save time.""" for pIndex in range(len(json_api_content[0]['Topics'][tIndex]['Parts'])): wanmen_downloa...
int, int, int->None Download ONE PART of the course.
def wanmen_download_by_course_topic_part(json_api_content, tIndex, pIndex, output_dir='.', merge=True, info_only=False, **kwargs): """int, int, int->None Download ONE PART of the course.""" html = json_api_content title = _wanmen_get_title_by_json_topic_part(html, ...
wrapper
def yixia_download(url, output_dir = '.', merge = True, info_only = False, **kwargs): """wrapper""" hostname = urlparse(url).hostname if 'n.miaopai.com' == hostname: smid = match1(url, r'n\.miaopai\.com/media/([^.]+)') miaopai_download_by_smid(smid, output_dir, merge, info_only) re...
str, str->True WARNING: NOT THE SAME PARMS AS OTHER FUNCTIONS!!!!!! You can basically download anything with this function but better leave it alone with
def ffmpeg_download_stream(files, title, ext, params={}, output_dir='.', stream=True): """str, str->True WARNING: NOT THE SAME PARMS AS OTHER FUNCTIONS!!!!!! You can basically download anything with this function but better leave it alone with """ output = title + '.' + ext if not (output_d...
Converts a string to a valid filename.
def legitimize(text, os=detect_os()): """Converts a string to a valid filename. """ # POSIX systems text = text.translate({ 0: None, ord('/'): '-', ord('|'): '-', }) # FIXME: do some filesystem detection if os == 'windows' or os == 'cygwin' or os == 'wsl': #...
Get (branch, commit) from HEAD of a git repo.
def get_head(repo_path): """Get (branch, commit) from HEAD of a git repo.""" try: ref = open(os.path.join(repo_path, '.git', 'HEAD'), 'r').read().strip()[5:].split('/') branch = ref[-1] commit = open(os.path.join(repo_path, '.git', *ref), 'r').read().strip()[:7] return branch, co...
Format text with color or other effects into ANSI escaped string.
def sprint(text, *colors): """Format text with color or other effects into ANSI escaped string.""" return "\33[{}m{content}\33[{}m".format(";".join([str(color) for color in colors]), RESET, content=text) if IS_ANSI_TERMINAL and colors else text
Print text to standard output.
def println(text, *colors): """Print text to standard output.""" sys.stdout.write(sprint(text, *colors) + "\n")
Print text to standard error.
def print_err(text, *colors): """Print text to standard error.""" sys.stderr.write(sprint(text, *colors) + "\n")
Print a log message to standard error.
def print_log(text, *colors): """Print a log message to standard error.""" sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n")
Print a normal log message.
def i(message): """Print a normal log message.""" print_log(message)
Print a debug log message.
def d(message): """Print a debug log message.""" print_log(message, BLUE)
Print a warning log message.
def w(message): """Print a warning log message.""" print_log(message, YELLOW)
Print an error log message.
def e(message, exit_code=None): """Print an error log message.""" print_log(message, YELLOW, BOLD) if exit_code is not None: sys.exit(exit_code)
What a Terrible Failure!
def wtf(message, exit_code=1): """What a Terrible Failure!""" print_log(message, RED, BOLD) if exit_code is not None: sys.exit(exit_code)
Detect operating system.
def detect_os(): """Detect operating system. """ # Inspired by: # https://github.com/scivision/pybashutils/blob/78b7f2b339cb03b1c37df94015098bbe462f8526/pybashutils/windows_linux_detect.py syst = system().lower() os = 'unknown' if 'cygwin' in syst: os = 'cygwin' elif 'darwin'...
Get (width, height) of the current terminal.
def get_terminal_size(): """Get (width, height) of the current terminal.""" try: import fcntl, termios, struct # fcntl module only available on Unix return struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')) except: return (40, 80)
Searches the provided modules for the named class and returns it.
def find_class_by_name(name, modules): """Searches the provided modules for the named class and returns it.""" modules = [getattr(module, name, None) for module in modules] return next(a for a in modules if a)
Creates the section of the graph which reads the evaluation data. Args: reader: A class which parses the training data. data_pattern: A 'glob' style path to the data files. batch_size: How many examples to process at a time. num_readers: How many I/O threads to use. Returns: A tuple containing the features ...
def get_input_evaluation_tensors(reader, data_pattern, batch_size=1024, num_readers=1): """Creates the section of the graph which reads the evaluation data. Args: reader: A class which parses the training data. ...
Creates the Tensorflow graph for evaluation. Args: reader: The data file reader. It should inherit from BaseReader. model: The core model (e.g. logistic or neural net). It should inherit from BaseModel. eval_data_pattern: glob path to the evaluation data files. label_loss_fn: What kind of loss to apply to ...
def build_graph(reader, model, eval_data_pattern, label_loss_fn, batch_size=1024, num_readers=1): """Creates the Tensorflow graph for evaluation. Args: reader: The data file reader. It should inherit from BaseReader. model: The...
Run the evaluation loop once. Args: fetches: a dict of tensors to be run within Session. saver: a tensorflow saver to restore the model. summary_writer: a tensorflow summary_writer evl_metrics: an EvaluationMetrics object. last_global_step_val: the global step used in the previous evaluation. Returns: The...
def evaluation_loop(fetches, saver, summary_writer, evl_metrics, last_global_step_val): """Run the evaluation loop once. Args: fetches: a dict of tensors to be run within Session. saver: a tensorflow saver to restore the model. summary_writer: a tensorflow summary_writer evl_met...
Starts main evaluation loop.
def evaluate(): """Starts main evaluation loop.""" tf.compat.v1.set_random_seed(0) # for reproducibility # Write json of flags model_flags_path = os.path.join(FLAGS.train_dir, "model_flags.json") if not file_io.file_exists(model_flags_path): raise IOError(("Cannot find file %s. Did you run train.py on t...
Merges a list of lists into a single list.
def flatten(l): """Merges a list of lists into a single list. """ return [item for sublist in l for item in sublist]
Performs a local (numpy) calculation of the hit at one. Args: predictions: Matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. actuals: Matrix containing the ground truth labels. Dimensions are 'batch' x 'num_classes'. Returns: float: The average hit at one across the ent...
def calculate_hit_at_one(predictions, actuals): """Performs a local (numpy) calculation of the hit at one. Args: predictions: Matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. actuals: Matrix containing the ground truth labels. Dimensions are 'batch' x 'num_cla...
Performs a local (numpy) calculation of the PERR. Args: predictions: Matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. actuals: Matrix containing the ground truth labels. Dimensions are 'batch' x 'num_classes'. Returns: float: The average precision at equal recall rate ...
def calculate_precision_at_equal_recall_rate(predictions, actuals): """Performs a local (numpy) calculation of the PERR. Args: predictions: Matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. actuals: Matrix containing the ground truth labels. Dimensions are 'batch' x ...
Performs a local (numpy) calculation of the global average precision. Only the top_k predictions are taken for each of the videos. Args: predictions: Matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. actuals: Matrix containing the ground truth labels. Dimensions are 'batch' x...
def calculate_gap(predictions, actuals, top_k=20): """Performs a local (numpy) calculation of the global average precision. Only the top_k predictions are taken for each of the videos. Args: predictions: Matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. actuals: M...
Extracts the top k predictions for each video, sorted by class. Args: predictions: A numpy matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. k: the top k non-zero entries to preserve in each prediction. Returns: A tuple (predictions,labels, true_positives). 'predictions' an...
def top_k_by_class(predictions, labels, k=20): """Extracts the top k predictions for each video, sorted by class. Args: predictions: A numpy matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. k: the top k non-zero entries to preserve in each prediction. Returns: ...
Get the top_k for a 1-d numpy array. Returns a sparse list of tuples in (prediction, class) format
def top_k_triplets(predictions, labels, k=20): """Get the top_k for a 1-d numpy array. Returns a sparse list of tuples in (prediction, class) format """ m = len(predictions) k = min(k, m) indices = numpy.argpartition(predictions, -k)[-k:] return [(index, predictions[index], labels[index]) for index in ...
Create an information line the submission file.
def format_lines(video_ids, predictions, top_k, whitelisted_cls_mask=None): """Create an information line the submission file.""" batch_size = len(video_ids) for video_index in range(batch_size): video_prediction = predictions[video_index] if whitelisted_cls_mask is not None: # Whitelist classes. ...
Creates the section of the graph which reads the input data. Args: reader: A class which parses the input data. data_pattern: A 'glob' style path to the data files. batch_size: How many examples to process at a time. num_readers: How many I/O threads to use. Returns: A tuple containing the features tensor, ...
def get_input_data_tensors(reader, data_pattern, batch_size, num_readers=1): """Creates the section of the graph which reads the input data. Args: reader: A class which parses the input data. data_pattern: A 'glob' style path to the data files. batch_size: How many examples to process at a time. nu...
Get segment-level inputs from frame-level features.
def get_segments(batch_video_mtx, batch_num_frames, segment_size): """Get segment-level inputs from frame-level features.""" video_batch_size = batch_video_mtx.shape[0] max_frame = batch_video_mtx.shape[1] feature_dim = batch_video_mtx.shape[-1] padded_segment_sizes = (batch_num_frames + segment_size - 1) // ...
Inference function.
def inference(reader, train_dir, data_pattern, out_file_location, batch_size, top_k): """Inference function.""" with tf.Session(config=tf.ConfigProto( allow_soft_placement=True)) as sess, gfile.Open(out_file_location, "w+") as out_file: v...
Samples a random sequence of frames of size num_samples. Args: model_input: A tensor of size batch_size x max_frames x feature_size num_frames: A tensor of size batch_size x 1 num_samples: A scalar Returns: `model_input`: A tensor of size batch_size x num_samples x feature_size
def SampleRandomSequence(model_input, num_frames, num_samples): """Samples a random sequence of frames of size num_samples. Args: model_input: A tensor of size batch_size x max_frames x feature_size num_frames: A tensor of size batch_size x 1 num_samples: A scalar Returns: `model_input`: A tenso...
Samples a random set of frames of size num_samples. Args: model_input: A tensor of size batch_size x max_frames x feature_size num_frames: A tensor of size batch_size x 1 num_samples: A scalar Returns: `model_input`: A tensor of size batch_size x num_samples x feature_size
def SampleRandomFrames(model_input, num_frames, num_samples): """Samples a random set of frames of size num_samples. Args: model_input: A tensor of size batch_size x max_frames x feature_size num_frames: A tensor of size batch_size x 1 num_samples: A scalar Returns: `model_input`: A tensor of si...
Pools over the frames of a video. Args: frames: A tensor with shape [batch_size, num_frames, feature_size]. method: "average", "max", "attention", or "none". Returns: A tensor with shape [batch_size, feature_size] for average, max, or attention pooling. A tensor with shape [batch_size*num_frames, feature_size...
def FramePooling(frames, method, **unused_params): """Pools over the frames of a video. Args: frames: A tensor with shape [batch_size, num_frames, feature_size]. method: "average", "max", "attention", or "none". Returns: A tensor with shape [batch_size, feature_size] for average, max, or attenti...
Truncates or pads a tensor to new_size on on a given axis. Truncate or extend tensor such that tensor.shape[axis] == new_size. If the size increases, the padding will be performed at the end, using fill_value. Args: tensor: The tensor to be resized. axis: An integer representing the dimension to be sliced. new_...
def resize_axis(tensor, axis, new_size, fill_value=0): """Truncates or pads a tensor to new_size on on a given axis. Truncate or extend tensor such that tensor.shape[axis] == new_size. If the size increases, the padding will be performed at the end, using fill_value. Args: tensor: The tensor to be resized...
Read labels from TFRecords. Args: data_pattern: the data pattern to the TFRecords. cache_path: the cache path for the label file. Returns: a Labels object.
def read_labels(data_pattern, cache_path=""): """Read labels from TFRecords. Args: data_pattern: the data pattern to the TFRecords. cache_path: the cache path for the label file. Returns: a Labels object. """ if cache_path: if tf.gfile.Exists(cache_path): tf.logging.info("Reading cach...
Read segement predictions. Args: file_path: the submission file path. labels: a Labels object containing the eval labels. top_n: the per-class class capping. Returns: a segment prediction list for each classes.
def read_segment_predictions(file_path, labels, top_n=None): """Read segement predictions. Args: file_path: the submission file path. labels: a Labels object containing the eval labels. top_n: the per-class class capping. Returns: a segment prediction list for each classes. """ cls_preds = {...
Entry function of the script.
def main(unused_argv): """Entry function of the script.""" if not FLAGS.submission_file: raise ValueError("You must input submission file.") eval_labels = read_labels(FLAGS.eval_data_pattern, cache_path=FLAGS.label_cache) tf.logging.info("Total rated segments: %d." % len(eval_lab...
Checks that the given string matches a class of the expected type. Args: flag_value: A string naming the class to instantiate. category: A string used further describe the class in error messages (e.g. 'model', 'reader', 'loss'). modules: A list of modules to search for the given class. expected_superclass...
def validate_class_name(flag_value, category, modules, expected_superclass): """Checks that the given string matches a class of the expected type. Args: flag_value: A string naming the class to instantiate. category: A string used further describe the class in error messages (e.g. 'model', 'reader', ...
Creates the section of the graph which reads the training data. Args: reader: A class which parses the training data. data_pattern: A 'glob' style path to the data files. batch_size: How many examples to process at a time. num_epochs: How many passes to make over the training data. Set to 'None' to run ind...
def get_input_data_tensors(reader, data_pattern, batch_size=1000, num_epochs=None, num_readers=1): """Creates the section of the graph which reads the training data. Args: reader: A class which parses th...
Searches the provided modules for the named class and returns it.
def find_class_by_name(name, modules): """Searches the provided modules for the named class and returns it.""" modules = [getattr(module, name, None) for module in modules] return next(a for a in modules if a)
Creates the Tensorflow graph. This will only be called once in the life of a training model, because after the graph is created the model will be restored from a meta graph file rather than being recreated. Args: reader: The data file reader. It should inherit from BaseReader. model: The core model (e.g. logistic...
def build_graph(reader, model, train_data_pattern, label_loss_fn=losses.CrossEntropyLoss(), batch_size=1000, base_learning_rate=0.01, learning_rate_decay_examples=1000000, learning_rate_decay=0.95, ...
Creates a Server. Args: cluster: A tf.train.ClusterSpec if the execution is distributed. None otherwise. task: A TaskSpec describing the job type and the task index.
def start_server(cluster, task): """Creates a Server. Args: cluster: A tf.train.ClusterSpec if the execution is distributed. None otherwise. task: A TaskSpec describing the job type and the task index. """ if not task.type: raise ValueError("%s: The task type must be specified." % ...
Dequantize the feature from the byte format to the float format. Args: feat_vector: the input 1-d vector. max_quantized_value: the maximum of the quantized value. min_quantized_value: the minimum of the quantized value. Returns: A float vector which has the same shape as feat_vector.
def Dequantize(feat_vector, max_quantized_value=2, min_quantized_value=-2): """Dequantize the feature from the byte format to the float format. Args: feat_vector: the input 1-d vector. max_quantized_value: the maximum of the quantized value. min_quantized_value: the minimum of the quantized value. R...
Creates a tf.Summary proto with the given name and value.
def MakeSummary(name, value): """Creates a tf.Summary proto with the given name and value.""" summary = tf.Summary() val = summary.value.add() val.tag = str(name) val.simple_value = float(value) return summary
Add the global_step summary to the Tensorboard. Args: summary_writer: Tensorflow summary_writer. global_step_val: a int value of the global step. global_step_info_dict: a dictionary of the evaluation metrics calculated for a mini-batch. summary_scope: Train or Eval. Returns: A string of this global_step...
def AddGlobalStepSummary(summary_writer, global_step_val, global_step_info_dict, summary_scope="Eval"): """Add the global_step summary to the Tensorboard. Args: summary_writer: Tensorflow summary_writer. global_step_val: a int value...
Add the epoch summary to the Tensorboard. Args: summary_writer: Tensorflow summary_writer. global_step_val: a int value of the global step. epoch_info_dict: a dictionary of the evaluation metrics calculated for the whole epoch. summary_scope: Train or Eval. Returns: A string of this global_step summary
def AddEpochSummary(summary_writer, global_step_val, epoch_info_dict, summary_scope="Eval"): """Add the epoch summary to the Tensorboard. Args: summary_writer: Tensorflow summary_writer. global_step_val: a int value of the global step. epoch_i...
Extract the list of feature names and the dimensionality of each feature from string of comma separated values. Args: feature_names: string containing comma separated list of feature names feature_sizes: string containing comma separated list of feature sizes Returns: List of the feature names and list of t...
def GetListOfFeatureNamesAndSizes(feature_names, feature_sizes): """Extract the list of feature names and the dimensionality of each feature from string of comma separated values. Args: feature_names: string containing comma separated list of feature names feature_sizes: string containing comma separ...
Clips the gradients by the given value. Args: gradients_to_variables: A list of gradient to variable pairs (tuples). max_norm: the maximum norm value. Returns: A list of clipped gradient to variable pairs.
def clip_gradient_norms(gradients_to_variables, max_norm): """Clips the gradients by the given value. Args: gradients_to_variables: A list of gradient to variable pairs (tuples). max_norm: the maximum norm value. Returns: A list of clipped gradient to variable pairs. """ clipped_grads_and_vars =...
Calculate the combined gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient calculation ...
def combine_gradients(tower_grads): """Calculate the combined gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. T...
Uses OpenCV to iterate over all frames of filename at a given frequency. Args: filename: Path to video file (e.g. mp4) every_ms: The duration (in milliseconds) to skip between frames. max_num_frames: Maximum number of frames to process, taken from the beginning of the video. Yields: RGB frame with shape (...
def frame_iterator(filename, every_ms=1000, max_num_frames=300): """Uses OpenCV to iterate over all frames of filename at a given frequency. Args: filename: Path to video file (e.g. mp4) every_ms: The duration (in milliseconds) to skip between frames. max_num_frames: Maximum number of frames to process...
Quantizes float32 `features` into string.
def quantize(features, min_quantized_value=-2.0, max_quantized_value=2.0): """Quantizes float32 `features` into string.""" assert features.dtype == 'float32' assert len(features.shape) == 1 # 1-D array features = numpy.clip(features, min_quantized_value, max_quantized_value) quantize_range = max_quantized_va...
Calculates element-wise percent difference between two numpy matrices.
def _MeanElementWiseDifference(a, b): """Calculates element-wise percent difference between two numpy matrices.""" difference = numpy.abs(a - b) denominator = numpy.maximum(numpy.abs(a), numpy.abs(b)) # We dont care if one is 0 and another is 0.01 return (difference / (0.01 + denominator)).mean()
Get the version without importing the package
def read_version(fname='youtube_dl/version.py'): """Get the version without importing the package""" exec(compile(read_file(fname), fname, 'exec')) return locals()['__version__']
Remove a file if it exists
def try_rm(filename): """ Remove a file if it exists """ try: os.remove(filename) except OSError as ose: if ose.errno != errno.ENOENT: raise
Print the message to stderr, it will be prefixed with 'WARNING:' If stderr is a tty file the 'WARNING:' will be colored
def report_warning(message): ''' Print the message to stderr, it will be prefixed with 'WARNING:' If stderr is a tty file the 'WARNING:' will be colored ''' if sys.stderr.isatty() and compat_os_name != 'nt': _msg_header = '\033[0;33mWARNING:\033[0m' else: _msg_header = 'WARNING:...
Returns true if the file has been downloaded
def _download_restricted(url, filename, age): """ Returns true if the file has been downloaded """ params = { 'age_limit': age, 'skip_download': True, 'writeinfojson': True, 'outtmpl': '%(id)s.%(ext)s', } ydl = YoutubeDL(params) ydl.add_default_info_extractors() ...
PKCS#7 padding @param {int[]} data cleartext @returns {int[]} padding data
def pkcs7_padding(data): """ PKCS#7 padding @param {int[]} data cleartext @returns {int[]} padding data """ remaining_length = BLOCK_SIZE_BYTES - len(data) % BLOCK_SIZE_BYTES return data + [remaining_length] * remaining_length
Decrypt with aes in counter mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {instance} counter Instance whose next_value function (@returns {int[]} 16-Byte block) returns the next counter block @returns {int[]} decrypted data
def aes_ctr_decrypt(data, key, counter): """ Decrypt with aes in counter mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {instance} counter Instance whose next_value function (@returns {int[]} 16-Byte block) returns ...
Decrypt with aes in CBC mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} decrypted data
def aes_cbc_decrypt(data, key, iv): """ Decrypt with aes in CBC mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} decrypted data """ expanded_key = key_expansion(key) block_coun...
Encrypt with aes in CBC mode. Using PKCS#7 padding @param {int[]} data cleartext @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} encrypted data
def aes_cbc_encrypt(data, key, iv): """ Encrypt with aes in CBC mode. Using PKCS#7 padding @param {int[]} data cleartext @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} encrypted data """ expanded_key = key_expa...
Encrypt with aes in ECB mode. Using PKCS#7 padding @param {int[]} data cleartext @param {int[]} key 16/24/32-Byte cipher key @returns {int[]} encrypted data
def aes_ecb_encrypt(data, key): """ Encrypt with aes in ECB mode. Using PKCS#7 padding @param {int[]} data cleartext @param {int[]} key 16/24/32-Byte cipher key @returns {int[]} encrypted data """ expanded_key = key_expansion(key) block_count = int(ceil(float(le...
Generate key schedule @param {int[]} data 16/24/32-Byte cipher key @returns {int[]} 176/208/240-Byte expanded key
def key_expansion(data): """ Generate key schedule @param {int[]} data 16/24/32-Byte cipher key @returns {int[]} 176/208/240-Byte expanded key """ data = data[:] # copy rcon_iteration = 1 key_size_bytes = len(data) expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SI...
Encrypt one block with aes @param {int[]} data 16-Byte state @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte cipher
def aes_encrypt(data, expanded_key): """ Encrypt one block with aes @param {int[]} data 16-Byte state @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte cipher """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 data = xor(data, ...
Decrypt one block with aes @param {int[]} data 16-Byte cipher @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte state
def aes_decrypt(data, expanded_key): """ Decrypt one block with aes @param {int[]} data 16-Byte cipher @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte state """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 for i in range(ro...
Decrypt text - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter - The cipher key is retrieved by encrypting the first 16 Byte of 'password' with the first 'key_size_bytes' Bytes from 'password' (if necessary filled with 0's) - Mode of operation is 'counter' @param {str} data ...
def aes_decrypt_text(data, password, key_size_bytes): """ Decrypt text - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter - The cipher key is retrieved by encrypting the first 16 Byte of 'password' with the first 'key_size_bytes' Bytes from 'password' (if necessary filled wi...
Simulate JS's ternary operator (cndn?if_true:if_false)
def _js_ternary(cndn, if_true=True, if_false=False): """Simulate JS's ternary operator (cndn?if_true:if_false)""" if cndn in (False, None, 0, '', JS_Undefined, _NaN): return if_false return if_true
Update the program file with the latest version from the repository
def update_self(to_screen, verbose, opener): """Update the program file with the latest version from the repository""" UPDATE_URL = 'https://yt-dl.org/update/' VERSION_URL = UPDATE_URL + 'LATEST_VERSION' JSON_URL = UPDATE_URL + 'versions.json' UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66...
Get preferred encoding. Returns the best encoding scheme for the system, based on locale.getpreferredencoding() and some further tweaks.
def preferredencoding(): """Get preferred encoding. Returns the best encoding scheme for the system, based on locale.getpreferredencoding() and some further tweaks. """ try: pref = locale.getpreferredencoding() 'TEST'.encode(pref) except Exception: pref = 'UTF-8' re...
Encode obj as JSON and write it to fn, atomically if possible
def write_json_file(obj, fn): """ Encode obj as JSON and write it to fn, atomically if possible """ fn = encodeFilename(fn) if sys.version_info < (3, 0) and sys.platform != 'win32': encoding = get_filesystem_encoding() # os.path.basename returns a bytes object, but NamedTemporaryFile ...
Return the content of the tag with the specified ID in the passed HTML document
def get_element_by_id(id, html): """Return the content of the tag with the specified ID in the passed HTML document""" return get_element_by_attribute('id', id, html)
Return the content of the first tag with the specified class in the passed HTML document
def get_element_by_class(class_name, html): """Return the content of the first tag with the specified class in the passed HTML document""" retval = get_elements_by_class(class_name, html) return retval[0] if retval else None
Return the content of all tags with the specified class in the passed HTML document as a list
def get_elements_by_class(class_name, html): """Return the content of all tags with the specified class in the passed HTML document as a list""" return get_elements_by_attribute( 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name), html, escape_value=False)
Return the content of the tag with the specified attribute in the passed HTML document
def get_elements_by_attribute(attribute, value, html, escape_value=True): """Return the content of the tag with the specified attribute in the passed HTML document""" value = re.escape(value) if escape_value else value retlist = [] for m in re.finditer(r'''(?xs) <([a-zA-Z0-9:._-]+) (?...
Given a string for an HTML element such as <el a="foo" B="bar" c="&98;az" d=boz empty= noval entity="&amp;" sq='"' dq="'" > Decode and return a dictionary of attributes. { 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz', 'empty': '', 'noval': None, 'entity': '&', 'sq': '"', 'dq': ''' }. NB HTMLPar...
def extract_attributes(html_element): """Given a string for an HTML element such as <el a="foo" B="bar" c="&98;az" d=boz empty= noval entity="&amp;" sq='"' dq="'" > Decode and return a dictionary of attributes. { 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz', ...
Clean an HTML snippet into a readable string
def clean_html(html): """Clean an HTML snippet into a readable string""" if html is None: # Convenience for sanitizing descriptions etc. return html # Newline vs <br /> html = html.replace('\n', ' ') html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html) html = re.sub(r'(?u)<\s*/\s*p...