partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | Network.feed | Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result | mtcnn/network.py | 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) | 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) | [
"Feeds",
"the",
"network",
"with",
"an",
"image",
":",
"param",
"image",
":",
"image",
"(",
"perhaps",
"loaded",
"with",
"CV2",
")",
":",
"return",
":",
"network",
"result"
] | ipazc/mtcnn | python | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/network.py#L99-L108 | [
"def",
"feed",
"(",
"self",
",",
"image",
")",
":",
"network_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"network_name",
")",
":",
"return",
"self",
".",
"_feed",
"(",
"image"... | 17029fe453a435f50c472ae2fd1c493341b5ede3 |
train | re_symlink | Helper function: relinks soft symbolic link if necessary | src/ocrmypdf/helpers.py | 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... | 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... | [
"Helper",
"function",
":",
"relinks",
"soft",
"symbolic",
"link",
"if",
"necessary"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/helpers.py#L28-L63 | [
"def",
"re_symlink",
"(",
"input_file",
",",
"soft_link_name",
",",
"log",
"=",
"None",
")",
":",
"input_file",
"=",
"os",
".",
"fspath",
"(",
"input_file",
")",
"soft_link_name",
"=",
"os",
".",
"fspath",
"(",
"soft_link_name",
")",
"if",
"log",
"is",
"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | is_file_writable | 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. | src/ocrmypdf/helpers.py | 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():
... | 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():
... | [
"Intentionally",
"racy",
"test",
"if",
"target",
"is",
"writable",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/helpers.py#L94-L122 | [
"def",
"is_file_writable",
"(",
"test_file",
")",
":",
"p",
"=",
"Path",
"(",
"test_file",
")",
"if",
"p",
".",
"is_symlink",
"(",
")",
":",
"p",
"=",
"p",
".",
"resolve",
"(",
"strict",
"=",
"False",
")",
"# p.is_file() throws an exception in some cases",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | generate_pdfa_ps | 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... | src/ocrmypdf/pdfa.py | 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... | 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... | [
"Create",
"a",
"Postscript",
"pdfmark",
"file",
"for",
"Ghostscript",
"PDF",
"/",
"A",
"conversion"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfa.py#L86-L124 | [
"def",
"generate_pdfa_ps",
"(",
"target_filename",
",",
"icc",
"=",
"'sRGB'",
")",
":",
"if",
"icc",
"==",
"'sRGB'",
":",
"icc_profile",
"=",
"SRGB_ICC_PROFILE",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"Only supporting sRGB\"",
")",
"# pdfmark must conta... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | file_claims_pdfa | 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. | src/ocrmypdf/pdfa.py | 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... | 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... | [
"Determines",
"if",
"the",
"file",
"claims",
"to",
"be",
"PDF",
"/",
"A",
"compliant"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfa.py#L127-L149 | [
"def",
"file_claims_pdfa",
"(",
"filename",
")",
":",
"with",
"pikepdf",
".",
"open",
"(",
"filename",
")",
"as",
"pdf",
":",
"pdfmeta",
"=",
"pdf",
".",
"open_metadata",
"(",
")",
"if",
"not",
"pdfmeta",
".",
"pdfa_status",
":",
"return",
"{",
"'pass'",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | name2unicode | 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. | src/ocrmypdf/pdfinfo/layout.py | 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... | 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... | [
"Fix",
"pdfminer",
"s",
"name2unicode",
"function"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/layout.py#L43-L63 | [
"def",
"name2unicode",
"(",
"name",
")",
":",
"if",
"name",
"in",
"glyphname2unicode",
":",
"return",
"glyphname2unicode",
"[",
"name",
"]",
"if",
"name",
".",
"startswith",
"(",
"'g'",
")",
"or",
"name",
".",
"startswith",
"(",
"'a'",
")",
":",
"raise",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | LTStateAwareChar.is_compatible | 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 | src/ocrmypdf/pdfinfo/layout.py | 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... | 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... | [
"Check",
"if",
"characters",
"can",
"be",
"combined",
"into",
"a",
"textline"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/layout.py#L168-L183 | [
"def",
"is_compatible",
"(",
"self",
",",
"obj",
")",
":",
"both_unicode_mapped",
"=",
"isinstance",
"(",
"self",
".",
"_text",
",",
"str",
")",
"and",
"isinstance",
"(",
"obj",
".",
"_text",
",",
"str",
")",
"try",
":",
"if",
"both_unicode_mapped",
":",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | LeptonicaObject._destroy | Destroy some cdata | src/ocrmypdf/leptonica.py | 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)
... | 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)
... | [
"Destroy",
"some",
"cdata"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L155-L161 | [
"def",
"_destroy",
"(",
"cls",
",",
"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",
"(",
"'{} **'",
"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix._repr_png_ | iPython display hook
returns png version of image | src/ocrmypdf/leptonica.py | 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")
... | 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")
... | [
"iPython",
"display",
"hook"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L201-L215 | [
"def",
"_repr_png_",
"(",
"self",
")",
":",
"data",
"=",
"ffi",
".",
"new",
"(",
"'l_uint8 **'",
")",
"size",
"=",
"ffi",
".",
"new",
"(",
"'size_t *'",
")",
"err",
"=",
"lept",
".",
"pixWriteMemPng",
"(",
"data",
",",
"size",
",",
"self",
".",
"_c... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.open | 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. | src/ocrmypdf/leptonica.py | 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... | 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... | [
"Load",
"an",
"image",
"file",
"into",
"a",
"PIX",
"object",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L289-L297 | [
"def",
"open",
"(",
"cls",
",",
"path",
")",
":",
"filename",
"=",
"fspath",
"(",
"path",
")",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"return",
"cls",
"(",
"lept",
".",
"pixRead",
"(",
"os",
".",
"fsencode",
"(",
"filename",
")",
")",
")"
] | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.write_implied_format | 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) | src/ocrmypdf/leptonica.py | 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... | 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... | [
"Write",
"pix",
"to",
"the",
"filename",
"with",
"the",
"extension",
"indicating",
"format",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L299-L309 | [
"def",
"write_implied_format",
"(",
"self",
",",
"path",
",",
"jpeg_quality",
"=",
"0",
",",
"jpeg_progressive",
"=",
"0",
")",
":",
"filename",
"=",
"fspath",
"(",
"path",
")",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"lept",
".",
"pixWriteImpliedForma... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.frompil | Create a copy of a PIL.Image from this Pix | src/ocrmypdf/leptonica.py | 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... | 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... | [
"Create",
"a",
"copy",
"of",
"a",
"PIL",
".",
"Image",
"from",
"this",
"Pix"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L312-L320 | [
"def",
"frompil",
"(",
"self",
",",
"pillow_image",
")",
":",
"bio",
"=",
"BytesIO",
"(",
")",
"pillow_image",
".",
"save",
"(",
"bio",
",",
"format",
"=",
"'png'",
",",
"compress_level",
"=",
"1",
")",
"py_buffer",
"=",
"bio",
".",
"getbuffer",
"(",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.topil | Returns a PIL.Image version of this Pix | src/ocrmypdf/leptonica.py | 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... | 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",
"a",
"PIL",
".",
"Image",
"version",
"of",
"this",
"Pix"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L322-L350 | [
"def",
"topil",
"(",
"self",
")",
":",
"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'",
":"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.deskew | 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 | src/ocrmypdf/leptonica.py | 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
... | 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",
"deskewed",
"pix",
"object",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L355-L365 | [
"def",
"deskew",
"(",
"self",
",",
"reduction_factor",
"=",
"0",
")",
":",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"return",
"Pix",
"(",
"lept",
".",
"pixDeskew",
"(",
"self",
".",
"_cdata",
",",
"reduction_factor",
")",
")"
] | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.scale | Returns the pix object rescaled according to the proportions given. | src/ocrmypdf/leptonica.py | 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])) | 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])) | [
"Returns",
"the",
"pix",
"object",
"rescaled",
"according",
"to",
"the",
"proportions",
"given",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L367-L370 | [
"def",
"scale",
"(",
"self",
",",
"scale_xy",
")",
":",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"return",
"Pix",
"(",
"lept",
".",
"pixScale",
"(",
"self",
".",
"_cdata",
",",
"scale_xy",
"[",
"0",
"]",
",",
"scale_xy",
"[",
"1",
"]",
")",
")... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.rotate_orth | Orthographic rotation, quads: 0-3, number of clockwise rotations | src/ocrmypdf/leptonica.py | def rotate_orth(self, quads):
"Orthographic rotation, quads: 0-3, number of clockwise rotations"
with _LeptonicaErrorTrap():
return Pix(lept.pixRotateOrth(self._cdata, quads)) | def rotate_orth(self, quads):
"Orthographic rotation, quads: 0-3, number of clockwise rotations"
with _LeptonicaErrorTrap():
return Pix(lept.pixRotateOrth(self._cdata, quads)) | [
"Orthographic",
"rotation",
"quads",
":",
"0",
"-",
"3",
"number",
"of",
"clockwise",
"rotations"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L376-L379 | [
"def",
"rotate_orth",
"(",
"self",
",",
"quads",
")",
":",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"return",
"Pix",
"(",
"lept",
".",
"pixRotateOrth",
"(",
"self",
".",
"_cdata",
",",
"quads",
")",
")"
] | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.find_skew | Returns a tuple (deskew angle in degrees, confidence value).
Returns (None, None) if no angle is available. | src/ocrmypdf/leptonica.py | 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... | 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... | [
"Returns",
"a",
"tuple",
"(",
"deskew",
"angle",
"in",
"degrees",
"confidence",
"value",
")",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L381-L393 | [
"def",
"find_skew",
"(",
"self",
")",
":",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"angle",
"=",
"ffi",
".",
"new",
"(",
"'float *'",
",",
"0.0",
")",
"confidence",
"=",
"ffi",
".",
"new",
"(",
"'float *'",
",",
"0.0",
")",
"result",
"=",
"lept... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.remove_colormap | Remove a palette (colormap); if no colormap, returns a copy of this
image
removal_type - any of lept.REMOVE_CMAP_* | src/ocrmypdf/leptonica.py | 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, ... | 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, ... | [
"Remove",
"a",
"palette",
"(",
"colormap",
")",
";",
"if",
"no",
"colormap",
"returns",
"a",
"copy",
"of",
"this",
"image"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L402-L412 | [
"def",
"remove_colormap",
"(",
"self",
",",
"removal_type",
")",
":",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"return",
"Pix",
"(",
"lept",
".",
"pixRemoveColormapGeneral",
"(",
"self",
".",
"_cdata",
",",
"removal_type",
",",
"lept",
".",
"L_COPY",
")... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | Pix.generate_pdf_ci_data | Convert to PDF data, with transcoding | src/ocrmypdf/leptonica.py | 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")
... | 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")
... | [
"Convert",
"to",
"PDF",
"data",
"with",
"transcoding"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L590-L596 | [
"def",
"generate_pdf_ci_data",
"(",
"self",
",",
"type_",
",",
"quality",
")",
":",
"p_compdata",
"=",
"ffi",
".",
"new",
"(",
"'L_COMP_DATA **'",
")",
"result",
"=",
"lept",
".",
"pixGenerateCIData",
"(",
"self",
".",
"_cdata",
",",
"type_",
",",
"quality... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | CompressedData.open | Open compressed data, without transcoding | src/ocrmypdf/leptonica.py | 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:
... | 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:
... | [
"Open",
"compressed",
"data",
"without",
"transcoding"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L671-L681 | [
"def",
"open",
"(",
"cls",
",",
"path",
",",
"jpeg_quality",
"=",
"75",
")",
":",
"filename",
"=",
"fspath",
"(",
"path",
")",
"p_compdata",
"=",
"ffi",
".",
"new",
"(",
"'L_COMP_DATA **'",
")",
"result",
"=",
"lept",
".",
"l_generateCIDataForPdf",
"(",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | CompressedData.get_palette_pdf_string | Returns palette pre-formatted for use in PDF | src/ocrmypdf/leptonica.py | 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) | 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) | [
"Returns",
"palette",
"pre",
"-",
"formatted",
"for",
"use",
"in",
"PDF"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L695-L699 | [
"def",
"get_palette_pdf_string",
"(",
"self",
")",
":",
"buflen",
"=",
"len",
"(",
"'< '",
")",
"+",
"len",
"(",
"' rrggbb'",
")",
"*",
"self",
".",
"_cdata",
".",
"ncolors",
"+",
"len",
"(",
"'>'",
")",
"buf",
"=",
"ffi",
".",
"buffer",
"(",
"self... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _update_page_resources | Update this page's fonts with a reference to the Glyphless font | src/ocrmypdf/_weave.py | 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... | 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... | [
"Update",
"this",
"page",
"s",
"fonts",
"with",
"a",
"reference",
"to",
"the",
"Glyphless",
"font"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_weave.py#L31-L47 | [
"def",
"_update_page_resources",
"(",
"*",
",",
"page",
",",
"font",
",",
"font_key",
",",
"procset",
")",
":",
"if",
"'/Resources'",
"not",
"in",
"page",
":",
"page",
"[",
"'/Resources'",
"]",
"=",
"pikepdf",
".",
"Dictionary",
"(",
"{",
"}",
")",
"re... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _weave_layers_graft | Insert the text layer from text page 0 on to pdf_base at page_num | src/ocrmypdf/_weave.py | 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 ... | 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 ... | [
"Insert",
"the",
"text",
"layer",
"from",
"text",
"page",
"0",
"on",
"to",
"pdf_base",
"at",
"page_num"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_weave.py#L95-L164 | [
"def",
"_weave_layers_graft",
"(",
"*",
",",
"pdf_base",
",",
"page_num",
",",
"text",
",",
"font",
",",
"font_key",
",",
"procset",
",",
"rotation",
",",
"strip_old_text",
",",
"log",
")",
":",
"log",
".",
"debug",
"(",
"\"Grafting\"",
")",
"if",
"Path"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _find_font | Copy a font from the filename text into pdf_base | src/ocrmypdf/_weave.py | 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', {})
... | 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', {})
... | [
"Copy",
"a",
"font",
"from",
"the",
"filename",
"text",
"into",
"pdf_base"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_weave.py#L167-L188 | [
"def",
"_find_font",
"(",
"text",
",",
"pdf_base",
")",
":",
"font",
",",
"font_key",
"=",
"None",
",",
"None",
"possible_font_names",
"=",
"(",
"'/f-0-0'",
",",
"'/F1'",
")",
"try",
":",
"with",
"pikepdf",
".",
"open",
"(",
"text",
")",
"as",
"pdf_tex... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _traverse_toc | 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... | src/ocrmypdf/_weave.py | 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.... | 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.... | [
"Walk",
"the",
"table",
"of",
"contents",
"calling",
"visitor_fn",
"()",
"at",
"each",
"node"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_weave.py#L191-L232 | [
"def",
"_traverse_toc",
"(",
"pdf_base",
",",
"visitor_fn",
",",
"log",
")",
":",
"visited",
"=",
"set",
"(",
")",
"queue",
"=",
"set",
"(",
")",
"link_keys",
"=",
"(",
"'/Parent'",
",",
"'/First'",
",",
"'/Last'",
",",
"'/Prev'",
",",
"'/Next'",
")",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _fix_toc | 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... | src/ocrmypdf/_weave.py | 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
... | 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
... | [
"Repair",
"the",
"table",
"of",
"contents"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_weave.py#L235-L281 | [
"def",
"_fix_toc",
"(",
"pdf_base",
",",
"pageref_remap",
",",
"log",
")",
":",
"if",
"not",
"pageref_remap",
":",
"return",
"def",
"remap_dest",
"(",
"dest_node",
")",
":",
"\"\"\"\n Inner helper function: change the objgen for any page from the old we\n inva... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | weave_layers | 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
... | src/ocrmypdf/_weave.py | 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,... | 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,... | [
"Apply",
"text",
"layer",
"and",
"/",
"or",
"image",
"layer",
"changes",
"to",
"baseline",
"file"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_weave.py#L284-L418 | [
"def",
"weave_layers",
"(",
"infiles",
",",
"output_file",
",",
"log",
",",
"context",
")",
":",
"def",
"input_sorter",
"(",
"key",
")",
":",
"try",
":",
"return",
"page_number",
"(",
"key",
")",
"except",
"ValueError",
":",
"return",
"-",
"1",
"flat_inp... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | numeric | Validator for numeric params | src/ocrmypdf/__main__.py | 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... | 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... | [
"Validator",
"for",
"numeric",
"params"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/__main__.py#L78-L91 | [
"def",
"numeric",
"(",
"basetype",
",",
"min_",
"=",
"None",
",",
"max_",
"=",
"None",
")",
":",
"min_",
"=",
"basetype",
"(",
"min_",
")",
"if",
"min_",
"is",
"not",
"None",
"else",
"None",
"max_",
"=",
"basetype",
"(",
"max_",
")",
"if",
"max_",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | do_ruffus_exception | Replace the elaborate ruffus stack trace with a user friendly
description of the error message that occurred. | src/ocrmypdf/__main__.py | 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):
... | 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):
... | [
"Replace",
"the",
"elaborate",
"ruffus",
"stack",
"trace",
"with",
"a",
"user",
"friendly",
"description",
"of",
"the",
"error",
"message",
"that",
"occurred",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/__main__.py#L759-L819 | [
"def",
"do_ruffus_exception",
"(",
"ruffus_five_tuple",
",",
"options",
",",
"log",
")",
":",
"exit_code",
"=",
"None",
"_task_name",
",",
"_job_name",
",",
"exc_name",
",",
"exc_value",
",",
"exc_stack",
"=",
"ruffus_five_tuple",
"if",
"isinstance",
"(",
"exc_n... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | traverse_ruffus_exception | 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... | src/ocrmypdf/__main__.py | 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 ... | 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 ... | [
"Traverse",
"a",
"RethrownJobError",
"and",
"output",
"the",
"exceptions"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/__main__.py#L822-L845 | [
"def",
"traverse_ruffus_exception",
"(",
"exceptions",
",",
"options",
",",
"log",
")",
":",
"exit_codes",
"=",
"[",
"]",
"for",
"exc",
"in",
"exceptions",
":",
"exit_code",
"=",
"do_ruffus_exception",
"(",
"exc",
",",
"options",
",",
"log",
")",
"exit_codes... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | check_closed_streams | 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... | src/ocrmypdf/__main__.py | 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... | 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... | [
"Work",
"around",
"Python",
"issue",
"with",
"multiprocessing",
"forking",
"on",
"closed",
"streams"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/__main__.py#L848-L897 | [
"def",
"check_closed_streams",
"(",
"options",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
":",
"3",
"]",
">=",
"(",
"3",
",",
"6",
",",
"4",
")",
":",
"return",
"True",
"# Issued fixed in Python 3.6.4+",
"if",
"sys",
".",
"stderr",
"is",
"No... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _pdf_guess_version | 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. | src/ocrmypdf/_pipeline.py | 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... | 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... | [
"Try",
"to",
"find",
"version",
"signature",
"at",
"start",
"of",
"file",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L126-L139 | [
"def",
"_pdf_guess_version",
"(",
"input_file",
",",
"search_window",
"=",
"1024",
")",
":",
"with",
"open",
"(",
"input_file",
",",
"'rb'",
")",
"as",
"f",
":",
"signature",
"=",
"f",
".",
"read",
"(",
"search_window",
")",
"m",
"=",
"re",
".",
"searc... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | get_pageinfo | Get zero-based page info implied by filename, e.g. 000002.pdf -> 1 | src/ocrmypdf/_pipeline.py | 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 | 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",
"zero",
"-",
"based",
"page",
"info",
"implied",
"by",
"filename",
"e",
".",
"g",
".",
"000002",
".",
"pdf",
"-",
">",
"1"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L219-L223 | [
"def",
"get_pageinfo",
"(",
"input_file",
",",
"context",
")",
":",
"pageno",
"=",
"page_number",
"(",
"input_file",
")",
"-",
"1",
"pageinfo",
"=",
"context",
".",
"get_pdfinfo",
"(",
")",
"[",
"pageno",
"]",
"return",
"pageinfo"
] | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | get_page_dpi | Get the DPI when nonsquare DPI is tolerable | src/ocrmypdf/_pipeline.py | 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... | 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",
"nonsquare",
"DPI",
"is",
"tolerable"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L226-L238 | [
"def",
"get_page_dpi",
"(",
"pageinfo",
",",
"options",
")",
":",
"xres",
"=",
"max",
"(",
"pageinfo",
".",
"xres",
"or",
"VECTOR_PAGE_DPI",
",",
"options",
".",
"oversample",
"or",
"0",
",",
"VECTOR_PAGE_DPI",
"if",
"pageinfo",
".",
"has_vector",
"else",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | get_page_square_dpi | Get the DPI when we require xres == yres, scaled to physical units | src/ocrmypdf/_pipeline.py | 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... | 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",
"scaled",
"to",
"physical",
"units"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L241-L253 | [
"def",
"get_page_square_dpi",
"(",
"pageinfo",
",",
"options",
")",
":",
"xres",
"=",
"pageinfo",
".",
"xres",
"or",
"0",
"yres",
"=",
"pageinfo",
".",
"yres",
"or",
"0",
"userunit",
"=",
"pageinfo",
".",
"userunit",
"or",
"1",
"return",
"float",
"(",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | get_canvas_square_dpi | Get the DPI when we require xres == yres, in Postscript units | src/ocrmypdf/_pipeline.py | 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... | 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... | [
"Get",
"the",
"DPI",
"when",
"we",
"require",
"xres",
"==",
"yres",
"in",
"Postscript",
"units"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L256-L265 | [
"def",
"get_canvas_square_dpi",
"(",
"pageinfo",
",",
"options",
")",
":",
"return",
"float",
"(",
"max",
"(",
"(",
"pageinfo",
".",
"xres",
")",
"or",
"VECTOR_PAGE_DPI",
",",
"(",
"pageinfo",
".",
"yres",
")",
"or",
"VECTOR_PAGE_DPI",
",",
"VECTOR_PAGE_DPI"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | orient_page | 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... | src/ocrmypdf/_pipeline.py | 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... | 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... | [
"Work",
"out",
"orientation",
"correct",
"for",
"each",
"page",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L409-L482 | [
"def",
"orient_page",
"(",
"infiles",
",",
"output_file",
",",
"log",
",",
"context",
")",
":",
"options",
"=",
"context",
".",
"get_options",
"(",
")",
"page_pdf",
"=",
"next",
"(",
"ii",
"for",
"ii",
"in",
"infiles",
"if",
"ii",
".",
"endswith",
"(",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | select_ocr_image | 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. | src/ocrmypdf/_pipeline.py | 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... | 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... | [
"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",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L572-L631 | [
"def",
"select_ocr_image",
"(",
"infiles",
",",
"output_file",
",",
"log",
",",
"context",
")",
":",
"image",
"=",
"infiles",
"[",
"0",
"]",
"options",
"=",
"context",
".",
"get_options",
"(",
")",
"pageinfo",
"=",
"get_pageinfo",
"(",
"image",
",",
"con... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | select_visible_page_image | Selects a whole page image that we can show the user (if necessary) | src/ocrmypdf/_pipeline.py | 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... | 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",
"a",
"whole",
"page",
"image",
"that",
"we",
"can",
"show",
"the",
"user",
"(",
"if",
"necessary",
")"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L650-L681 | [
"def",
"select_visible_page_image",
"(",
"infiles",
",",
"output_file",
",",
"log",
",",
"context",
")",
":",
"options",
"=",
"context",
".",
"get_options",
"(",
")",
"if",
"options",
".",
"clean_final",
":",
"image_suffix",
"=",
"'.pp-clean.png'",
"elif",
"op... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | select_image_layer | 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. | src/ocrmypdf/_pipeline.py | 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... | 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... | [
"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",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/_pipeline.py#L684-L717 | [
"def",
"select_image_layer",
"(",
"infiles",
",",
"output_file",
",",
"log",
",",
"context",
")",
":",
"options",
"=",
"context",
".",
"get_options",
"(",
")",
"page_pdf",
"=",
"next",
"(",
"ii",
"for",
"ii",
"in",
"infiles",
"if",
"ii",
".",
"endswith",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _normalize_stack | Convert runs of qQ's in the stack into single graphobjs | src/ocrmypdf/pdfinfo/__init__.py | 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
... | 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
... | [
"Convert",
"runs",
"of",
"qQ",
"s",
"in",
"the",
"stack",
"into",
"single",
"graphobjs"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L109-L117 | [
"def",
"_normalize_stack",
"(",
"graphobjs",
")",
":",
"for",
"operands",
",",
"operator",
"in",
"graphobjs",
":",
"operator",
"=",
"str",
"(",
"operator",
")",
"if",
"re",
".",
"match",
"(",
"r'Q*q+$'",
",",
"operator",
")",
":",
"# Zero or more Q, one or m... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _interpret_contents | 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... | src/ocrmypdf/pdfinfo/__init__.py | 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... | 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... | [
"Interpret",
"the",
"PDF",
"content",
"stream",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L120-L198 | [
"def",
"_interpret_contents",
"(",
"contentstream",
",",
"initial_shorthand",
"=",
"UNIT_SQUARE",
")",
":",
"stack",
"=",
"[",
"]",
"ctm",
"=",
"PdfMatrix",
"(",
"initial_shorthand",
")",
"xobject_settings",
"=",
"[",
"]",
"inline_images",
"=",
"[",
"]",
"foun... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _get_dpi | 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... | src/ocrmypdf/pdfinfo/__init__.py | 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... | 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... | [
"Given",
"the",
"transformation",
"matrix",
"and",
"image",
"size",
"find",
"the",
"image",
"DPI",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L201-L262 | [
"def",
"_get_dpi",
"(",
"ctm_shorthand",
",",
"image_size",
")",
":",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"_",
",",
"_",
"=",
"ctm_shorthand",
"# Calculate the width and height of the image in PDF units",
"image_drawn_width",
"=",
"hypot",
"(",
"a",
",",
"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _find_inline_images | Find inline images in the contentstream | src/ocrmypdf/pdfinfo/__init__.py | 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
) | 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
) | [
"Find",
"inline",
"images",
"in",
"the",
"contentstream"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L364-L370 | [
"def",
"_find_inline_images",
"(",
"contentsinfo",
")",
":",
"for",
"n",
",",
"inline",
"in",
"enumerate",
"(",
"contentsinfo",
".",
"inline_images",
")",
":",
"yield",
"ImageInfo",
"(",
"name",
"=",
"'inline-%02d'",
"%",
"n",
",",
"shorthand",
"=",
"inline"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _image_xobjects | 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... | src/ocrmypdf/pdfinfo/__init__.py | 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... | 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... | [
"Search",
"for",
"all",
"XObject",
"-",
"based",
"images",
"in",
"the",
"container"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L373-L398 | [
"def",
"_image_xobjects",
"(",
"container",
")",
":",
"if",
"'/Resources'",
"not",
"in",
"container",
":",
"return",
"resources",
"=",
"container",
"[",
"'/Resources'",
"]",
"if",
"'/XObject'",
"not",
"in",
"resources",
":",
"return",
"xobjs",
"=",
"resources"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _find_regular_images | 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. | src/ocrmypdf/pdfinfo/__init__.py | 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... | 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",
"images",
"stored",
"in",
"the",
"container",
"s",
"/",
"Resources",
"/",
"XObject"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L401-L426 | [
"def",
"_find_regular_images",
"(",
"container",
",",
"contentsinfo",
")",
":",
"for",
"pdfimage",
",",
"xobj",
"in",
"_image_xobjects",
"(",
"container",
")",
":",
"# For each image that is drawn on this, check if we drawing the",
"# current image - yes this is O(n^2), but n =... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _find_form_xobject_images | Find any images that are in Form XObjects in the container
The container may be a page, or a parent Form XObject. | src/ocrmypdf/pdfinfo/__init__.py | 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... | 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",
"any",
"images",
"that",
"are",
"in",
"Form",
"XObjects",
"in",
"the",
"container"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L429-L458 | [
"def",
"_find_form_xobject_images",
"(",
"pdf",
",",
"container",
",",
"contentsinfo",
")",
":",
"if",
"'/Resources'",
"not",
"in",
"container",
":",
"return",
"resources",
"=",
"container",
"[",
"'/Resources'",
"]",
"if",
"'/XObject'",
"not",
"in",
"resources",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _process_content_streams | 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... | src/ocrmypdf/pdfinfo/__init__.py | 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... | 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... | [
"Find",
"all",
"individual",
"instances",
"of",
"images",
"drawn",
"in",
"the",
"container"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L461-L505 | [
"def",
"_process_content_streams",
"(",
"*",
",",
"pdf",
",",
"container",
",",
"shorthand",
"=",
"None",
")",
":",
"if",
"container",
".",
"get",
"(",
"'/Type'",
")",
"==",
"'/Page'",
"and",
"'/Contents'",
"in",
"container",
":",
"initial_shorthand",
"=",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _page_has_text | Smarter text detection that ignores text in margins | src/ocrmypdf/pdfinfo/__init__.py | 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... | 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... | [
"Smarter",
"text",
"detection",
"that",
"ignores",
"text",
"in",
"margins"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L508-L534 | [
"def",
"_page_has_text",
"(",
"text_blocks",
",",
"page_width",
",",
"page_height",
")",
":",
"pw",
",",
"ph",
"=",
"float",
"(",
"page_width",
")",
",",
"float",
"(",
"page_height",
")",
"margin_ratio",
"=",
"0.125",
"interior_bbox",
"=",
"(",
"margin_ratio... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | simplify_textboxes | Extract only limited content from text boxes
We do this to save memory and ensure that our objects are pickleable. | src/ocrmypdf/pdfinfo/__init__.py | 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_... | 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_... | [
"Extract",
"only",
"limited",
"content",
"from",
"text",
"boxes"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L537-L548 | [
"def",
"simplify_textboxes",
"(",
"miner",
",",
"textbox_getter",
")",
":",
"for",
"box",
"in",
"textbox_getter",
"(",
"miner",
")",
":",
"first_line",
"=",
"box",
".",
"_objs",
"[",
"0",
"]",
"first_char",
"=",
"first_line",
".",
"_objs",
"[",
"0",
"]",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | page_get_textblocks | Get text boxes out of Ghostscript txtwrite xml | src/ocrmypdf/pdfinfo/ghosttext.py | 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... | 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... | [
"Get",
"text",
"boxes",
"out",
"of",
"Ghostscript",
"txtwrite",
"xml"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/ghosttext.py#L38-L74 | [
"def",
"page_get_textblocks",
"(",
"infile",
",",
"pageno",
",",
"xmltext",
",",
"height",
")",
":",
"root",
"=",
"xmltext",
"if",
"not",
"hasattr",
"(",
"xmltext",
",",
"'findall'",
")",
":",
"return",
"[",
"]",
"def",
"blocks",
"(",
")",
":",
"for",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | has_textonly_pdf | Does Tesseract have textonly_pdf capability?
Available in v4.00.00alpha since January 2017. Best to
parse the parameter list | src/ocrmypdf/exec/tesseract.py | 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... | 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... | [
"Does",
"Tesseract",
"have",
"textonly_pdf",
"capability?"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/tesseract.py#L70-L85 | [
"def",
"has_textonly_pdf",
"(",
")",
":",
"args_tess",
"=",
"[",
"'tesseract'",
",",
"'--print-parameters'",
",",
"'pdf'",
"]",
"params",
"=",
"''",
"try",
":",
"params",
"=",
"check_output",
"(",
"args_tess",
",",
"universal_newlines",
"=",
"True",
",",
"st... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _generate_null_hocr | Produce a .hocr file that reports no text detected on a page that is
the same size as the input image. | src/ocrmypdf/exec/tesseract.py | 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... | 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... | [
"Produce",
"a",
".",
"hocr",
"file",
"that",
"reports",
"no",
"text",
"detected",
"on",
"a",
"page",
"that",
"is",
"the",
"same",
"size",
"as",
"the",
"input",
"image",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/tesseract.py#L210-L221 | [
"def",
"_generate_null_hocr",
"(",
"output_hocr",
",",
"output_sidecar",
",",
"image",
")",
":",
"from",
"PIL",
"import",
"Image",
"im",
"=",
"Image",
".",
"open",
"(",
"image",
")",
"w",
",",
"h",
"=",
"im",
".",
"size",
"with",
"open",
"(",
"output_h... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | generate_pdf | 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... | src/ocrmypdf/exec/tesseract.py | 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 --... | 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 --... | [
"Use",
"Tesseract",
"to",
"render",
"a",
"PDF",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/tesseract.py#L295-L361 | [
"def",
"generate_pdf",
"(",
"*",
",",
"input_image",
",",
"skip_pdf",
"=",
"None",
",",
"output_pdf",
",",
"output_text",
",",
"language",
":",
"list",
",",
"engine_mode",
",",
"text_only",
":",
"bool",
",",
"tessconfig",
":",
"list",
",",
"timeout",
":",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | extract_images | 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... | src/ocrmypdf/optimize.py | 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... | 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",
"image",
"using",
"extract_fn"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/optimize.py#L149-L199 | [
"def",
"extract_images",
"(",
"pike",
",",
"root",
",",
"log",
",",
"options",
",",
"extract_fn",
")",
":",
"include_xrefs",
"=",
"set",
"(",
")",
"exclude_xrefs",
"=",
"set",
"(",
")",
"pageno_for_xref",
"=",
"{",
"}",
"errors",
"=",
"0",
"for",
"page... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | extract_images_generic | Extract any >=2bpp image we think we can improve | src/ocrmypdf/optimize.py | 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':
... | 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",
">",
"=",
"2bpp",
"image",
"we",
"think",
"we",
"can",
"improve"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/optimize.py#L202-L214 | [
"def",
"extract_images_generic",
"(",
"pike",
",",
"root",
",",
"log",
",",
"options",
")",
":",
"jpegs",
"=",
"[",
"]",
"pngs",
"=",
"[",
"]",
"for",
"_",
",",
"xref",
",",
"ext",
"in",
"extract_images",
"(",
"pike",
",",
"root",
",",
"log",
",",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | extract_images_jbig2 | Extract any bitonal image that we think we can improve as JBIG2 | src/ocrmypdf/optimize.py | 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... | 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... | [
"Extract",
"any",
"bitonal",
"image",
"that",
"we",
"think",
"we",
"can",
"improve",
"as",
"JBIG2"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/optimize.py#L217-L232 | [
"def",
"extract_images_jbig2",
"(",
"pike",
",",
"root",
",",
"log",
",",
"options",
")",
":",
"jbig2_groups",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"pageno",
",",
"xref",
",",
"ext",
"in",
"extract_images",
"(",
"pike",
",",
"root",
",",
"log",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | _produce_jbig2_images | Produce JBIG2 images from their groups | src/ocrmypdf/optimize.py | 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... | 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... | [
"Produce",
"JBIG2",
"images",
"from",
"their",
"groups"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/optimize.py#L235-L272 | [
"def",
"_produce_jbig2_images",
"(",
"jbig2_groups",
",",
"root",
",",
"log",
",",
"options",
")",
":",
"def",
"jbig2_group_futures",
"(",
"executor",
",",
"root",
",",
"groups",
")",
":",
"for",
"group",
",",
"xref_exts",
"in",
"groups",
".",
"items",
"("... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | convert_to_jbig2 | 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... | src/ocrmypdf/optimize.py | 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... | 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... | [
"Convert",
"images",
"to",
"JBIG2",
"and",
"insert",
"into",
"PDF",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/optimize.py#L275-L310 | [
"def",
"convert_to_jbig2",
"(",
"pike",
",",
"jbig2_groups",
",",
"root",
",",
"log",
",",
"options",
")",
":",
"_produce_jbig2_images",
"(",
"jbig2_groups",
",",
"root",
",",
"log",
",",
"options",
")",
"for",
"group",
",",
"xref_exts",
"in",
"jbig2_groups"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | get_version | Get the version of the specified program | src/ocrmypdf/exec/__init__.py | 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... | 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... | [
"Get",
"the",
"version",
"of",
"the",
"specified",
"program"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/__init__.py#L28-L61 | [
"def",
"get_version",
"(",
"program",
",",
"*",
",",
"version_arg",
"=",
"'--version'",
",",
"regex",
"=",
"r'(\\d+(\\.\\d+)*)'",
")",
":",
"args_prog",
"=",
"[",
"program",
",",
"version_arg",
"]",
"try",
":",
"proc",
"=",
"run",
"(",
"args_prog",
",",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | HocrTransform._get_element_text | Return the textual content of the element and its children | src/ocrmypdf/hocrtransform.py | 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... | 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... | [
"Return",
"the",
"textual",
"content",
"of",
"the",
"element",
"and",
"its",
"children"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/hocrtransform.py#L103-L114 | [
"def",
"_get_element_text",
"(",
"self",
",",
"element",
")",
":",
"text",
"=",
"''",
"if",
"element",
".",
"text",
"is",
"not",
"None",
":",
"text",
"+=",
"element",
".",
"text",
"for",
"child",
"in",
"element",
".",
"getchildren",
"(",
")",
":",
"t... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | HocrTransform.element_coordinates | Returns a tuple containing the coordinates of the bounding box around
an element | src/ocrmypdf/hocrtransform.py | 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:
... | 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",
"coordinates",
"of",
"the",
"bounding",
"box",
"around",
"an",
"element"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/hocrtransform.py#L117-L128 | [
"def",
"element_coordinates",
"(",
"cls",
",",
"element",
")",
":",
"out",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"if",
"'title'",
"in",
"element",
".",
"attrib",
":",
"matches",
"=",
"cls",
".",
"box_pattern",
".",
"search",
"(",
"eleme... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | HocrTransform.baseline | Returns a tuple containing the baseline slope and intercept. | src/ocrmypdf/hocrtransform.py | 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... | 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",
"a",
"tuple",
"containing",
"the",
"baseline",
"slope",
"and",
"intercept",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/hocrtransform.py#L131-L139 | [
"def",
"baseline",
"(",
"cls",
",",
"element",
")",
":",
"if",
"'title'",
"in",
"element",
".",
"attrib",
":",
"matches",
"=",
"cls",
".",
"baseline_pattern",
".",
"search",
"(",
"element",
".",
"attrib",
"[",
"'title'",
"]",
")",
"if",
"matches",
":",... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | HocrTransform.pt_from_pixel | Returns the quantity in PDF units (pt) given quantity in pixels | src/ocrmypdf/hocrtransform.py | 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) | 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) | [
"Returns",
"the",
"quantity",
"in",
"PDF",
"units",
"(",
"pt",
")",
"given",
"quantity",
"in",
"pixels"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/hocrtransform.py#L141-L145 | [
"def",
"pt_from_pixel",
"(",
"self",
",",
"pxl",
")",
":",
"return",
"Rect",
".",
"_make",
"(",
"(",
"c",
"/",
"self",
".",
"dpi",
"*",
"inch",
")",
"for",
"c",
"in",
"pxl",
")"
] | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | HocrTransform.to_pdf | 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. | src/ocrmypdf/hocrtransform.py | 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... | 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... | [
"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",
... | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/hocrtransform.py#L156-L231 | [
"def",
"to_pdf",
"(",
"self",
",",
"outFileName",
",",
"imageFileName",
"=",
"None",
",",
"showBoundingboxes",
"=",
"False",
",",
"fontname",
"=",
"\"Helvetica\"",
",",
"invisibleText",
"=",
"False",
",",
"interwordSpaces",
"=",
"False",
",",
")",
":",
"# cr... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | extract_text | 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... | src/ocrmypdf/exec/ghostscript.py | 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="..... | 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="..... | [
"Use",
"the",
"txtwrite",
"device",
"to",
"get",
"text",
"layout",
"information",
"out"
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/ghostscript.py#L57-L99 | [
"def",
"extract_text",
"(",
"input_file",
",",
"pageno",
"=",
"1",
")",
":",
"if",
"pageno",
"is",
"not",
"None",
":",
"pages",
"=",
"[",
"'-dFirstPage=%i'",
"%",
"pageno",
",",
"'-dLastPage=%i'",
"%",
"pageno",
"]",
"else",
":",
"pages",
"=",
"[",
"]"... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | rasterize_pdf | 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... | src/ocrmypdf/exec/ghostscript.py | 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... | 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... | [
"Rasterize",
"one",
"page",
"of",
"a",
"PDF",
"at",
"resolution",
"(",
"xres",
"yres",
")",
"in",
"canvas",
"units",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/ghostscript.py#L102-L200 | [
"def",
"rasterize_pdf",
"(",
"input_file",
",",
"output_file",
",",
"xres",
",",
"yres",
",",
"raster_device",
",",
"log",
",",
"pageno",
"=",
"1",
",",
"page_dpi",
"=",
"None",
",",
"rotation",
"=",
"None",
",",
"filter_vector",
"=",
"False",
",",
")",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | generate_pdfa | 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... | src/ocrmypdf/exec/ghostscript.py | 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
... | 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
... | [
"Generate",
"a",
"PDF",
"/",
"A",
"."
] | jbarlow83/OCRmyPDF | python | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/ghostscript.py#L203-L308 | [
"def",
"generate_pdfa",
"(",
"pdf_pages",
",",
"output_file",
",",
"compression",
",",
"log",
",",
"threads",
"=",
"1",
",",
"pdf_version",
"=",
"'1.5'",
",",
"pdfa_part",
"=",
"'2'",
",",
")",
":",
"compression_args",
"=",
"[",
"]",
"if",
"compression",
... | 79c84eefa353632a3d7ccddbd398c6678c1c1777 |
train | convert_zero_consonant | 零声母转换,还原原始的韵母
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(晕);ü上两点省略。 | pypinyin/standard.py | 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(晕);ü上两点省略。
"""
... | 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(晕);ü上两点省略。
"""
... | [
"零声母转换,还原原始的韵母"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/standard.py#L65-L108 | [
"def",
"convert_zero_consonant",
"(",
"pinyin",
")",
":",
"# y: yu -> v, yi -> i, y -> i",
"if",
"pinyin",
".",
"startswith",
"(",
"'y'",
")",
":",
"# 去除 y 后的拼音",
"no_y_py",
"=",
"pinyin",
"[",
"1",
":",
"]",
"first_char",
"=",
"no_y_py",
"[",
"0",
"]",
"if"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | convert_uv | ü 转换,还原原始的韵母
ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚),
ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。 | pypinyin/standard.py | 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) | 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) | [
"ü",
"转换,还原原始的韵母"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/standard.py#L111-L119 | [
"def",
"convert_uv",
"(",
"pinyin",
")",
":",
"return",
"UV_RE",
".",
"sub",
"(",
"lambda",
"m",
":",
"''",
".",
"join",
"(",
"(",
"m",
".",
"group",
"(",
"1",
")",
",",
"UV_MAP",
"[",
"m",
".",
"group",
"(",
"2",
")",
"]",
",",
"m",
".",
"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | convert_iou | iou 转换,还原原始的韵母
iou,uei,uen前面加声母的时候,写成iu,ui,un。
例如niu(牛),gui(归),lun(论)。 | pypinyin/standard.py | 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) | 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) | [
"iou",
"转换,还原原始的韵母"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/standard.py#L122-L128 | [
"def",
"convert_iou",
"(",
"pinyin",
")",
":",
"return",
"IU_RE",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"1",
")",
"+",
"IU_MAP",
"[",
"m",
".",
"group",
"(",
"2",
")",
"]",
",",
"pinyin",
")"
] | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | convert_uei | uei 转换,还原原始的韵母
iou,uei,uen前面加声母的时候,写成iu,ui,un。
例如niu(牛),gui(归),lun(论)。 | pypinyin/standard.py | 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) | 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) | [
"uei",
"转换,还原原始的韵母"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/standard.py#L131-L137 | [
"def",
"convert_uei",
"(",
"pinyin",
")",
":",
"return",
"UI_RE",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"1",
")",
"+",
"UI_MAP",
"[",
"m",
".",
"group",
"(",
"2",
")",
"]",
",",
"pinyin",
")"
] | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | convert_uen | uen 转换,还原原始的韵母
iou,uei,uen前面加声母的时候,写成iu,ui,un。
例如niu(牛),gui(归),lun(论)。 | pypinyin/standard.py | 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_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) | [
"uen",
"转换,还原原始的韵母"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/standard.py#L140-L146 | [
"def",
"convert_uen",
"(",
"pinyin",
")",
":",
"return",
"UN_RE",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"1",
")",
"+",
"UN_MAP",
"[",
"m",
".",
"group",
"(",
"2",
")",
"]",
",",
"pinyin",
")"
] | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | convert_finals | 还原原始的韵母 | pypinyin/standard.py | 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 | 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 | [
"还原原始的韵母"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/standard.py#L149-L156 | [
"def",
"convert_finals",
"(",
"pinyin",
")",
":",
"pinyin",
"=",
"convert_zero_consonant",
"(",
"pinyin",
")",
"pinyin",
"=",
"convert_uv",
"(",
"pinyin",
")",
"pinyin",
"=",
"convert_iou",
"(",
"pinyin",
")",
"pinyin",
"=",
"convert_uei",
"(",
"pinyin",
")"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | _seg | 按是否是汉字进行分词 | pypinyin/utils.py | def _seg(chars):
"""按是否是汉字进行分词"""
s = '' # 保存一个词
ret = [] # 分词结果
flag = 0 # 上一个字符是什么? 0: 汉字, 1: 不是汉字
for n, c in enumerate(chars):
if RE_HANS.match(c): # 汉字, 确定 flag 的初始值
if n == 0: # 第一个字符
flag = 0
if flag == 0:
s += c
... | def _seg(chars):
"""按是否是汉字进行分词"""
s = '' # 保存一个词
ret = [] # 分词结果
flag = 0 # 上一个字符是什么? 0: 汉字, 1: 不是汉字
for n, c in enumerate(chars):
if RE_HANS.match(c): # 汉字, 确定 flag 的初始值
if n == 0: # 第一个字符
flag = 0
if flag == 0:
s += c
... | [
"按是否是汉字进行分词"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/utils.py#L13-L43 | [
"def",
"_seg",
"(",
"chars",
")",
":",
"s",
"=",
"''",
"# 保存一个词",
"ret",
"=",
"[",
"]",
"# 分词结果",
"flag",
"=",
"0",
"# 上一个字符是什么? 0: 汉字, 1: 不是汉字",
"for",
"n",
",",
"c",
"in",
"enumerate",
"(",
"chars",
")",
":",
"if",
"RE_HANS",
".",
"match",
"(",
"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | simple_seg | 将传入的字符串按是否是汉字来分割 | pypinyin/utils.py | def simple_seg(hans):
"""将传入的字符串按是否是汉字来分割"""
assert not isinstance(hans, bytes_type), \
'must be unicode string or [unicode, ...] list'
if isinstance(hans, text_type):
return _seg(hans)
else:
hans = list(hans)
if len(hans) == 1:
return simple_seg(hans[0])
... | def simple_seg(hans):
"""将传入的字符串按是否是汉字来分割"""
assert not isinstance(hans, bytes_type), \
'must be unicode string or [unicode, ...] list'
if isinstance(hans, text_type):
return _seg(hans)
else:
hans = list(hans)
if len(hans) == 1:
return simple_seg(hans[0])
... | [
"将传入的字符串按是否是汉字来分割"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/utils.py#L46-L57 | [
"def",
"simple_seg",
"(",
"hans",
")",
":",
"assert",
"not",
"isinstance",
"(",
"hans",
",",
"bytes_type",
")",
",",
"'must be unicode string or [unicode, ...] list'",
"if",
"isinstance",
"(",
"hans",
",",
"text_type",
")",
":",
"return",
"_seg",
"(",
"hans",
... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | load_single_dict | 载入用户自定义的单字拼音库
:param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}``
:param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type pinyin_dict: dict | pypinyin/core.py | def load_single_dict(pinyin_dict, style='default'):
"""载入用户自定义的单字拼音库
:param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}``
:param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type pinyin_dict: dict
"""
if style == 'tone2':
for k, v in pinyin_dict.items():
v = _replace_t... | def load_single_dict(pinyin_dict, style='default'):
"""载入用户自定义的单字拼音库
:param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}``
:param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type pinyin_dict: dict
"""
if style == 'tone2':
for k, v in pinyin_dict.items():
v = _replace_t... | [
"载入用户自定义的单字拼音库"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L35-L49 | [
"def",
"load_single_dict",
"(",
"pinyin_dict",
",",
"style",
"=",
"'default'",
")",
":",
"if",
"style",
"==",
"'tone2'",
":",
"for",
"k",
",",
"v",
"in",
"pinyin_dict",
".",
"items",
"(",
")",
":",
"v",
"=",
"_replace_tone2_style_dict_to_default",
"(",
"v"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | load_phrases_dict | 载入用户自定义的词语拼音库
:param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}``
:param style: phrases_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type phrases_dict: dict | pypinyin/core.py | def load_phrases_dict(phrases_dict, style='default'):
"""载入用户自定义的词语拼音库
:param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}``
:param style: phrases_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type phrases_dict: dict
"""
if style == 'tone2':
for k, value in phrases_dict.items():
... | def load_phrases_dict(phrases_dict, style='default'):
"""载入用户自定义的词语拼音库
:param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}``
:param style: phrases_dict 参数值的拼音库风格. 支持 'default', 'tone2'
:type phrases_dict: dict
"""
if style == 'tone2':
for k, value in phrases_dict.items():
... | [
"载入用户自定义的词语拼音库"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L52-L69 | [
"def",
"load_phrases_dict",
"(",
"phrases_dict",
",",
"style",
"=",
"'default'",
")",
":",
"if",
"style",
"==",
"'tone2'",
":",
"for",
"k",
",",
"value",
"in",
"phrases_dict",
".",
"items",
"(",
")",
":",
"v",
"=",
"[",
"list",
"(",
"map",
"(",
"_rep... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | to_fixed | 根据拼音风格格式化带声调的拼音.
:param pinyin: 单个拼音
:param style: 拼音风格
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 根据拼音风格格式化后的拼音字符串
:rtype: unicode | pypinyin/core.py | def to_fixed(pinyin, style, strict=True):
"""根据拼音风格格式化带声调的拼音.
:param pinyin: 单个拼音
:param style: 拼音风格
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 根据拼音风格格式化后的拼音字符串
:rtype: unicode
"""
return convert_style(pinyin, style=style, strict=strict, default=pinyin) | def to_fixed(pinyin, style, strict=True):
"""根据拼音风格格式化带声调的拼音.
:param pinyin: 单个拼音
:param style: 拼音风格
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 根据拼音风格格式化后的拼音字符串
:rtype: unicode
"""
return convert_style(pinyin, style=style, strict=strict, default=pinyin) | [
"根据拼音风格格式化带声调的拼音",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L72-L81 | [
"def",
"to_fixed",
"(",
"pinyin",
",",
"style",
",",
"strict",
"=",
"True",
")",
":",
"return",
"convert_style",
"(",
"pinyin",
",",
"style",
"=",
"style",
",",
"strict",
"=",
"strict",
",",
"default",
"=",
"pinyin",
")"
] | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | _handle_nopinyin_char | 处理没有拼音的字符 | pypinyin/core.py | def _handle_nopinyin_char(chars, errors='default'):
"""处理没有拼音的字符"""
if callable_check(errors):
return errors(chars)
if errors == 'default':
return chars
elif errors == 'ignore':
return None
elif errors == 'replace':
if len(chars) > 1:
return ''.join(text_... | def _handle_nopinyin_char(chars, errors='default'):
"""处理没有拼音的字符"""
if callable_check(errors):
return errors(chars)
if errors == 'default':
return chars
elif errors == 'ignore':
return None
elif errors == 'replace':
if len(chars) > 1:
return ''.join(text_... | [
"处理没有拼音的字符"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L87-L100 | [
"def",
"_handle_nopinyin_char",
"(",
"chars",
",",
"errors",
"=",
"'default'",
")",
":",
"if",
"callable_check",
"(",
"errors",
")",
":",
"return",
"errors",
"(",
"chars",
")",
"if",
"errors",
"==",
"'default'",
":",
"return",
"chars",
"elif",
"errors",
"=... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | single_pinyin | 单字拼音转换.
:param han: 单个汉字
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:func:`~pypinyin.pinyin`
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 返回拼音列表,多音字会有多个拼音项
:rtype: list | pypinyin/core.py | def single_pinyin(han, style, heteronym, errors='default', strict=True):
"""单字拼音转换.
:param han: 单个汉字
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:func:`~pypinyin.pinyin`
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 返回拼音列表,多音字会有多个拼音项
:rtype: list
"""
num = ord(han)
# 处... | def single_pinyin(han, style, heteronym, errors='default', strict=True):
"""单字拼音转换.
:param han: 单个汉字
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:func:`~pypinyin.pinyin`
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 返回拼音列表,多音字会有多个拼音项
:rtype: list
"""
num = ord(han)
# 处... | [
"单字拼音转换",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L121-L152 | [
"def",
"single_pinyin",
"(",
"han",
",",
"style",
",",
"heteronym",
",",
"errors",
"=",
"'default'",
",",
"strict",
"=",
"True",
")",
":",
"num",
"=",
"ord",
"(",
"han",
")",
"# 处理没有拼音的字符",
"if",
"num",
"not",
"in",
"PINYIN_DICT",
":",
"return",
"handl... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | phrase_pinyin | 词语拼音转换.
:param phrase: 词语
:param errors: 指定如何处理没有拼音的字符
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 拼音列表
:rtype: list | pypinyin/core.py | def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True):
"""词语拼音转换.
:param phrase: 词语
:param errors: 指定如何处理没有拼音的字符
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 拼音列表
:rtype: list
"""
py = []
if phrase in PHRASES_DICT:
py = deepcopy(PHRASES_DICT[phrase])
... | def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True):
"""词语拼音转换.
:param phrase: 词语
:param errors: 指定如何处理没有拼音的字符
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 拼音列表
:rtype: list
"""
py = []
if phrase in PHRASES_DICT:
py = deepcopy(PHRASES_DICT[phrase])
... | [
"词语拼音转换",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L155-L179 | [
"def",
"phrase_pinyin",
"(",
"phrase",
",",
"style",
",",
"heteronym",
",",
"errors",
"=",
"'default'",
",",
"strict",
"=",
"True",
")",
":",
"py",
"=",
"[",
"]",
"if",
"phrase",
"in",
"PHRASES_DICT",
":",
"py",
"=",
"deepcopy",
"(",
"PHRASES_DICT",
"[... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | _pinyin | :param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符,
不存在混合的情况。 | pypinyin/core.py | def _pinyin(words, style, heteronym, errors, strict=True):
"""
:param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符,
不存在混合的情况。
"""
pys = []
# 初步过滤没有拼音的字符
if RE_HANS.match(words):
pys = phrase_pinyin(words, style=style, heteronym=heteronym,
errors=error... | def _pinyin(words, style, heteronym, errors, strict=True):
"""
:param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符,
不存在混合的情况。
"""
pys = []
# 初步过滤没有拼音的字符
if RE_HANS.match(words):
pys = phrase_pinyin(words, style=style, heteronym=heteronym,
errors=error... | [
":",
"param",
"words",
":",
"经过分词处理后的字符串,只包含中文字符或只包含非中文字符,",
"不存在混合的情况。"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L182-L197 | [
"def",
"_pinyin",
"(",
"words",
",",
"style",
",",
"heteronym",
",",
"errors",
",",
"strict",
"=",
"True",
")",
":",
"pys",
"=",
"[",
"]",
"# 初步过滤没有拼音的字符",
"if",
"RE_HANS",
".",
"match",
"(",
"words",
")",
":",
"pys",
"=",
"phrase_pinyin",
"(",
"word... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | pinyin | 将汉字转换为拼音.
:param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ).
可以使用自己喜爱的分词模块对字符串进行分词处理,
只需将经过分词处理的字符串列表传进来就可以了。
:type hans: unicode 字符串或字符串列表
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.TONE` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`
:param error... | pypinyin/core.py | def pinyin(hans, style=Style.TONE, heteronym=False,
errors='default', strict=True):
"""将汉字转换为拼音.
:param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ).
可以使用自己喜爱的分词模块对字符串进行分词处理,
只需将经过分词处理的字符串列表传进来就可以了。
:type hans: unicode 字符串或字符串列表
:param style: 指定拼音风格,默认是 :p... | def pinyin(hans, style=Style.TONE, heteronym=False,
errors='default', strict=True):
"""将汉字转换为拼音.
:param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ).
可以使用自己喜爱的分词模块对字符串进行分词处理,
只需将经过分词处理的字符串列表传进来就可以了。
:type hans: unicode 字符串或字符串列表
:param style: 指定拼音风格,默认是 :p... | [
"将汉字转换为拼音",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L200-L248 | [
"def",
"pinyin",
"(",
"hans",
",",
"style",
"=",
"Style",
".",
"TONE",
",",
"heteronym",
"=",
"False",
",",
"errors",
"=",
"'default'",
",",
"strict",
"=",
"True",
")",
":",
"# 对字符串进行分词处理",
"if",
"isinstance",
"(",
"hans",
",",
"text_type",
")",
":",
... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | slug | 生成 slug 字符串.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`
:param heteronym: 是否启用多音字
:param separstor: 两个拼音间的分隔符/连接符
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:func:`~... | pypinyin/core.py | def slug(hans, style=Style.NORMAL, heteronym=False, separator='-',
errors='default', strict=True):
"""生成 slug 字符串.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`
:param heteronym... | def slug(hans, style=Style.NORMAL, heteronym=False, separator='-',
errors='default', strict=True):
"""生成 slug 字符串.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`
:param heteronym... | [
"生成",
"slug",
"字符串",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L251-L283 | [
"def",
"slug",
"(",
"hans",
",",
"style",
"=",
"Style",
".",
"NORMAL",
",",
"heteronym",
"=",
"False",
",",
"separator",
"=",
"'-'",
",",
"errors",
"=",
"'default'",
",",
"strict",
"=",
"True",
")",
":",
"return",
"separator",
".",
"join",
"(",
"chai... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | lazy_pinyin | 不包含多音字的拼音列表.
与 :py:func:`~pypinyin.pinyin` 的区别是返回的拼音是个字符串,
并且每个字只包含一个读音.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~pypinyin.Style`。
:param errors: 指定如何处理没有拼音的字符,详情请参考
:py:fun... | pypinyin/core.py | def lazy_pinyin(hans, style=Style.NORMAL, errors='default', strict=True):
"""不包含多音字的拼音列表.
与 :py:func:`~pypinyin.pinyin` 的区别是返回的拼音是个字符串,
并且每个字只包含一个读音.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~p... | def lazy_pinyin(hans, style=Style.NORMAL, errors='default', strict=True):
"""不包含多音字的拼音列表.
与 :py:func:`~pypinyin.pinyin` 的区别是返回的拼音是个字符串,
并且每个字只包含一个读音.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
更多拼音风格详见 :class:`~p... | [
"不包含多音字的拼音列表",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L286-L320 | [
"def",
"lazy_pinyin",
"(",
"hans",
",",
"style",
"=",
"Style",
".",
"NORMAL",
",",
"errors",
"=",
"'default'",
",",
"strict",
"=",
"True",
")",
":",
"return",
"list",
"(",
"chain",
"(",
"*",
"pinyin",
"(",
"hans",
",",
"style",
"=",
"style",
",",
"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | convert | 根据拼音风格把原始拼音转换为不同的格式
:param pinyin: 原始有声调的单个拼音
:type pinyin: unicode
:param style: 拼音风格
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
:type strict: bool
:param default: 拼音风格对应的实现不存在时返回的默认值
:return: 按照拼音风格进行处理过后的拼音字符串
:rtype: unicode | pypinyin/style/__init__.py | def convert(pinyin, style, strict, default=None, **kwargs):
"""根据拼音风格把原始拼音转换为不同的格式
:param pinyin: 原始有声调的单个拼音
:type pinyin: unicode
:param style: 拼音风格
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
:type strict: bool
:param default: 拼音风格对应的实现不存在时返回的默认值
:return: 按照拼音风格进行处理过后的拼音字符串... | def convert(pinyin, style, strict, default=None, **kwargs):
"""根据拼音风格把原始拼音转换为不同的格式
:param pinyin: 原始有声调的单个拼音
:type pinyin: unicode
:param style: 拼音风格
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
:type strict: bool
:param default: 拼音风格对应的实现不存在时返回的默认值
:return: 按照拼音风格进行处理过后的拼音字符串... | [
"根据拼音风格把原始拼音转换为不同的格式"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/style/__init__.py#L8-L22 | [
"def",
"convert",
"(",
"pinyin",
",",
"style",
",",
"strict",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"style",
"in",
"_registry",
":",
"return",
"_registry",
"[",
"style",
"]",
"(",
"pinyin",
",",
"strict",
"=",
"strict"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | register | 注册一个拼音风格实现
::
@register('echo')
def echo(pinyin, **kwargs):
return pinyin
# or
register('echo', echo) | pypinyin/style/__init__.py | def register(style, func=None):
"""注册一个拼音风格实现
::
@register('echo')
def echo(pinyin, **kwargs):
return pinyin
# or
register('echo', echo)
"""
if func is not None:
_registry[style] = func
return
def decorator(func):
_registry[styl... | def register(style, func=None):
"""注册一个拼音风格实现
::
@register('echo')
def echo(pinyin, **kwargs):
return pinyin
# or
register('echo', echo)
"""
if func is not None:
_registry[style] = func
return
def decorator(func):
_registry[styl... | [
"注册一个拼音风格实现"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/style/__init__.py#L25-L49 | [
"def",
"register",
"(",
"style",
",",
"func",
"=",
"None",
")",
":",
"if",
"func",
"is",
"not",
"None",
":",
"_registry",
"[",
"style",
"]",
"=",
"func",
"return",
"def",
"decorator",
"(",
"func",
")",
":",
"_registry",
"[",
"style",
"]",
"=",
"fun... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | get_initials | 获取单个拼音中的声母.
:param pinyin: 单个拼音
:type pinyin: unicode
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 声母
:rtype: unicode | pypinyin/style/_utils.py | def get_initials(pinyin, strict):
"""获取单个拼音中的声母.
:param pinyin: 单个拼音
:type pinyin: unicode
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 声母
:rtype: unicode
"""
if strict:
_initials = _INITIALS
else:
_initials = _INITIALS_NOT_STRICT
for i in _initials:
i... | def get_initials(pinyin, strict):
"""获取单个拼音中的声母.
:param pinyin: 单个拼音
:type pinyin: unicode
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 声母
:rtype: unicode
"""
if strict:
_initials = _INITIALS
else:
_initials = _INITIALS_NOT_STRICT
for i in _initials:
i... | [
"获取单个拼音中的声母",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/style/_utils.py#L12-L29 | [
"def",
"get_initials",
"(",
"pinyin",
",",
"strict",
")",
":",
"if",
"strict",
":",
"_initials",
"=",
"_INITIALS",
"else",
":",
"_initials",
"=",
"_INITIALS_NOT_STRICT",
"for",
"i",
"in",
"_initials",
":",
"if",
"pinyin",
".",
"startswith",
"(",
"i",
")",
... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | get_finals | 获取单个拼音中的韵母.
:param pinyin: 单个拼音
:type pinyin: unicode
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 韵母
:rtype: unicode | pypinyin/style/_utils.py | def get_finals(pinyin, strict):
"""获取单个拼音中的韵母.
:param pinyin: 单个拼音
:type pinyin: unicode
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 韵母
:rtype: unicode
"""
if strict:
pinyin = convert_finals(pinyin)
initials = get_initials(pinyin, strict=strict) or ''
# 没有声母,整个都是韵母
... | def get_finals(pinyin, strict):
"""获取单个拼音中的韵母.
:param pinyin: 单个拼音
:type pinyin: unicode
:param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
:return: 韵母
:rtype: unicode
"""
if strict:
pinyin = convert_finals(pinyin)
initials = get_initials(pinyin, strict=strict) or ''
# 没有声母,整个都是韵母
... | [
"获取单个拼音中的韵母",
"."
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/style/_utils.py#L32-L49 | [
"def",
"get_finals",
"(",
"pinyin",
",",
"strict",
")",
":",
"if",
"strict",
":",
"pinyin",
"=",
"convert_finals",
"(",
"pinyin",
")",
"initials",
"=",
"get_initials",
"(",
"pinyin",
",",
"strict",
"=",
"strict",
")",
"or",
"''",
"# 没有声母,整个都是韵母",
"if",
"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | replace_symbol_to_number | 把声调替换为数字 | pypinyin/style/_utils.py | def replace_symbol_to_number(pinyin):
"""把声调替换为数字"""
def _replace(match):
symbol = match.group(0) # 带声调的字符
# 返回使用数字标识声调的字符
return PHONETIC_SYMBOL_DICT[symbol]
# 替换拼音中的带声调字符
return RE_PHONETIC_SYMBOL.sub(_replace, pinyin) | def replace_symbol_to_number(pinyin):
"""把声调替换为数字"""
def _replace(match):
symbol = match.group(0) # 带声调的字符
# 返回使用数字标识声调的字符
return PHONETIC_SYMBOL_DICT[symbol]
# 替换拼音中的带声调字符
return RE_PHONETIC_SYMBOL.sub(_replace, pinyin) | [
"把声调替换为数字"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/style/_utils.py#L52-L60 | [
"def",
"replace_symbol_to_number",
"(",
"pinyin",
")",
":",
"def",
"_replace",
"(",
"match",
")",
":",
"symbol",
"=",
"match",
".",
"group",
"(",
"0",
")",
"# 带声调的字符",
"# 返回使用数字标识声调的字符",
"return",
"PHONETIC_SYMBOL_DICT",
"[",
"symbol",
"]",
"# 替换拼音中的带声调字符",
"r... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | replace_symbol_to_no_symbol | 把带声调字符替换为没有声调的字符 | pypinyin/style/_utils.py | def replace_symbol_to_no_symbol(pinyin):
"""把带声调字符替换为没有声调的字符"""
def _replace(match):
symbol = match.group(0) # 带声调的字符
# 去掉声调: a1 -> a
return RE_NUMBER.sub(r'', PHONETIC_SYMBOL_DICT[symbol])
# 替换拼音中的带声调字符
return RE_PHONETIC_SYMBOL.sub(_replace, pinyin) | def replace_symbol_to_no_symbol(pinyin):
"""把带声调字符替换为没有声调的字符"""
def _replace(match):
symbol = match.group(0) # 带声调的字符
# 去掉声调: a1 -> a
return RE_NUMBER.sub(r'', PHONETIC_SYMBOL_DICT[symbol])
# 替换拼音中的带声调字符
return RE_PHONETIC_SYMBOL.sub(_replace, pinyin) | [
"把带声调字符替换为没有声调的字符"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/style/_utils.py#L63-L71 | [
"def",
"replace_symbol_to_no_symbol",
"(",
"pinyin",
")",
":",
"def",
"_replace",
"(",
"match",
")",
":",
"symbol",
"=",
"match",
".",
"group",
"(",
"0",
")",
"# 带声调的字符",
"# 去掉声调: a1 -> a",
"return",
"RE_NUMBER",
".",
"sub",
"(",
"r''",
",",
"PHONETIC_SYMBOL... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | Seg.cut | 分词
:param text: 待分词的文本
:yield: 单个词语 | pypinyin/contrib/mmseg.py | def cut(self, text):
"""分词
:param text: 待分词的文本
:yield: 单个词语
"""
remain = text
while remain:
matched = ''
# 一次加一个字的匹配
for index in range(len(remain)):
word = remain[:index + 1]
if word in self._prefix_set... | def cut(self, text):
"""分词
:param text: 待分词的文本
:yield: 单个词语
"""
remain = text
while remain:
matched = ''
# 一次加一个字的匹配
for index in range(len(remain)):
word = remain[:index + 1]
if word in self._prefix_set... | [
"分词"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/contrib/mmseg.py#L14-L41 | [
"def",
"cut",
"(",
"self",
",",
"text",
")",
":",
"remain",
"=",
"text",
"while",
"remain",
":",
"matched",
"=",
"''",
"# 一次加一个字的匹配",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"remain",
")",
")",
":",
"word",
"=",
"remain",
"[",
":",
"index",... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | PrefixSet.train | 更新 prefix set
:param word_s: 词语库列表
:type word_s: iterable
:return: None | pypinyin/contrib/mmseg.py | def train(self, word_s):
"""更新 prefix set
:param word_s: 词语库列表
:type word_s: iterable
:return: None
"""
for word in word_s:
# 把词语的每个前缀更新到 prefix_set 中
for index in range(len(word)):
self._set.add(word[:index + 1]) | def train(self, word_s):
"""更新 prefix set
:param word_s: 词语库列表
:type word_s: iterable
:return: None
"""
for word in word_s:
# 把词语的每个前缀更新到 prefix_set 中
for index in range(len(word)):
self._set.add(word[:index + 1]) | [
"更新",
"prefix",
"set"
] | mozillazg/python-pinyin | python | https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/contrib/mmseg.py#L55-L65 | [
"def",
"train",
"(",
"self",
",",
"word_s",
")",
":",
"for",
"word",
"in",
"word_s",
":",
"# 把词语的每个前缀更新到 prefix_set 中",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"word",
")",
")",
":",
"self",
".",
"_set",
".",
"add",
"(",
"word",
"[",
":",
"... | b44756c852e0d2f50f251e3098cbbfef51774979 |
train | get_char_type | 0, 汉字
1, 英文字母
2. 数字
3. 其他 | train/data_utils.py | def get_char_type(ch):
"""
0, 汉字
1, 英文字母
2. 数字
3. 其他
"""
if re.match(en_p, ch):
return 1
elif re.match("\d+", ch):
return 2
elif re.match(re_han, ch):
return 3
else:
return 4 | def get_char_type(ch):
"""
0, 汉字
1, 英文字母
2. 数字
3. 其他
"""
if re.match(en_p, ch):
return 1
elif re.match("\d+", ch):
return 2
elif re.match(re_han, ch):
return 3
else:
return 4 | [
"0",
"汉字",
"1",
"英文字母",
"2",
".",
"数字",
"3",
".",
"其他"
] | rockyzhengwu/FoolNLTK | python | https://github.com/rockyzhengwu/FoolNLTK/blob/f9929edc7b2f1b154b5f9bbd2c0c95203a5bddb3/train/data_utils.py#L80-L94 | [
"def",
"get_char_type",
"(",
"ch",
")",
":",
"if",
"re",
".",
"match",
"(",
"en_p",
",",
"ch",
")",
":",
"return",
"1",
"elif",
"re",
".",
"match",
"(",
"\"\\d+\"",
",",
"ch",
")",
":",
"return",
"2",
"elif",
"re",
".",
"match",
"(",
"re_han",
... | f9929edc7b2f1b154b5f9bbd2c0c95203a5bddb3 |
train | to_latex | Translates a given pyquil Program to a TikZ picture in a Latex document.
:param Program circuit: The circuit to be drawn, represented as a pyquil program.
:param dict settings: An optional dictionary with settings for drawing the circuit. See `get_default_settings`
in `latex_config` for more information a... | pyquil/latex/latex_generation.py | def to_latex(circuit, settings=None):
"""
Translates a given pyquil Program to a TikZ picture in a Latex document.
:param Program circuit: The circuit to be drawn, represented as a pyquil program.
:param dict settings: An optional dictionary with settings for drawing the circuit. See `get_default_setti... | def to_latex(circuit, settings=None):
"""
Translates a given pyquil Program to a TikZ picture in a Latex document.
:param Program circuit: The circuit to be drawn, represented as a pyquil program.
:param dict settings: An optional dictionary with settings for drawing the circuit. See `get_default_setti... | [
"Translates",
"a",
"given",
"pyquil",
"Program",
"to",
"a",
"TikZ",
"picture",
"in",
"a",
"Latex",
"document",
"."
] | rigetti/pyquil | python | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/latex/latex_generation.py#L52-L67 | [
"def",
"to_latex",
"(",
"circuit",
",",
"settings",
"=",
"None",
")",
":",
"if",
"settings",
"is",
"None",
":",
"settings",
"=",
"get_default_settings",
"(",
")",
"text",
"=",
"header",
"(",
"settings",
")",
"text",
"+=",
"body",
"(",
"circuit",
",",
"... | ec98e453084b0037d69d8c3245f6822a5422593d |
train | body | Return the body of the Latex document, including the entire circuit in
TikZ format.
:param Program circuit: The circuit to be drawn, represented as a pyquil program.
:param dict settings:
:return: Latex string to draw the entire circuit.
:rtype: string | pyquil/latex/latex_generation.py | def body(circuit, settings):
"""
Return the body of the Latex document, including the entire circuit in
TikZ format.
:param Program circuit: The circuit to be drawn, represented as a pyquil program.
:param dict settings:
:return: Latex string to draw the entire circuit.
:rtype: string
... | def body(circuit, settings):
"""
Return the body of the Latex document, including the entire circuit in
TikZ format.
:param Program circuit: The circuit to be drawn, represented as a pyquil program.
:param dict settings:
:return: Latex string to draw the entire circuit.
:rtype: string
... | [
"Return",
"the",
"body",
"of",
"the",
"Latex",
"document",
"including",
"the",
"entire",
"circuit",
"in",
"TikZ",
"format",
"."
] | rigetti/pyquil | python | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/latex/latex_generation.py#L70-L145 | [
"def",
"body",
"(",
"circuit",
",",
"settings",
")",
":",
"qubit_instruction_mapping",
"=",
"{",
"}",
"# Allocate each qubit.",
"for",
"inst",
"in",
"circuit",
":",
"if",
"isinstance",
"(",
"inst",
",",
"Measurement",
")",
":",
"inst",
".",
"qubits",
"=",
... | ec98e453084b0037d69d8c3245f6822a5422593d |
train | CircuitTikzGenerator.to_tikz | Generate the TikZ code for one line of the circuit up to a certain
gate.
It modifies the circuit to include only the gates which have not been
drawn. It automatically switches to other lines if the gates on those
lines have to be drawn earlier.
:param int line: Line to generate... | pyquil/latex/latex_generation.py | def to_tikz(self, line, circuit, end=None):
"""
Generate the TikZ code for one line of the circuit up to a certain
gate.
It modifies the circuit to include only the gates which have not been
drawn. It automatically switches to other lines if the gates on those
lines have... | def to_tikz(self, line, circuit, end=None):
"""
Generate the TikZ code for one line of the circuit up to a certain
gate.
It modifies the circuit to include only the gates which have not been
drawn. It automatically switches to other lines if the gates on those
lines have... | [
"Generate",
"the",
"TikZ",
"code",
"for",
"one",
"line",
"of",
"the",
"circuit",
"up",
"to",
"a",
"certain",
"gate",
"."
] | rigetti/pyquil | python | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/latex/latex_generation.py#L175-L271 | [
"def",
"to_tikz",
"(",
"self",
",",
"line",
",",
"circuit",
",",
"end",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"len",
"(",
"circuit",
"[",
"line",
"]",
")",
"tikz_code",
"=",
"[",
"]",
"cmds",
"=",
"circuit",
"[",
"l... | ec98e453084b0037d69d8c3245f6822a5422593d |
train | CircuitTikzGenerator._gate_name | Return the string representation of the gate.
Tries to use gate.tex_str and, if that is not available, uses str(gate)
instead.
:param string gate: Gate object of which to get the name / LaTeX representation.
:return: LaTeX gate name.
:rtype: string | pyquil/latex/latex_generation.py | def _gate_name(self, gate):
"""
Return the string representation of the gate.
Tries to use gate.tex_str and, if that is not available, uses str(gate)
instead.
:param string gate: Gate object of which to get the name / LaTeX representation.
:return: LaTeX gate name.
... | def _gate_name(self, gate):
"""
Return the string representation of the gate.
Tries to use gate.tex_str and, if that is not available, uses str(gate)
instead.
:param string gate: Gate object of which to get the name / LaTeX representation.
:return: LaTeX gate name.
... | [
"Return",
"the",
"string",
"representation",
"of",
"the",
"gate",
"."
] | rigetti/pyquil | python | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/latex/latex_generation.py#L273-L288 | [
"def",
"_gate_name",
"(",
"self",
",",
"gate",
")",
":",
"try",
":",
"name",
"=",
"gate",
".",
"tex_str",
"(",
")",
"except",
"AttributeError",
":",
"name",
"=",
"str",
"(",
"gate",
")",
"return",
"name"
] | ec98e453084b0037d69d8c3245f6822a5422593d |
train | CircuitTikzGenerator._swap_gate | Return the TikZ code for a Swap-gate.
:param lines: List of length 2 denoting the target qubit of the Swap gate.
:type: list[int]
:param ctrl_lines: List of qubit lines which act as controls.
:type: list[int] | pyquil/latex/latex_generation.py | def _swap_gate(self, lines, ctrl_lines):
"""
Return the TikZ code for a Swap-gate.
:param lines: List of length 2 denoting the target qubit of the Swap gate.
:type: list[int]
:param ctrl_lines: List of qubit lines which act as controls.
:type: list[int]
"""
... | def _swap_gate(self, lines, ctrl_lines):
"""
Return the TikZ code for a Swap-gate.
:param lines: List of length 2 denoting the target qubit of the Swap gate.
:type: list[int]
:param ctrl_lines: List of qubit lines which act as controls.
:type: list[int]
"""
... | [
"Return",
"the",
"TikZ",
"code",
"for",
"a",
"Swap",
"-",
"gate",
"."
] | rigetti/pyquil | python | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/latex/latex_generation.py#L290-L327 | [
"def",
"_swap_gate",
"(",
"self",
",",
"lines",
",",
"ctrl_lines",
")",
":",
"delta_pos",
"=",
"self",
".",
"_gate_offset",
"(",
"SWAP",
")",
"gate_width",
"=",
"self",
".",
"_gate_width",
"(",
"SWAP",
")",
"lines",
".",
"sort",
"(",
")",
"gate_str",
"... | ec98e453084b0037d69d8c3245f6822a5422593d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.