Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def list_tickets(self, **kwargs): filter_name = 'all_tickets' if 'filter_name' in kwargs and kwargs['filter_name'] is not None: filter_name = kwargs['filter_name'] del kwargs['filter_name'] url = 'helpdesk/tickets/fi...
[ "List all tickets, optionally filtered by a view. Specify filters as\n keyword arguments, such as:\n\n filter_name = one of ['all_tickets', 'new_my_open', 'spam', 'deleted',\n None]\n (defaults to 'all_tickets'; passing None uses the default)\n\n Multipl...
Please provide a description of the function:def list_contacts(self, **kwargs): url = 'contacts.json?' if 'query' in kwargs.keys(): filter_query = kwargs.pop('query') url = url + "query={}".format(filter_query) if 'state' in kwargs.keys(): state_que...
[ "\n List all contacts, optionally filtered by a query. Specify filters as\n query keyword argument, such as: \n \n query= email is abc@xyz.com,\n query= mobile is 1234567890,\n query= phone is 1234567890,\n\n contacts can be filtered by name such as;\n \n ...
Please provide a description of the function:def create_contact(self, *args, **kwargs): url = 'contacts.json' contact_data = { 'active': True, 'helpdesk_agent': False, 'description': 'Freshdesk Contact' } contact_data.update(kwargs) pa...
[ "Creates a contact" ]
Please provide a description of the function:def list_agents(self, **kwargs): url = 'agents.json?' if 'query' in kwargs.keys(): filter_query = kwargs.pop('query') url = url + "query={}".format(filter_query) if 'state' in kwargs.keys(): state_query =...
[ "List all agents, optionally filtered by a query. Specify filters as\n query keyword argument, such as: \n \n query= email is abc@xyz.com,\n query= mobile is 1234567890,\n query= phone is 1234567890,\n\n agents can be filtered by state such as:\n \n state=acti...
Please provide a description of the function:def _get(self, url, params={}): r = requests.get(self._api_prefix + url, params=params, headers=self.headers, auth=self.auth, ) return self._action(r)
[ "Wrapper around request.get() to use the API prefix. Returns a JSON response." ]
Please provide a description of the function:def _post(self, url, data={}): r = requests.post(self._api_prefix + url, data=json.dumps(data), headers=self.headers, auth=self.auth, allow_redirects=False, ) return self._action(r)
[ "Wrapper around request.post() to use the API prefix. Returns a JSON response." ]
Please provide a description of the function:def _put(self, url, data={}): r = requests.put(self._api_prefix + url, data=json.dumps(data), headers=self.headers, auth=self.auth, allow_redirects=False, ) return self._action(r)
[ "Wrapper around request.put() to use the API prefix. Returns a JSON response." ]
Please provide a description of the function:def _delete(self, url): r = requests.delete(self._api_prefix + url, headers=self.headers, auth=self.auth, allow_redirects=False, ) return self._action(r)
[ "Wrapper around request.delete() to use the API prefix. Returns a JSON response." ]
Please provide a description of the function:def _action(self, res): try: j = res.json() except: res.raise_for_status() j = {} if 'Retry-After' in res.headers: raise HTTPError('403 Forbidden: API rate-limit has been reached until {}.' ...
[ "Returns JSON response or raise exception if errors are present" ]
Please provide a description of the function:def headTail_breaks(values, cuts): values = np.array(values) mean = np.mean(values) cuts.append(mean) if len(values) > 1: return headTail_breaks(values[values >= mean], cuts) return cuts
[ "\n head tail breaks helper function\n " ]
Please provide a description of the function:def quantile(y, k=4): w = 100. / k p = np.arange(w, 100 + w, w) if p[-1] > 100.0: p[-1] = 100.0 q = np.array([stats.scoreatpercentile(y, pct) for pct in p]) q = np.unique(q) k_q = len(q) if k_q < k: Warn('Warning: Not enough ...
[ "\n Calculates the quantiles for an array\n\n Parameters\n ----------\n y : array\n (n,1), values to classify\n k : int\n number of quantiles\n\n Returns\n -------\n q : array\n (n,1), quantile values\n\n Examples\n --------\n >>> import numpy as...
Please provide a description of the function:def binC(y, bins): if np.ndim(y) == 1: k = 1 n = np.shape(y)[0] else: n, k = np.shape(y) b = np.zeros((n, k), dtype='int') for i, bin in enumerate(bins): b[np.nonzero(y == bin)] = i # check for non-binned items and w...
[ "\n Bin categorical/qualitative data\n\n Parameters\n ----------\n y : array\n (n,q), categorical values\n bins : array\n (k,1), unique values associated with each bin\n\n Return\n ------\n b : array\n (n,q), bin membership, values between 0 and k-1\n\n Exam...
Please provide a description of the function:def bin(y, bins): if np.ndim(y) == 1: k = 1 n = np.shape(y)[0] else: n, k = np.shape(y) b = np.zeros((n, k), dtype='int') i = len(bins) if type(bins) != list: bins = bins.tolist() binsc = copy.copy(bins) while ...
[ "\n bin interval/ratio data\n\n Parameters\n ----------\n y : array\n (n,q), values to bin\n bins : array\n (k,1), upper bounds of each bin (monotonic)\n\n Returns\n -------\n b : array\n (n,q), values of values between 0 and k-1\n\n Examples\n --------\n >>>...
Please provide a description of the function:def bin1d(x, bins): left = [-float("inf")] left.extend(bins[0:-1]) right = bins cuts = list(zip(left, right)) k = len(bins) binIds = np.zeros(x.shape, dtype='int') while cuts: k -= 1 l, r = cuts.pop(-1) binIds += (x > ...
[ "\n Place values of a 1-d array into bins and determine counts of values in\n each bin\n\n Parameters\n ----------\n x : array\n (n, 1), values to bin\n bins : array\n (k,1), upper bounds of each bin (monotonic)\n\n Returns\n -------\n binIds : array\n 1-d arr...
Please provide a description of the function:def _kmeans(y, k=5): y = y * 1. # KMEANS needs float or double dtype centroids = KMEANS(y, k)[0] centroids.sort() try: class_ids = np.abs(y - centroids).argmin(axis=1) except: class_ids = np.abs(y[:, np.newaxis] - centroids).argmin(...
[ "\n Helper function to do kmeans in one dimension\n " ]
Please provide a description of the function:def natural_breaks(values, k=5): values = np.array(values) uv = np.unique(values) uvk = len(uv) if uvk < k: Warn('Warning: Not enough unique values in array to form k classes', UserWarning) Warn('Warning: setting k to %d' % u...
[ "\n natural breaks helper function\n\n Jenks natural breaks is kmeans in one dimension\n " ]
Please provide a description of the function:def _fisher_jenks_means(values, classes=5, sort=True): if sort: values.sort() n_data = len(values) mat1 = np.zeros((n_data + 1, classes + 1), dtype=np.int32) mat2 = np.zeros((n_data + 1, classes + 1), dtype=np.float32) mat1[1, 1:] = 1 mat...
[ "\n Jenks Optimal (Natural Breaks) algorithm implemented in Python.\n\n Notes\n -----\n The original Python code comes from here:\n http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/\n and is based on a JAVA and Fortran code available here:\n https://stat.ethz.ch/piper...
Please provide a description of the function:def _fit(y, classes): tss = 0 for class_def in classes: yc = y[class_def] css = yc - yc.mean() css *= css tss += sum(css) return tss
[ "Calculate the total sum of squares for a vector y classified into\n classes\n\n Parameters\n ----------\n y : array\n (n,1), variable to be classified\n\n classes : array\n (k,1), integer values denoting class membership\n\n " ]
Please provide a description of the function:def gadf(y, method="Quantiles", maxk=15, pct=0.8): y = np.array(y) adam = (np.abs(y - np.median(y))).sum() for k in range(2, maxk + 1): cl = kmethods[method](y, k) gadf = 1 - cl.adcm / adam if gadf > pct: break return...
[ "\n Evaluate the Goodness of Absolute Deviation Fit of a Classifier\n Finds the minimum value of k for which gadf>pct\n\n Parameters\n ----------\n\n y : array\n (n, 1) values to be classified\n method : {'Quantiles, 'Fisher_Jenks', 'Maximum_Breaks', 'Natrual_Breaks'}\n maxk ...
Please provide a description of the function:def _update(self, data, *args, **kwargs): if data is not None: data = np.asarray(data).flatten() data = np.append(data.flatten(), self.y) else: data = self.y self.__init__(data, *args, **kwargs)
[ "\n The only thing that *should* happen in this function is\n 1. input sanitization for pandas\n 2. classification/reclassification.\n\n Using their __init__ methods, all classifiers can re-classify given\n different input parameters or additional data.\n\n If you've got a ...
Please provide a description of the function:def make(cls, *args, **kwargs): # only flag overrides return flag to_annotate = copy.deepcopy(kwargs) return_object = kwargs.pop('return_object', False) return_bins = kwargs.pop('return_bins', False) return_counts = kwargs.po...
[ "\n Configure and create a classifier that will consume data and produce\n classifications, given the configuration options specified by this\n function.\n\n Note that this like a *partial application* of the relevant class\n constructor. `make` creates a function that returns cla...
Please provide a description of the function:def get_tss(self): tss = 0 for class_def in self.classes: if len(class_def) > 0: yc = self.y[class_def] css = yc - yc.mean() css *= css tss += sum(css) return tss
[ "\n Total sum of squares around class means\n\n Returns sum of squares over all class means\n " ]
Please provide a description of the function:def get_adcm(self): adcm = 0 for class_def in self.classes: if len(class_def) > 0: yc = self.y[class_def] yc_med = np.median(yc) ycd = np.abs(yc - yc_med) adcm += sum(ycd) ...
[ "\n Absolute deviation around class median (ADCM).\n\n Calculates the absolute deviations of each observation about its class\n median as a measure of fit for the classification method.\n\n Returns sum of ADCM over all classes\n " ]
Please provide a description of the function:def get_gadf(self): adam = (np.abs(self.y - np.median(self.y))).sum() gadf = 1 - self.adcm / adam return gadf
[ "\n Goodness of absolute deviation of fit\n " ]
Please provide a description of the function:def find_bin(self, x): x = np.asarray(x).flatten() right = np.digitize(x, self.bins, right=True) if right.max() == len(self.bins): right[right == len(self.bins)] = len(self.bins) - 1 return right
[ "\n Sort input or inputs according to the current bin estimate\n\n Parameters\n ----------\n x : array or numeric\n a value or array of values to fit within the estimated\n bins\n\n Returns\n -------\n a bin index or arra...
Please provide a description of the function:def update(self, y=None, inplace=False, **kwargs): kwargs.update({'k': kwargs.pop('k', self.k)}) kwargs.update({'pct': kwargs.pop('pct', self.pct)}) kwargs.update({'truncate': kwargs.pop('truncate', self._truncated)}) if inplace: ...
[ "\n Add data or change classification parameters.\n\n Parameters\n ----------\n y : array\n (n,1) array of data to classify\n inplace : bool\n whether to conduct the update in place or to return a\n ...
Please provide a description of the function:def _ss(self, class_def): yc = self.y[class_def] css = yc - yc.mean() css *= css return sum(css)
[ "calculates sum of squares for a class" ]
Please provide a description of the function:def _swap(self, class1, class2, a): ss1 = self._ss(class1) ss2 = self._ss(class2) tss1 = ss1 + ss2 class1c = copy.copy(class1) class2c = copy.copy(class2) class1c.remove(a) class2c.append(a) ss1 = self....
[ "evaluate cost of moving a from class1 to class2" ]
Please provide a description of the function:def get_bounding_box_list(input_doc_fname, input_doc, full_page_box_list, set_of_page_nums_to_crop, argparse_args, chosen_PdfFileWriter): global args, page_nums_to_crop, PdfFileWriter args = argparse_args # Make args available to all funs ...
[ "Calculate a bounding box for each page in the document. The first\n argument is the filename of the document's original PDF file, the second is\n the PdfFileReader for the document. The argument full_page_box_list is a list\n of the full-page-size boxes (which is used to correct for any nonzero origins\...
Please provide a description of the function:def correct_bounding_box_list_for_nonzero_origin(bbox_list, full_box_list): corrected_box_list = [] for bbox, full_box in zip(bbox_list, full_box_list): left_x = full_box[0] lower_y = full_box[1] corrected_box_list.append([bbox[0]+left_x...
[ "The bounding box calculated from an image has coordinates relative to the\n lower-left point in the PDF being at zero. Similarly, Ghostscript reports a\n bounding box relative to a zero lower-left point. If the MediaBox (or full\n page box) has been shifted, like when cropping a previously cropped\n ...
Please provide a description of the function:def get_bounding_box_list_render_image(pdf_file_name, input_doc): program_to_use = "pdftoppm" # default to pdftoppm if args.gsRender: program_to_use = "Ghostscript" # Threshold value set in range 0-255, where 0 is black, with 191 default. if not args.t...
[ "Calculate the bounding box list by directly rendering each page of the PDF as\n an image file. The MediaBox and CropBox values in input_doc should have\n already been set to the chosen page size before the rendering." ]
Please provide a description of the function:def render_pdf_file_to_image_files(pdf_file_name, output_filename_root, program_to_use): res_x = str(args.resX) res_y = str(args.resY) if program_to_use == "Ghostscript": if ex.system_os == "Windows": # Windows PIL is more likely to know BMP ...
[ "Render all the pages of the PDF file at pdf_file_name to image files with\n path and filename prefix given by output_filename_root. Any directories must\n have already been created, and the calling program is responsible for\n deleting any directories or image files. The program program_to_use,\n cur...
Please provide a description of the function:def calculate_bounding_box_from_image(im, curr_page): xMax, y_max = im.size bounding_box = im.getbbox() # note this uses ltrb convention if not bounding_box: #print("\nWarning: could not calculate a bounding box for this page." # "\nAn e...
[ "This function uses a PIL routine to get the bounding box of the rendered\n image." ]
Please provide a description of the function:def get_temporary_filename(extension="", use_program_temp_dir=True): dir_name = None # uses the regular system temp dir if None if use_program_temp_dir: dir_name = program_temp_directory tmp_output_file = tempfile.NamedTemporaryFile(delete=False, ...
[ "Return the string for a temporary file with the given extension or suffix. For a\n file extension like .pdf the dot should also be in the passed string. Caller is\n expected to open and close it as necessary and call os.remove on it after\n finishing with it. (Note the entire programTempDir will be del...
Please provide a description of the function:def get_canonical_absolute_expanded_path(path): return os.path.normcase( os.path.normpath( os.path.realpath( # remove any symbolic links os.path.abspath( # may not be needed with realpath, to be safe ...
[ "Get the canonical form of the absolute path from a possibly relative path\n (which may have symlinks, etc.)" ]
Please provide a description of the function:def samefile(path1, path2): if system_os == "Linux" or system_os == "Cygwin": return os.path.samefile(path1, path2) return (get_canonical_absolute_expanded_path(path1) == get_canonical_absolute_expanded_path(path2))
[ "Test if paths refer to the same file or directory." ]
Please provide a description of the function:def get_parent_directory(path): if not os.path.isdir(path): path = os.path.dirname(path) return os.path.abspath(os.path.join(path, os.path.pardir))
[ "Like os.path.dirname except it returns the absolute name of the parent\n of the dirname directory. No symbolic link expansion (os.path.realpath)\n or user expansion (os.path.expanduser) is done." ]
Please provide a description of the function:def glob_if_windows_os(path, exact_num_args=False): if system_os != "Windows": return [path] globbed = glob.glob(path) if not globbed: print("\nWarning in pdfCropMargins: The wildcards in the path\n " + path + "\nfailed to expand. Tr...
[ "Expands any globbing if system_os is Windows (DOS doesn't do it). The\n argument exactNumFiles can be set to an integer to check for an exact\n number of matching files. Returns a list." ]
Please provide a description of the function:def convert_windows_path_to_cygwin(path): if len(path) > 2 and path[1] == ":" and path[2] == "\\": newpath = cygwin_full_path_prefix + "/" + path[0] if len(path) > 3: newpath += "/" + path[3:] path = newpath path = path.replace("\\", "/")...
[ "Convert a Windows path to a Cygwin path. Just handles the basic case." ]
Please provide a description of the function:def remove_program_temp_directory(): if os.path.exists(program_temp_directory): max_retries = 3 curr_retries = 0 time_between_retries = 1 while True: try: shutil.rmtree(program_temp_directory) ...
[ "Remove the global temp directory and all its contents." ]
Please provide a description of the function:def get_external_subprocess_output(command_list, print_output=False, indent_string="", split_lines=True, ignore_called_process_errors=False, env=None): # Note ghostscript bounding box output writes to stderr! So we need to # be sure to ca...
[ "Run the command and arguments in the command_list. Will search the system\n PATH. Returns the output as a list of lines. If print_output is True the\n output is echoed to stdout, indented (or otherwise prefixed) by indent_string.\n Waits for command completion. Called process errors can be set to be\...
Please provide a description of the function:def call_external_subprocess(command_list, stdin_filename=None, stdout_filename=None, stderr_filename=None, env=None): if stdin_filename: stdin = open(stdin_filename, "r") else: stdin = None if stdout_filename: ...
[ "Run the command and arguments in the command_list. Will search the system\n PATH for commands to execute, but no shell is started. Redirects any selected\n outputs to the given filename. Waits for command completion." ]
Please provide a description of the function:def run_external_subprocess_in_background(command_list, env=None): if system_os == "Windows": DETACHED_PROCESS = 0x00000008 p = subprocess.Popen(command_list, shell=False, stdin=None, stdout=None, stderr=None, close_fds=True, creation...
[ "Runs the command and arguments in the list as a background process." ]
Please provide a description of the function:def function_call_with_timeout(fun_name, fun_args, secs=5): from multiprocessing import Process, Queue p = Process(target=fun_name, args=tuple(fun_args)) p.start() curr_secs = 0 no_timeout = False if secs == 0: no_timeout = True else: timeout...
[ "Run a Python function with a timeout. No interprocess communication or\n return values are handled. Setting secs to 0 gives infinite timeout." ]
Please provide a description of the function:def fix_pdf_with_ghostscript_to_tmp_file(input_doc_fname): if not gs_executable: init_and_test_gs_executable(exit_on_fail=True) temp_file_name = get_temporary_filename(extension=".pdf") gs_run_command = [gs_executable, "-dSAFER", "-o", temp_file_name, ...
[ "Attempt to fix a bad PDF file with a Ghostscript command, writing the output\n PDF to a temporary file and returning the filename. Caller is responsible for\n deleting the file." ]
Please provide a description of the function:def get_bounding_box_list_ghostscript(input_doc_fname, res_x, res_y, full_page_box): if not gs_executable: init_and_test_gs_executable(exit_on_fail=True) res = str(res_x) + "x" + str(res_y) box_arg = "-dUseMediaBox" # should be default, but set anyway i...
[ "Call Ghostscript to get the bounding box list. Cannot set a threshold\n with this method." ]
Please provide a description of the function:def render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name, root_output_file_path, res_x=150, res_y=150, extra_args=None): if extra_args is None: extra_args = [] if not pdftoppm_executable: init_and_test_pd...
[ "Use the pdftoppm program to render a PDF file to .png images. The\n root_output_file_path is prepended to all the output files, which have numbers\n and extensions added. Extra arguments can be passed as a list in extra_args.\n Return the command output." ]
Please provide a description of the function:def render_pdf_file_to_image_files_pdftoppm_pgm(pdf_file_name, root_output_file_path, res_x=150, res_y=150): comm_output = render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name, ...
[ "Same as renderPdfFileToImageFile_pdftoppm_ppm but with -gray option for pgm." ]
Please provide a description of the function:def render_pdf_file_to_image_files__ghostscript_png(pdf_file_name, root_output_file_path, res_x=150, res_y=150): # For gs commands see # http://ghostscript.co...
[ "Use Ghostscript to render a PDF file to .png images. The root_output_file_path\n is prepended to all the output files, which have numbers and extensions added.\n Return the command output." ]
Please provide a description of the function:def show_preview(viewer_path, pdf_file_name): try: cmd = [viewer_path, pdf_file_name] run_external_subprocess_in_background(cmd) except (subprocess.CalledProcessError, OSError, IOError) as e: print("\nWarning from pdfCropMargins: The argu...
[ "Run the PDF viewer at the path viewer_path on the file pdf_file_name." ]
Please provide a description of the function:def main(): cleanup_and_exit = sys.exit # Function to do cleanup and exit before the import. exit_code = 0 # Imports are done here inside the try block so some ugly (and useless) # traceback info is avoided on user's ^C (KeyboardInterrupt, EOFError on ...
[ "Run main, catching any exceptions and cleaning up the temp directories." ]
Please provide a description of the function:def generate_default_filename(infile_path, is_cropped_file=True): if is_cropped_file: suffix = prefix = args.stringCropped else: suffix = prefix = args.stringUncropped # Use modified basename as output path; program writes default output to CWD. file_n...
[ "Generate the name of the default output file from the name of the input\n file. The is_cropped_file boolean is used to indicate that the file has been\n (or will be) cropped, to determine which filename-modification string to\n use. Function assumes that args has been set globally by argparse." ]
Please provide a description of the function:def intersect_boxes(box1, box2): if not box1 and not box2: return None if not box1: return box2 if not box2: return box1 intersect = RectangleObject([0, 0, 0, 0]) # Note [llx,lly,urx,ury] == [l,b,r,t] intersect.upperRight = (min(box1.upperRight[0], b...
[ "Takes two pyPdf boxes (such as page.mediaBox) and returns the pyPdf\n box which is their intersection." ]
Please provide a description of the function:def mod_box_for_rotation(box, angle, undo=False): def rotate_ninety_degrees_clockwise(box, n): if n == 0: return box box = rotate_ninety_degrees_clockwise(box, n-1) return [box[1], box[2], box[3], box[0]] # These are for clockwise, swap...
[ "The user sees left, bottom, right, and top margins on a page, but inside\n the PDF and in pyPdf the page may be rotated (such as in landscape mode).\n In the case of 90 degree clockwise rotation the left really modifies the\n top, the top really modifies right, and so forth. In order for the options\n ...
Please provide a description of the function:def get_full_page_box_assigning_media_and_crop(page): # Find the page rotation angle (degrees). # Note rotation is clockwise, and four values are allowed: 0 90 180 270 try: rotation = page["/Rotate"].getObject() # this works, needs try #rota...
[ "This returns whatever PDF box was selected (by the user option\n '--fullPageBox') to represent the full page size. All cropping is done\n relative to this box. The default selection option is the MediaBox\n intersected with the CropBox so multiple crops work as expected. The\n argument page should b...
Please provide a description of the function:def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False): full_page_box_list = [] rotation_list = [] if args.verbose and not quiet: print("\nOriginal full page sizes, in PDF format (lbrt):") for page_num in range(input_doc.g...
[ "Get a list of all the full-page box values for each page. The argument\n input_doc should be a PdfFileReader object. The boxes on the list are in the\n simple 4-float list format used by this program, not RectangleObject format." ]
Please provide a description of the function:def calculate_crop_list(full_page_box_list, bounding_box_list, angle_list, page_nums_to_crop): # Definition: the deltas are the four differences, one for each margin, # between the original full pag...
[ "Given a list of full-page boxes (media boxes) and a list of tight\n bounding boxes for each page, calculate and return another list giving the\n list of bounding boxes to crop down to. The parameter `angle_list` is\n a list of rotation angles which correspond to the pages. The pages\n selected to cro...
Please provide a description of the function:def set_cropped_metadata(input_doc, output_doc, metadata_info): # Setting metadata with pyPdf requires low-level pyPdf operations, see # http://stackoverflow.com/questions/2574676/change-metadata-of-pdf-file-with-pypdf if not metadata_info: # In cas...
[ "Set the metadata for the output document. Mostly just copied over, but\n \"Producer\" has a string appended to indicate that this program modified the\n file. That allows for the undo operation to make sure that this\n program cropped the file in the first place." ]
Please provide a description of the function:def apply_crop_list(crop_list, input_doc, page_nums_to_crop, already_cropped_by_this_program): if args.restore and not already_cropped_by_this_program: print("\nWarning from pdfCropMargins: The Producer string indic...
[ "Apply the crop list to the pages of the input PdfFileReader object." ]
Please provide a description of the function:def setup_output_document(input_doc, tmp_input_doc, metadata_info, copy_document_catalog=True): # NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters # seems to cause problems (writer can ha...
[ "Create the output `PdfFileWriter` objects and copy over the relevant info.", "This can expand some of the `IndirectObject` objects in a root object to\n see the actual values. Currently only used for debugging. May mess up the\n input doc and require a temporary one." ]
Please provide a description of the function:def main_crop(): ## ## Process some of the command-line arguments. ## if args.verbose: print("\nProcessing the PDF with pdfCropMargins (version", __version__+")...") print("System type:", ex.system_os) if len(args.pdf_input_doc) > ...
[ "This function does the real work. It is called by main() in\n pdfCropMargins.py, which just handles catching exceptions and cleaning up." ]
Please provide a description of the function:def parse_command_line_arguments(argparse_parser, init_indent=5, subs_indent=5, line_width=76): # Redirect stdout and stderr to prettify help or usage output from argparse. old_stdout = sys.stdout # save stdout old_stderr = s...
[ "Main routine to call to execute the command parsing. Returns an object\n from argparse's parse_args() routine." ]
Please provide a description of the function:def write(self, s): pretty_str = s for pair in self.help_string_replacement_pairs: pretty_str = pretty_str.replace(pair[0], pair[1]) # Define ^^s as the bell control char for now, so fill will treat it right. pretty_str = ...
[ "First preprocess the string `s` to prettify it (assuming it is argparse\n help output). Then write the result to the outstream associated with the\n class.", "Fill function for regexp to apply to ^^f matches." ]
Please provide a description of the function:def get_static_folder(app_or_blueprint): if not hasattr(app_or_blueprint, 'static_folder'): # I believe this is for app objects in very old Flask # versions that did not support custom static folders. return path.join(app_or_blueprint.root_pa...
[ "Return the static folder of the given Flask app\n instance, or module/blueprint.\n\n In newer Flask versions this can be customized, in older\n ones (<=0.6) the folder is fixed.\n " ]
Please provide a description of the function:def setdefault(self, key, value): try: super(FlaskConfigStorage, self).setdefault(key, value) except RuntimeError: self._defaults.__setitem__(key, value)
[ "We may not always be connected to an app, but we still need\n to provide a way to the base environment to set it's defaults.\n " ]
Please provide a description of the function:def split_prefix(self, ctx, item): app = ctx._app try: if hasattr(app, 'blueprints'): blueprint, name = item.split('/', 1) directory = get_static_folder(app.blueprints[blueprint]) endpoint =...
[ "See if ``item`` has blueprint prefix, return (directory, rel_path).\n " ]
Please provide a description of the function:def convert_item_to_flask_url(self, ctx, item, filepath=None): if ctx.environment._app.config.get("FLASK_ASSETS_USE_S3"): try: from flask_s3 import url_for except ImportError as e: print("You must have ...
[ "Given a relative reference like `foo/bar.css`, returns\n the Flask static url. By doing so it takes into account\n blueprints, i.e. in the aformentioned example,\n ``foo`` may reference a blueprint.\n\n If an absolute path is given via ``filepath``, it will be\n used instead. Thi...
Please provide a description of the function:def _app(self): if self.app is not None: return self.app ctx = _request_ctx_stack.top if ctx is not None: return ctx.app try: from flask import _app_ctx_stack app_ctx = _app_ctx_stack....
[ "The application object to work with; this is either the app\n that we have been bound to, or the current application.\n " ]
Please provide a description of the function:def from_yaml(self, path): bundles = YAMLLoader(path).load_bundles() for name in bundles: self.register(name, bundles[name])
[ "Register bundles from a YAML configuration file" ]
Please provide a description of the function:def from_module(self, path): bundles = PythonLoader(path).load_bundles() for name in bundles: self.register(name, bundles[name])
[ "Register bundles from a Python module" ]
Please provide a description of the function:def handle_unhandled_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): # call the default excepthook saved at __excepthook__ sys.__excepthook__(exc_type, exc_value, exc_traceback) return logger = l...
[ "Handler for unhandled exceptions that will write to the logs" ]
Please provide a description of the function:def write_transcriptions(utterances: List[Utterance], tgt_dir: Path, ext: str, lazy: bool) -> None: tgt_dir.mkdir(parents=True, exist_ok=True) for utter in utterances: out_path = tgt_dir / "{}.{}".format(utter.prefix, ext) ...
[ " Write the utterance transcriptions to files in the tgt_dir. Is lazy and\n checks if the file already exists.\n\n Args:\n utterances: A list of Utterance objects to be written.\n tgt_dir: The directory in which to write the text of the utterances,\n one file per utterance.\n e...
Please provide a description of the function:def remove_duplicates(utterances: List[Utterance]) -> List[Utterance]: filtered_utters = [] utter_set = set() # type: Set[Tuple[int, int, str]] for utter in utterances: if (utter.start_time, utter.end_time, utter.text) in utter_set: cont...
[ " Removes utterances with the same start_time, end_time and text. Other\n metadata isn't considered.\n " ]
Please provide a description of the function:def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: return [utter for utter in utterances if utter.text.strip() != ""]
[ "Remove empty utterances from a list of utterances\n Args:\n utterances: The list of utterance we are processing\n " ]
Please provide a description of the function:def total_duration(utterances: List[Utterance]) -> int: return sum([duration(utter) for utter in utterances])
[ "Get the duration of an entire list of utterances in milliseconds\n Args:\n utterances: The list of utterance we are finding the duration of\n " ]
Please provide a description of the function:def make_speaker_utters(utterances: List[Utterance]) -> Dict[str, List[Utterance]]: speaker_utters = defaultdict(list) # type: DefaultDict[str, List[Utterance]] for utter in utterances: speaker_utters[utter.speaker].append(utter) return speaker_utt...
[ " Creates a dictionary mapping from speakers to their utterances. " ]
Please provide a description of the function:def speaker_durations(utterances: List[Utterance]) -> List[Tuple[str, int]]: speaker_utters = make_speaker_utters(utterances) speaker_duration_tuples = [] # type: List[Tuple[str, int]] for speaker in speaker_utters: speaker_duration_tuples.append((...
[ " Takes a list of utterances and itemizes them by speaker, returning a\n list of tuples of the form (Speaker Name, duration).\n " ]
Please provide a description of the function:def remove_too_short(utterances: List[Utterance], _winlen=25, winstep=10) -> List[Utterance]: def is_too_short(utterance: Utterance) -> bool: charlen = len(utterance.text) if (duration(utterance) / winstep) < charlen: ...
[ " Removes utterances that will probably have issues with CTC because of\n the number of frames being less than the number of tokens in the\n transcription. Assuming char tokenization to minimize false negatives.\n " ]
Please provide a description of the function:def min_edit_distance( source: Sequence[T], target: Sequence[T], ins_cost: Callable[..., int] = lambda _x: 1, del_cost: Callable[..., int] = lambda _x: 1, sub_cost: Callable[..., int] = lambda x, y: 0 if x == y else 1) -> int: # Init...
[ "Calculates the minimum edit distance between two sequences.\n\n Uses the Levenshtein weighting as a default, but offers keyword arguments\n to supply functions to measure the costs for editing with different\n elements.\n\n Args:\n ins_cost: A function describing the cost of inserting a given ch...
Please provide a description of the function:def min_edit_distance_align( # TODO Wrangle the typing errors in this function. # TODO This could work on generic sequences but for now it relies on # empty strings. #source: Sequence[str], target: Sequence[str], #ins_cost: Callable[.....
[ "Finds a minimum cost alignment between two strings.\n\n Uses the Levenshtein weighting as a default, but offers keyword arguments\n to supply functions to measure the costs for editing with different\n characters. Note that the alignment may not be unique.\n\n Args:\n ins_cost: A function descri...
Please provide a description of the function:def cluster_alignment_errors(alignment): # TODO Review documentation and consider for inclusion in API. newalign = [] mistakes = ([],[]) for align_item in alignment: if align_item[0] == align_item[1]: if mistakes != ([],[]): ...
[ "Clusters alignments\n Takes an alignment created by min_edit_distance_align() and groups\n consecutive errors together. This is useful, because there are often\n many possible alignments, and so often we can't meaningfully distinguish\n between alignment errors at the character level, so it makes many-...
Please provide a description of the function:def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float: if len(ref) == 0: raise EmptyReferenceException( "Cannot calculating word error rate against a length 0 "\ "reference sequence.") distance = min_edit_distance(ref...
[ " Calculate the word error rate of a sequence against a reference.\n\n Args:\n ref: The gold-standard reference sequence\n hyp: The hypothesis to be evaluated against the reference.\n\n Returns:\n The word error rate of the supplied hypothesis with respect to the\n reference string...
Please provide a description of the function:def load_metagraph(model_path_prefix: Union[str, Path]) -> tf.train.Saver: model_path_prefix = str(model_path_prefix) metagraph = tf.train.import_meta_graph(model_path_prefix + ".meta") return metagraph
[ " Given the path to a model on disk (these will typically be found in\n directories such as exp/<exp_num>/model/model_best.*) creates a Saver\n object that can then be used to restore the graph inside a tf.Session.\n " ]
Please provide a description of the function:def dense_to_human_readable(dense_repr: Sequence[Sequence[int]], index_to_label: Dict[int, str]) -> List[List[str]]: transcripts = [] for dense_r in dense_repr: non_empty_phonemes = [phn_i for phn_i in dense_r if phn_i != 0] transcript = [index_...
[ " Converts a dense representation of model decoded output into human\n readable, using a mapping from indices to labels. " ]
Please provide a description of the function:def decode(model_path_prefix: Union[str, Path], input_paths: Sequence[Path], label_set: Set[str], *, feature_type: str = "fbank", #TODO Make this None and infer feature_type from dimension of NN input layer. batch_size: ...
[ "Use an existing tensorflow model that exists on disk to decode\n WAV files.\n\n Args:\n model_path_prefix: The path to the saved tensorflow model.\n This is the full prefix to the \".ckpt\" file.\n input_paths: A sequence of `pathlib.Path`s to WAV files to put through\...
Please provide a description of the function:def transcribe(self, restore_model_path: Optional[str]=None) -> None: saver = tf.train.Saver() with tf.Session(config=allow_growth_config) as sess: if restore_model_path: saver.restore(sess, restore_model_path) ...
[ " Transcribes an untranscribed dataset. Similar to eval() except\n no reference translation is assumed, thus no LER is calculated.\n " ]
Please provide a description of the function:def eval(self, restore_model_path: Optional[str]=None) -> None: saver = tf.train.Saver() with tf.Session(config=allow_growth_config) as sess: if restore_model_path: logger.info("restoring model from %s", restore_model_pat...
[ " Evaluates the model on a test set." ]
Please provide a description of the function:def output_best_scores(self, best_epoch_str: str) -> None: BEST_SCORES_FILENAME = "best_scores.txt" with open(os.path.join(self.exp_dir, BEST_SCORES_FILENAME), "w", encoding=ENCODING) as best_f: print(best_epoch_str, fil...
[ "Output best scores to the filesystem" ]
Please provide a description of the function:def train(self, early_stopping_steps: int = 10, min_epochs: int = 30, max_valid_ler: float = 1.0, max_train_ler: float = 0.3, max_epochs: int = 100, restore_model_path: Optional[str]=None, epoch_callback: Optional[Callable[[Dict], No...
[ " Train the model.\n\n min_epochs: minimum number of epochs to run training for.\n max_epochs: maximum number of epochs to run training for.\n early_stopping_steps: Stop training after this number of steps\n if no LER improvement has been made.\n ...
Please provide a description of the function:def ensure_no_set_overlap(train: Sequence[str], valid: Sequence[str], test: Sequence[str]) -> None: logger.debug("Ensuring that the training, validation and test data sets have no overlap") train_s = set(train) valid_s = set(valid) test_s = set(test) ...
[ " Ensures no test set data has creeped into the training set." ]
Please provide a description of the function:def find_untranscribed_wavs(wav_path: Path, transcription_path: Path, label_type: str) -> List[str]: audio_files = wav_path.glob("**/*.wav") transcription_files = transcription_path.glob("**/*.{}".format(label_type)) transcription_file_prefixes = [t_file.st...
[ "Find the prefixes for all the wav files that do not have an associated transcription\n Args:\n wav_path: Path to search for wav files in\n transcription_path: Path to search for transcriptions in\n label_type: The type of labels for transcriptions. Eg \"phonemes\" \"phonemes_and_tones\"\n ...
Please provide a description of the function:def get_untranscribed_prefixes_from_file(target_directory: Path) -> List[str]: untranscribed_prefix_fn = target_directory / "untranscribed_prefixes.txt" if untranscribed_prefix_fn.exists(): with untranscribed_prefix_fn.open() as f: prefixes ...
[ "\n The file \"untranscribed_prefixes.txt\" will specify prefixes which\n do not have an associated transcription file if placed in the target directory.\n\n This will fetch those prefixes from that file and will return an empty\n list if that file does not exist.\n\n See find_untranscribed_wavs func...
Please provide a description of the function:def determine_labels(target_dir: Path, label_type: str) -> Set[str]: logger.info("Finding phonemes of type %s in directory %s", label_type, target_dir) label_dir = target_dir / "label/" if not label_dir.is_dir(): raise FileNotFoundError( ...
[ " Returns a set of all phonemes found in the corpus. Assumes that WAV files and\n label files are split into utterances and segregated in a directory which contains a\n \"wav\" subdirectory and \"label\" subdirectory.\n\n Arguments:\n target_dir: A `Path` to the directory where the corpus data is fo...
Please provide a description of the function:def from_elan(cls: Type[CorpusT], org_dir: Path, tgt_dir: Path, feat_type: str = "fbank", label_type: str = "phonemes", utterance_filter: Callable[[Utterance], bool] = None, label_segmenter: Optional[LabelSegmenter] = Non...
[ " Construct a `Corpus` from ELAN files.\n\n Args:\n org_dir: A path to the directory containing the unpreprocessed\n data.\n tgt_dir: A path to the directory where the preprocessed data will\n be stored.\n feat_type: A string describing the input...
Please provide a description of the function:def set_and_check_directories(self, tgt_dir: Path) -> None: logger.info("Setting up directories for corpus in %s", tgt_dir) # Check directories exist. if not tgt_dir.is_dir(): raise FileNotFoundError( "The directo...
[ "\n Make sure that the required directories exist in the target directory.\n set variables accordingly.\n " ]
Please provide a description of the function:def initialize_labels(self, labels: Set[str]) -> Tuple[dict, dict]: logger.debug("Creating mappings for labels") label_to_index = {label: index for index, label in enumerate( ["pad"] + sorted(list(labels)))} ...
[ "Create mappings from label to index and index to label" ]
Please provide a description of the function:def prepare_feats(self) -> None: logger.debug("Preparing input features") self.feat_dir.mkdir(parents=True, exist_ok=True) should_extract_feats = False for path in self.wav_dir.iterdir(): if not path.suffix == ".wav": ...
[ " Prepares input features" ]
Please provide a description of the function:def make_data_splits(self, max_samples: int) -> None: train_f_exists = self.train_prefix_fn.is_file() valid_f_exists = self.valid_prefix_fn.is_file() test_f_exists = self.test_prefix_fn.is_file() if train_f_exists and valid_f_exists...
[ " Splits the utterances into training, validation and test sets." ]
Please provide a description of the function:def divide_prefixes(prefixes: List[str], seed:int=0) -> Tuple[List[str], List[str], List[str]]: if len(prefixes) < 3: raise PersephoneException( "{} cannot be split into 3 groups as it only has {} items".format(prefixes, len(prefi...
[ "Divide data into training, validation and test subsets" ]
Please provide a description of the function:def indices_to_labels(self, indices: Sequence[int]) -> List[str]: return [(self.INDEX_TO_LABEL[index]) for index in indices]
[ " Converts a sequence of indices into their corresponding labels." ]