INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Used for class based definitions
def get_def_models(self, definition_filter=None): """ Used for class based definitions """ model_filter = definition_filter or (lambda tag: True) return { definition.name: definition.obj for definition in self.definition_models if model_filter(...
Decorator to add class based definitions
def definition(self, name, tags=None): """ Decorator to add class based definitions """ def wrapper(obj): self.definition_models.append(SwaggerDefinition(name, obj, tags=tags)) return obj return w...
Register Flasgger views
def register_views(self, app): """ Register Flasgger views """ # Wrap the views in an arbitrary number of decorators. def wrap_view(view): if self.decorators: for decorator in self.decorators: view = decorator(view) ret...
Inject headers after request
def add_headers(self, app): """ Inject headers after request """ @app.after_request def after_request(response): # noqa for header, value in self.config.get('headers'): response.headers[header] = value return response
A decorator that is used to validate incoming requests data against a schema swagger = Swagger(app) @app.route('/pets', methods=['POST']) @swagger.validate('Pet') @swag_from("pet_post_endpoint.yml") def post(): return db.insert(reques...
def validate( self, schema_id, validation_function=None, validation_error_handler=None): """ A decorator that is used to validate incoming requests data against a schema swagger = Swagger(app) @app.route('/pets', methods=['POST']) @sw...
This method finds a schema known to Flasgger and returns it. :raise KeyError: when the specified :param schema_id: is not found by Flasgger :param schema_id: the id of the desired schema
def get_schema(self, schema_id): """ This method finds a schema known to Flasgger and returns it. :raise KeyError: when the specified :param schema_id: is not found by Flasgger :param schema_id: the id of the desired schema """ schema_specs = get_schema_specs(sc...
This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: '#/definitions/Task' - in: path name: todo_id required: true description: The ID of the task, try 42! ...
def put(self, todo_id): """ This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: '#/definitions/Task' - in: path name: todo_id required: true ...
This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: '#/definitions/Task' responses: 201: description: The task has been created schema: $ref: '#/de...
def post(self): """ This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: '#/definitions/Task' responses: 201: description: The task has been created ...
Example endpoint return a list of colors by palette This is using docstring for specifications --- tags: - colors parameters: - name: palette in: path type: string enum: ['all', 'rgb', 'cmyk'] required: true default: all description: Which pale...
def colors(palette): """Example endpoint return a list of colors by palette This is using docstring for specifications --- tags: - colors parameters: - name: palette in: path type: string enum: ['all', 'rgb', 'cmyk'] required: true default: all ...
Decorator to require HTTP Basic Auth for your endpoint.
def requires_basic_auth(f): """Decorator to require HTTP Basic Auth for your endpoint.""" def check_auth(username, password): return username == "guest" and password == "secret" def authenticate(): return Response( "Authentication required.", 401, {"WWW-Authenticate...
Scales the image to a given scale. :param image: :param scale: :return:
def __scale_image(image, scale: float): """ Scales the image to a given scale. :param image: :param scale: :return: """ height, width, _ = image.shape width_scaled = int(np.ceil(width * scale)) height_scaled = int(np.ceil(height * scale)) ...
Non Maximum Suppression. :param boxes: np array with bounding boxes. :param threshold: :param method: NMS method to apply. Available values ('Min', 'Union') :return:
def __nms(boxes, threshold, method): """ Non Maximum Suppression. :param boxes: np array with bounding boxes. :param threshold: :param method: NMS method to apply. Available values ('Min', 'Union') :return: """ if boxes.size == 0: return np.em...
Detects bounding boxes from the specified image. :param img: image to process :return: list containing all the bounding boxes detected with their keypoints.
def detect_faces(self, img) -> list: """ Detects bounding boxes from the specified image. :param img: image to process :return: list containing all the bounding boxes detected with their keypoints. """ if img is None or not hasattr(img, "shape"): raise Invalid...
First stage of the MTCNN. :param image: :param scales: :param stage_status: :return:
def __stage1(self, image, scales: list, stage_status: StageStatus): """ First stage of the MTCNN. :param image: :param scales: :param stage_status: :return: """ total_boxes = np.empty((0, 9)) status = stage_status for scale in scales: ...
Second stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :return:
def __stage2(self, img, total_boxes, stage_status:StageStatus): """ Second stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :return: """ num_boxes = total_boxes.shape[0] if num_boxes == 0: return total_boxes, st...
Third stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :return:
def __stage3(self, img, total_boxes, stage_status: StageStatus): """ Third stage of the MTCNN. :param img: :param total_boxes: :param stage_status: :return: """ num_boxes = total_boxes.shape[0] if num_boxes == 0: return total_boxes, np...
Creates a tensorflow variable with the given name and shape. :param name: name to set for the variable. :param shape: list defining the shape of the variable. :return: created TF variable.
def __make_var(self, name: str, shape: list): """ Creates a tensorflow variable with the given name and shape. :param name: name to set for the variable. :param shape: list defining the shape of the variable. :return: created TF variable. """ return tf.get_variabl...
Creates a feed layer. This is usually the first layer in the network. :param name: name of the layer :return:
def new_feed(self, name: str, layer_shape: tuple): """ Creates a feed layer. This is usually the first layer in the network. :param name: name of the layer :return: """ feed_data = tf.placeholder(tf.float32, layer_shape, 'input') self.__network.add_layer(name, la...
Creates a new prelu layer with the given name and input. :param name: name for this layer. :param input_layer_name: name of the layer that serves as input for this one.
def new_prelu(self, name: str, input_layer_name: str=None): """ Creates a new prelu layer with the given name and input. :param name: name for this layer. :param input_layer_name: name of the layer that serves as input for this one. """ input_layer = self.__network.get_la...
Creates a convolution layer for the network. :param name: name for the layer :param kernel_size: tuple containing the size of the kernel (Width, Height) :param channels_output: ¿? Perhaps number of channels in the output? it is used as the bias size. :param stride_size: tuple containing ...
def new_conv(self, name: str, kernel_size: tuple, channels_output: int, stride_size: tuple, padding: str='SAME', group: int=1, biased: bool=True, relu: bool=True, input_layer_name: str=None): """ Creates a convolution layer for the network. :param name: name for...
Creates a new max pooling layer. :param name: name for the layer. :param kernel_size: tuple containing the size of the kernel (Width, Height) :param stride_size: tuple containing the size of the stride (Width, Height) :param padding: Type of padding. Available values are: ('SAME', 'VALID...
def new_max_pool(self, name:str, kernel_size: tuple, stride_size: tuple, padding='SAME', input_layer_name: str=None): """ Creates a new max pooling layer. :param name: name for the layer. :param kernel_size: tuple containing the size of the kernel (Width, Height) ...
Creates a new fully connected layer. :param name: name for the layer. :param output_count: number of outputs of the fully connected layer. :param relu: boolean flag to set if ReLu should be applied at the end of this layer. :param input_layer_name: name of the input layer for this layer...
def new_fully_connected(self, name: str, output_count: int, relu=True, input_layer_name: str=None): """ Creates a new fully connected layer. :param name: name for the layer. :param output_count: number of outputs of the fully connected layer. :param relu: boolean flag to set if ...
Creates a new softmax layer :param name: name to set for the layer :param axis: :param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of the network.
def new_softmax(self, name, axis, input_layer_name: str=None): """ Creates a new softmax layer :param name: name to set for the layer :param axis: :param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of the network. ...
Adds a layer to the network. :param name: name of the layer to add :param layer_output: output layer.
def add_layer(self, name: str, layer_output): """ Adds a layer to the network. :param name: name of the layer to add :param layer_output: output layer. """ self.__layers[name] = layer_output self.__last_layer_name = name
Retrieves the layer by its name. :param name: name of the layer to retrieve. If name is None, it will retrieve the last added layer to the network. :return: layer output
def get_layer(self, name: str=None): """ Retrieves the layer by its name. :param name: name of the layer to retrieve. If name is None, it will retrieve the last added layer to the network. :return: layer output """ if name is None: name = self.__last_l...
Sets the weights values of the network. :param weights_values: dictionary with weights for each layer
def set_weights(self, weights_values: dict, ignore_missing=False): """ Sets the weights values of the network. :param weights_values: dictionary with weights for each layer """ network_name = self.__class__.__name__.lower() with tf.variable_scope(network_name): ...
Feeds the network with an image :param image: image (perhaps loaded with CV2) :return: network result
def feed(self, image): """ Feeds the network with an image :param image: image (perhaps loaded with CV2) :return: network result """ network_name = self.__class__.__name__.lower() with tf.variable_scope(network_name): return self._feed(image)
Helper function: relinks soft symbolic link if necessary
def re_symlink(input_file, soft_link_name, log=None): """ Helper function: relinks soft symbolic link if necessary """ input_file = os.fspath(input_file) soft_link_name = os.fspath(soft_link_name) if log is None: prdebug = partial(print, file=sys.stderr) else: prdebug = log.d...
Intentionally racy test if target is writable. We intend to write to the output file if and only if we succeed and can replace it atomically. Before doing the OCR work, make sure the location is writable.
def is_file_writable(test_file): """Intentionally racy test if target is writable. We intend to write to the output file if and only if we succeed and can replace it atomically. Before doing the OCR work, make sure the location is writable. """ p = Path(test_file) if p.is_symlink(): ...
Create a Postscript pdfmark file for Ghostscript PDF/A conversion A pdfmark file is a small Postscript program that provides some information Ghostscript needs to perform PDF/A conversion. The only information we put in specifies that we want the file to be a PDF/A, and we want to Ghostscript to conver...
def generate_pdfa_ps(target_filename, icc='sRGB'): """Create a Postscript pdfmark file for Ghostscript PDF/A conversion A pdfmark file is a small Postscript program that provides some information Ghostscript needs to perform PDF/A conversion. The only information we put in specifies that we want the fi...
Determines if the file claims to be PDF/A compliant This only checks if the XMP metadata contains a PDF/A marker. It does not do full PDF/A validation.
def file_claims_pdfa(filename): """Determines if the file claims to be PDF/A compliant This only checks if the XMP metadata contains a PDF/A marker. It does not do full PDF/A validation. """ with pikepdf.open(filename) as pdf: pdfmeta = pdf.open_metadata() if not pdfmeta.pdfa_statu...
Fix pdfminer's name2unicode function Font cids that are mapped to names of the form /g123 seem to be, by convention characters with no corresponding Unicode entry. These can be subsetted fonts or symbolic fonts. There seems to be no way to map /g123 fonts to Unicode, barring a ToUnicode data structure.
def name2unicode(name): """Fix pdfminer's name2unicode function Font cids that are mapped to names of the form /g123 seem to be, by convention characters with no corresponding Unicode entry. These can be subsetted fonts or symbolic fonts. There seems to be no way to map /g123 fonts to Unicode, barr...
Check if characters can be combined into a textline We consider characters compatible if: - the Unicode mapping is known, and both have the same render mode - the Unicode mapping is unknown but both are part of the same font
def is_compatible(self, obj): """Check if characters can be combined into a textline We consider characters compatible if: - the Unicode mapping is known, and both have the same render mode - the Unicode mapping is unknown but both are part of the same font """ b...
Destroy some cdata
def _destroy(cls, cdata): """Destroy some cdata""" # Leptonica API uses double-pointers for its destroy APIs to prevent # dangling pointers. This means we need to put our single pointer, # cdata, in a temporary CDATA**. pp = ffi.new('{} **'.format(cls.LEPTONICA_TYPENAME), cdata) ...
iPython display hook returns png version of image
def _repr_png_(self): """iPython display hook returns png version of image """ data = ffi.new('l_uint8 **') size = ffi.new('size_t *') err = lept.pixWriteMemPng(data, size, self._cdata, 0) if err != 0: raise LeptonicaIOError("pixWriteMemPng") ...
Load an image file into a PIX object. Leptonica can load TIFF, PNM (PBM, PGM, PPM), PNG, and JPEG. If loading fails then the object will wrap a C null pointer.
def open(cls, path): """Load an image file into a PIX object. Leptonica can load TIFF, PNM (PBM, PGM, PPM), PNG, and JPEG. If loading fails then the object will wrap a C null pointer. """ filename = fspath(path) with _LeptonicaErrorTrap(): return cls(lept.pi...
Write pix to the filename, with the extension indicating format. jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default) jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive)
def write_implied_format(self, path, jpeg_quality=0, jpeg_progressive=0): """Write pix to the filename, with the extension indicating format. jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default) jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive) """ fil...
Create a copy of a PIL.Image from this Pix
def frompil(self, pillow_image): """Create a copy of a PIL.Image from this Pix""" bio = BytesIO() pillow_image.save(bio, format='png', compress_level=1) py_buffer = bio.getbuffer() c_buffer = ffi.from_buffer(py_buffer) with _LeptonicaErrorTrap(): pix = Pix(lep...
Returns a PIL.Image version of this Pix
def topil(self): """Returns a PIL.Image version of this Pix""" from PIL import Image # Leptonica manages data in words, so it implicitly does an endian # swap. Tell Pillow about this when it reads the data. pix = self if sys.byteorder == 'little': if self.mo...
Returns the deskewed pix object. A clone of the original is returned when the algorithm cannot find a skew angle with sufficient confidence. reduction_factor -- amount to downsample (0 for default) when searching for skew angle
def deskew(self, reduction_factor=0): """Returns the deskewed pix object. A clone of the original is returned when the algorithm cannot find a skew angle with sufficient confidence. reduction_factor -- amount to downsample (0 for default) when searching for skew angle ...
Returns the pix object rescaled according to the proportions given.
def scale(self, scale_xy): "Returns the pix object rescaled according to the proportions given." with _LeptonicaErrorTrap(): return Pix(lept.pixScale(self._cdata, scale_xy[0], scale_xy[1]))
Orthographic rotation, quads: 0-3, number of clockwise rotations
def rotate_orth(self, quads): "Orthographic rotation, quads: 0-3, number of clockwise rotations" with _LeptonicaErrorTrap(): return Pix(lept.pixRotateOrth(self._cdata, quads))
Returns a tuple (deskew angle in degrees, confidence value). Returns (None, None) if no angle is available.
def find_skew(self): """Returns a tuple (deskew angle in degrees, confidence value). Returns (None, None) if no angle is available. """ with _LeptonicaErrorTrap(): angle = ffi.new('float *', 0.0) confidence = ffi.new('float *', 0.0) result = lept.pixF...
Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_*
def remove_colormap(self, removal_type): """Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_* """ with _LeptonicaErrorTrap(): return Pix( lept.pixRemoveColormapGeneral(self._cdata, ...
Convert to PDF data, with transcoding
def generate_pdf_ci_data(self, type_, quality): "Convert to PDF data, with transcoding" p_compdata = ffi.new('L_COMP_DATA **') result = lept.pixGenerateCIData(self._cdata, type_, quality, 0, p_compdata) if result != 0: raise LeptonicaError("Generate PDF data failed") ...
Open compressed data, without transcoding
def open(cls, path, jpeg_quality=75): "Open compressed data, without transcoding" filename = fspath(path) p_compdata = ffi.new('L_COMP_DATA **') result = lept.l_generateCIDataForPdf( os.fsencode(filename), ffi.NULL, jpeg_quality, p_compdata ) if result != 0: ...
Returns palette pre-formatted for use in PDF
def get_palette_pdf_string(self): "Returns palette pre-formatted for use in PDF" buflen = len('< ') + len(' rrggbb') * self._cdata.ncolors + len('>') buf = ffi.buffer(self._cdata.cmapdatahex, buflen) return bytes(buf)
Update this page's fonts with a reference to the Glyphless font
def _update_page_resources(*, page, font, font_key, procset): """Update this page's fonts with a reference to the Glyphless font""" if '/Resources' not in page: page['/Resources'] = pikepdf.Dictionary({}) resources = page['/Resources'] try: fonts = resources['/Font'] except KeyError...
Insert the text layer from text page 0 on to pdf_base at page_num
def _weave_layers_graft( *, pdf_base, page_num, text, font, font_key, procset, rotation, strip_old_text, log ): """Insert the text layer from text page 0 on to pdf_base at page_num""" log.debug("Grafting") if Path(text).stat().st_size == 0: return # This is a pointer indicating a specific ...
Copy a font from the filename text into pdf_base
def _find_font(text, pdf_base): """Copy a font from the filename text into pdf_base""" font, font_key = None, None possible_font_names = ('/f-0-0', '/F1') try: with pikepdf.open(text) as pdf_text: try: pdf_text_fonts = pdf_text.pages[0].Resources.get('/Font', {}) ...
Walk the table of contents, calling visitor_fn() at each node The /Outlines data structure is a messy data structure, but rather than navigating hierarchically we just track unique nodes. Enqueue nodes when we find them, and never visit them again. set() is awesome. We look for the two types of obje...
def _traverse_toc(pdf_base, visitor_fn, log): """ Walk the table of contents, calling visitor_fn() at each node The /Outlines data structure is a messy data structure, but rather than navigating hierarchically we just track unique nodes. Enqueue nodes when we find them, and never visit them again....
Repair the table of contents Whenever we replace a page wholesale, it gets assigned a new objgen number and other references to it within the PDF become invalid, most notably in the table of contents (/Outlines in PDF-speak). In weave_layers we collect pageref_remap, a mapping that describes the new o...
def _fix_toc(pdf_base, pageref_remap, log): """Repair the table of contents Whenever we replace a page wholesale, it gets assigned a new objgen number and other references to it within the PDF become invalid, most notably in the table of contents (/Outlines in PDF-speak). In weave_layers we collect ...
Apply text layer and/or image layer changes to baseline file This is where the magic happens. infiles will be the main PDF to modify, and optional .text.pdf and .image-layer.pdf files, organized however ruffus organizes them. From .text.pdf, we copy the content stream (which contains the Tesseract ...
def weave_layers(infiles, output_file, log, context): """Apply text layer and/or image layer changes to baseline file This is where the magic happens. infiles will be the main PDF to modify, and optional .text.pdf and .image-layer.pdf files, organized however ruffus organizes them. From .text.pdf,...
Validator for numeric params
def numeric(basetype, min_=None, max_=None): """Validator for numeric params""" min_ = basetype(min_) if min_ is not None else None max_ = basetype(max_) if max_ is not None else None def _numeric(string): value = basetype(string) if min_ is not None and value < min_ or max_ is not None...
Replace the elaborate ruffus stack trace with a user friendly description of the error message that occurred.
def do_ruffus_exception(ruffus_five_tuple, options, log): """Replace the elaborate ruffus stack trace with a user friendly description of the error message that occurred.""" exit_code = None _task_name, _job_name, exc_name, exc_value, exc_stack = ruffus_five_tuple if isinstance(exc_name, type): ...
Traverse a RethrownJobError and output the exceptions Ruffus presents exceptions as 5 element tuples. The RethrownJobException has a list of exceptions like e.job_exceptions = [(5-tuple), (5-tuple), ...] ruffus < 2.7.0 had a bug with exception marshalling that would give different output wheth...
def traverse_ruffus_exception(exceptions, options, log): """Traverse a RethrownJobError and output the exceptions Ruffus presents exceptions as 5 element tuples. The RethrownJobException has a list of exceptions like e.job_exceptions = [(5-tuple), (5-tuple), ...] ruffus < 2.7.0 had a bug with ...
Work around Python issue with multiprocessing forking on closed streams https://bugs.python.org/issue28326 Attempting to a fork/exec a new Python process when any of std{in,out,err} are closed or not flushable for some reason may raise an exception. Fix this by opening devnull if the handle seems to b...
def check_closed_streams(options): """Work around Python issue with multiprocessing forking on closed streams https://bugs.python.org/issue28326 Attempting to a fork/exec a new Python process when any of std{in,out,err} are closed or not flushable for some reason may raise an exception. Fix this b...
Try to find version signature at start of file. Not robust enough to deal with appended files. Returns empty string if not found, indicating file is probably not PDF.
def _pdf_guess_version(input_file, search_window=1024): """Try to find version signature at start of file. Not robust enough to deal with appended files. Returns empty string if not found, indicating file is probably not PDF. """ with open(input_file, 'rb') as f: signature = f.read(search...
Get zero-based page info implied by filename, e.g. 000002.pdf -> 1
def get_pageinfo(input_file, context): "Get zero-based page info implied by filename, e.g. 000002.pdf -> 1" pageno = page_number(input_file) - 1 pageinfo = context.get_pdfinfo()[pageno] return pageinfo
Get the DPI when nonsquare DPI is tolerable
def get_page_dpi(pageinfo, options): "Get the DPI when nonsquare DPI is tolerable" xres = max( pageinfo.xres or VECTOR_PAGE_DPI, options.oversample or 0, VECTOR_PAGE_DPI if pageinfo.has_vector else 0, ) yres = max( pageinfo.yres or VECTOR_PAGE_DPI, options.oversam...
Get the DPI when we require xres == yres, scaled to physical units
def get_page_square_dpi(pageinfo, options): "Get the DPI when we require xres == yres, scaled to physical units" xres = pageinfo.xres or 0 yres = pageinfo.yres or 0 userunit = pageinfo.userunit or 1 return float( max( (xres * userunit) or VECTOR_PAGE_DPI, (yres * user...
Get the DPI when we require xres == yres, in Postscript units
def get_canvas_square_dpi(pageinfo, options): """Get the DPI when we require xres == yres, in Postscript units""" return float( max( (pageinfo.xres) or VECTOR_PAGE_DPI, (pageinfo.yres) or VECTOR_PAGE_DPI, VECTOR_PAGE_DPI if pageinfo.has_vector else 0, opti...
Work out orientation correct for each page. We ask Ghostscript to draw a preview page, which will rasterize with the current /Rotate applied, and then ask Tesseract which way the page is oriented. If the value of /Rotate is correct (e.g., a user already manually fixed rotation), then Tesseract will say...
def orient_page(infiles, output_file, log, context): """ Work out orientation correct for each page. We ask Ghostscript to draw a preview page, which will rasterize with the current /Rotate applied, and then ask Tesseract which way the page is oriented. If the value of /Rotate is correct (e.g., a u...
Select the image we send for OCR. May not be the same as the display image depending on preprocessing. This image will never be shown to the user.
def select_ocr_image(infiles, output_file, log, context): """Select the image we send for OCR. May not be the same as the display image depending on preprocessing. This image will never be shown to the user.""" image = infiles[0] options = context.get_options() pageinfo = get_pageinfo(image, co...
Selects a whole page image that we can show the user (if necessary)
def select_visible_page_image(infiles, output_file, log, context): """Selects a whole page image that we can show the user (if necessary)""" options = context.get_options() if options.clean_final: image_suffix = '.pp-clean.png' elif options.deskew: image_suffix = '.pp-deskew.png' el...
Selects the image layer for the output page. If possible this is the orientation-corrected input page, or an image of the whole page converted to PDF.
def select_image_layer(infiles, output_file, log, context): """Selects the image layer for the output page. If possible this is the orientation-corrected input page, or an image of the whole page converted to PDF.""" options = context.get_options() page_pdf = next(ii for ii in infiles if ii.endswit...
Convert runs of qQ's in the stack into single graphobjs
def _normalize_stack(graphobjs): """Convert runs of qQ's in the stack into single graphobjs""" for operands, operator in graphobjs: operator = str(operator) if re.match(r'Q*q+$', operator): # Zero or more Q, one or more q for char in operator: # Split into individual ...
Interpret the PDF content stream. The stack represents the state of the PDF graphics stack. We are only interested in the current transformation matrix (CTM) so we only track this object; a full implementation would need to track many other items. The CTM is initialized to the mapping from user space...
def _interpret_contents(contentstream, initial_shorthand=UNIT_SQUARE): """Interpret the PDF content stream. The stack represents the state of the PDF graphics stack. We are only interested in the current transformation matrix (CTM) so we only track this object; a full implementation would need to trac...
Find inline images in the contentstream
def _find_inline_images(contentsinfo): "Find inline images in the contentstream" for n, inline in enumerate(contentsinfo.inline_images): yield ImageInfo( name='inline-%02d' % n, shorthand=inline.shorthand, inline=inline )
Given the transformation matrix and image size, find the image DPI. PDFs do not include image resolution information within image data. Instead, the PDF page content stream describes the location where the image will be rasterized, and the effective resolution is the ratio of the pixel size to raster t...
def _get_dpi(ctm_shorthand, image_size): """Given the transformation matrix and image size, find the image DPI. PDFs do not include image resolution information within image data. Instead, the PDF page content stream describes the location where the image will be rasterized, and the effective resolutio...
Search for all XObject-based images in the container Usually the container is a page, but it could also be a Form XObject that contains images. Filter out the Form XObjects which are dealt with elsewhere. Generate a sequence of tuples (image, xobj container), where container, where xobj is the nam...
def _image_xobjects(container): """Search for all XObject-based images in the container Usually the container is a page, but it could also be a Form XObject that contains images. Filter out the Form XObjects which are dealt with elsewhere. Generate a sequence of tuples (image, xobj container), whe...
Find images stored in the container's /Resources /XObject Usually the container is a page, but it could also be a Form XObject that contains images. Generates images with their DPI at time of drawing.
def _find_regular_images(container, contentsinfo): """Find images stored in the container's /Resources /XObject Usually the container is a page, but it could also be a Form XObject that contains images. Generates images with their DPI at time of drawing. """ for pdfimage, xobj in _image_xobje...
Find any images that are in Form XObjects in the container The container may be a page, or a parent Form XObject.
def _find_form_xobject_images(pdf, container, contentsinfo): """Find any images that are in Form XObjects in the container The container may be a page, or a parent Form XObject. """ if '/Resources' not in container: return resources = container['/Resources'] if '/XObject' not in resour...
Find all individual instances of images drawn in the container Usually the container is a page, but it may also be a Form XObject. On a typical page images are stored inline or as regular images in an XObject. Form XObjects may include inline images, XObject images, and recursively, other Form XO...
def _process_content_streams(*, pdf, container, shorthand=None): """Find all individual instances of images drawn in the container Usually the container is a page, but it may also be a Form XObject. On a typical page images are stored inline or as regular images in an XObject. Form XObjects may i...
Smarter text detection that ignores text in margins
def _page_has_text(text_blocks, page_width, page_height): """Smarter text detection that ignores text in margins""" pw, ph = float(page_width), float(page_height) margin_ratio = 0.125 interior_bbox = ( margin_ratio * pw, # left (1 - margin_ratio) * ph, # top (1 - margin_ratio...
Extract only limited content from text boxes We do this to save memory and ensure that our objects are pickleable.
def simplify_textboxes(miner, textbox_getter): """Extract only limited content from text boxes We do this to save memory and ensure that our objects are pickleable. """ for box in textbox_getter(miner): first_line = box._objs[0] first_char = first_line._objs[0] visible = first_...
Get text boxes out of Ghostscript txtwrite xml
def page_get_textblocks(infile, pageno, xmltext, height): """Get text boxes out of Ghostscript txtwrite xml""" root = xmltext if not hasattr(xmltext, 'findall'): return [] def blocks(): for span in root.findall('.//span'): bbox_str = span.attrib['bbox'] font_siz...
Does Tesseract have textonly_pdf capability? Available in v4.00.00alpha since January 2017. Best to parse the parameter list
def has_textonly_pdf(): """Does Tesseract have textonly_pdf capability? Available in v4.00.00alpha since January 2017. Best to parse the parameter list """ args_tess = ['tesseract', '--print-parameters', 'pdf'] params = '' try: params = check_output(args_tess, universal_newlines=Tru...
Produce a .hocr file that reports no text detected on a page that is the same size as the input image.
def _generate_null_hocr(output_hocr, output_sidecar, image): """Produce a .hocr file that reports no text detected on a page that is the same size as the input image.""" from PIL import Image im = Image.open(image) w, h = im.size with open(output_hocr, 'w', encoding="utf-8") as f: f.wr...
Use Tesseract to render a PDF. input_image -- image to analyze skip_pdf -- if we time out, use this file as output output_pdf -- file to generate output_text -- OCR text file language -- list of languages to consider engine_mode -- engine mode argument for tess v4 text_only -- enable tesser...
def generate_pdf( *, input_image, skip_pdf=None, output_pdf, output_text, language: list, engine_mode, text_only: bool, tessconfig: list, timeout: float, pagesegmode: int, user_words, user_patterns, log, ): '''Use Tesseract to render a PDF. input_image --...
Extract image using extract_fn Enumerate images on each page, lookup their xref/ID number in the PDF. Exclude images that are soft masks (i.e. alpha transparency related). Record the page number on which an image is first used, since images may be used on multiple pages (or multiple times on the same p...
def extract_images(pike, root, log, options, extract_fn): """Extract image using extract_fn Enumerate images on each page, lookup their xref/ID number in the PDF. Exclude images that are soft masks (i.e. alpha transparency related). Record the page number on which an image is first used, since images m...
Extract any >=2bpp image we think we can improve
def extract_images_generic(pike, root, log, options): """Extract any >=2bpp image we think we can improve""" jpegs = [] pngs = [] for _, xref, ext in extract_images(pike, root, log, options, extract_image_generic): log.debug('xref = %s ext = %s', xref, ext) if ext == '.png': ...
Extract any bitonal image that we think we can improve as JBIG2
def extract_images_jbig2(pike, root, log, options): """Extract any bitonal image that we think we can improve as JBIG2""" jbig2_groups = defaultdict(list) for pageno, xref, ext in extract_images( pike, root, log, options, extract_image_jbig2 ): group = pageno // options.jbig2_page_group...
Produce JBIG2 images from their groups
def _produce_jbig2_images(jbig2_groups, root, log, options): """Produce JBIG2 images from their groups""" def jbig2_group_futures(executor, root, groups): for group, xref_exts in groups.items(): prefix = f'group{group:08d}' future = executor.submit( jbig2enc.conv...
Convert images to JBIG2 and insert into PDF. When the JBIG2 page group size is > 1 we do several JBIG2 images at once and build a symbol dictionary that will span several pages. Each JBIG2 image must reference to its symbol dictionary. If too many pages shared the same dictionary JBIG2 encoding becomes...
def convert_to_jbig2(pike, jbig2_groups, root, log, options): """Convert images to JBIG2 and insert into PDF. When the JBIG2 page group size is > 1 we do several JBIG2 images at once and build a symbol dictionary that will span several pages. Each JBIG2 image must reference to its symbol dictionary. If...
Get the version of the specified program
def get_version(program, *, version_arg='--version', regex=r'(\d+(\.\d+)*)'): "Get the version of the specified program" args_prog = [program, version_arg] try: proc = run( args_prog, close_fds=True, universal_newlines=True, stdout=PIPE, st...
Return the textual content of the element and its children
def _get_element_text(self, element): """ Return the textual content of the element and its children """ text = '' if element.text is not None: text += element.text for child in element.getchildren(): text += self._get_element_text(child) i...
Returns a tuple containing the coordinates of the bounding box around an element
def element_coordinates(cls, element): """ Returns a tuple containing the coordinates of the bounding box around an element """ out = (0, 0, 0, 0) if 'title' in element.attrib: matches = cls.box_pattern.search(element.attrib['title']) if matches: ...
Returns a tuple containing the baseline slope and intercept.
def baseline(cls, element): """ Returns a tuple containing the baseline slope and intercept. """ if 'title' in element.attrib: matches = cls.baseline_pattern.search(element.attrib['title']) if matches: return float(matches.group(1)), int(matches.gr...
Returns the quantity in PDF units (pt) given quantity in pixels
def pt_from_pixel(self, pxl): """ Returns the quantity in PDF units (pt) given quantity in pixels """ return Rect._make((c / self.dpi * inch) for c in pxl)
Creates a PDF file with an image superimposed on top of the text. Text is positioned according to the bounding box of the lines in the hOCR file. The image need not be identical to the image used to create the hOCR file. It can have a lower resolution, different color mode, etc.
def to_pdf( self, outFileName, imageFileName=None, showBoundingboxes=False, fontname="Helvetica", invisibleText=False, interwordSpaces=False, ): """ Creates a PDF file with an image superimposed on top of the text. Text is positioned ac...
Use the txtwrite device to get text layout information out For details on options of -dTextFormat see https://www.ghostscript.com/doc/current/VectorDevices.htm#TXT Format is like <page> <line> <span bbox="left top right bottom" font="..." size="..."> <char bbox="...." c="X"/> :param p...
def extract_text(input_file, pageno=1): """Use the txtwrite device to get text layout information out For details on options of -dTextFormat see https://www.ghostscript.com/doc/current/VectorDevices.htm#TXT Format is like <page> <line> <span bbox="left top right bottom" font="..." size=".....
Rasterize one page of a PDF at resolution (xres, yres) in canvas units. The image is sized to match the integer pixels dimensions implied by (xres, yres) even if those numbers are noninteger. The image's DPI will be overridden with the values in page_dpi. :param input_file: pathlike :param output...
def rasterize_pdf( input_file, output_file, xres, yres, raster_device, log, pageno=1, page_dpi=None, rotation=None, filter_vector=False, ): """Rasterize one page of a PDF at resolution (xres, yres) in canvas units. The image is sized to match the integer pixels dimension...
Generate a PDF/A. The pdf_pages, a list files, will be merged into output_file. One or more PDF files may be merged. One of the files in this list must be a pdfmark file that provides Ghostscript with details on how to perform the PDF/A conversion. By default with we pick PDF/A-2b, but this works for 1...
def generate_pdfa( pdf_pages, output_file, compression, log, threads=1, pdf_version='1.5', pdfa_part='2', ): """Generate a PDF/A. The pdf_pages, a list files, will be merged into output_file. One or more PDF files may be merged. One of the files in this list must be a pdfmark ...
零声母转换,还原原始的韵母 i行的韵母,前面没有声母的时候,写成yi(衣),ya(呀),ye(耶),yao(腰), you(忧),yan(烟),yin(因),yang(央),ying(英),yong(雍)。 u行的韵母,前面没有声母的时候,写成wu(乌),wa(蛙),wo(窝),wai(歪), wei(威),wan(弯),wen(温),wang(汪),weng(翁)。 ü行的韵母,前面没有声母的时候,写成yu(迂),yue(约),yuan(冤), yun(晕);ü上两点省略。
def convert_zero_consonant(pinyin): """零声母转换,还原原始的韵母 i行的韵母,前面没有声母的时候,写成yi(衣),ya(呀),ye(耶),yao(腰), you(忧),yan(烟),yin(因),yang(央),ying(英),yong(雍)。 u行的韵母,前面没有声母的时候,写成wu(乌),wa(蛙),wo(窝),wai(歪), wei(威),wan(弯),wen(温),wang(汪),weng(翁)。 ü行的韵母,前面没有声母的时候,写成yu(迂),yue(约),yuan(冤), yun(晕);ü上两点省略。 """ ...
ü 转换,还原原始的韵母 ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚), ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。
def convert_uv(pinyin): """ü 转换,还原原始的韵母 ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚), ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。 """ return UV_RE.sub( lambda m: ''.join((m.group(1), UV_MAP[m.group(2)], m.group(3))), pinyin)
iou 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。
def convert_iou(pinyin): """iou 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 """ return IU_RE.sub(lambda m: m.group(1) + IU_MAP[m.group(2)], pinyin)
uei 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。
def convert_uei(pinyin): """uei 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 """ return UI_RE.sub(lambda m: m.group(1) + UI_MAP[m.group(2)], pinyin)
uen 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。
def convert_uen(pinyin): """uen 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。 """ return UN_RE.sub(lambda m: m.group(1) + UN_MAP[m.group(2)], pinyin)
还原原始的韵母
def convert_finals(pinyin): """还原原始的韵母""" pinyin = convert_zero_consonant(pinyin) pinyin = convert_uv(pinyin) pinyin = convert_iou(pinyin) pinyin = convert_uei(pinyin) pinyin = convert_uen(pinyin) return pinyin