desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'The vertical dots per inch value calculated from the XResolution and ResolutionUnit tags of the IFD; defaults to 72 if those tags are not present.'
@property def vert_dpi(self):
return self._dpi(TIFF_TAG.Y_RESOLUTION)
'The number of stacked rows of pixels in the image, |None| if the IFD contains no ``ImageLength`` tag, the expected case when the TIFF is embeded in an Exif image.'
@property def px_height(self):
return self._ifd_entries.get(TIFF_TAG.IMAGE_LENGTH)
'The number of pixels in each row in the image, |None| if the IFD contains no ``ImageWidth`` tag, the expected case when the TIFF is embeded in an Exif image.'
@property def px_width(self):
return self._ifd_entries.get(TIFF_TAG.IMAGE_WIDTH)
'Return either BIG_ENDIAN or LITTLE_ENDIAN depending on the endian indicator found in the TIFF *stream* header, either \'MM\' or \'II\'.'
@classmethod def _detect_endian(cls, stream):
stream.seek(0) endian_str = stream.read(2) return (BIG_ENDIAN if (endian_str == 'MM') else LITTLE_ENDIAN)
'Return the dpi value calculated for *resolution_tag*, which can be either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The calculation is based on the values of both that tag and the TIFF_TAG.RESOLUTION_UNIT tag in this parser\'s |_IfdEntries| instance.'
def _dpi(self, resolution_tag):
ifd_entries = self._ifd_entries if (resolution_tag not in ifd_entries): return 72 resolution_unit = (ifd_entries[TIFF_TAG.RESOLUTION_UNIT] if (TIFF_TAG.RESOLUTION_UNIT in ifd_entries) else 2) if (resolution_unit == 1): return 72 units_per_inch = (1 if (resolution_unit == 2) else 2.54) dots_per_unit = ifd_entries[resolution_tag] return int(round((dots_per_unit * units_per_inch)))
'Return a |StreamReader| instance with wrapping *stream* and having "endian-ness" determined by the \'MM\' or \'II\' indicator in the TIFF stream header.'
@classmethod def _make_stream_reader(cls, stream):
endian = cls._detect_endian(stream) return StreamReader(stream, endian)
'Provides ``in`` operator, e.g. ``tag in ifd_entries``'
def __contains__(self, key):
return self._entries.__contains__(key)
'Provides indexed access, e.g. ``tag_value = ifd_entries[tag_code]``'
def __getitem__(self, key):
return self._entries.__getitem__(key)
'Return a new |_IfdEntries| instance parsed from *stream* starting at *offset*.'
@classmethod def from_stream(cls, stream, offset):
ifd_parser = _IfdParser(stream, offset) entries = dict(((e.tag, e.value) for e in ifd_parser.iter_entries())) return cls(entries)
'Return value of IFD entry having tag matching *tag_code*, or *default* if no matching tag found.'
def get(self, tag_code, default=None):
return self._entries.get(tag_code, default)
'Generate an |_IfdEntry| instance corresponding to each entry in the directory.'
def iter_entries(self):
for idx in range(self._entry_count): dir_entry_offset = ((self._offset + 2) + (idx * 12)) ifd_entry = _IfdEntryFactory(self._stream_rdr, dir_entry_offset) (yield ifd_entry)
'The count of directory entries, read from the top of the IFD header'
@property def _entry_count(self):
return self._stream_rdr.read_short(self._offset)
'Return an |_IfdEntry| subclass instance containing the tag and value of the tag parsed from *stream_rdr* at *offset*. Note this method is common to all subclasses. Override the ``_parse_value()`` method to provide distinctive behavior based on field type.'
@classmethod def from_stream(cls, stream_rdr, offset):
tag_code = stream_rdr.read_short(offset, 0) value_count = stream_rdr.read_long(offset, 4) value_offset = stream_rdr.read_long(offset, 8) value = cls._parse_value(stream_rdr, offset, value_count, value_offset) return cls(tag_code, value)
'Return the value of this field parsed from *stream_rdr* at *offset*. Intended to be overridden by subclasses.'
@classmethod def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
return 'UNIMPLEMENTED FIELD TYPE'
'Short int code that identifies this IFD entry'
@property def tag(self):
return self._tag_code
'Value of this tag, its type being dependent on the tag.'
@property def value(self):
return self._value
'Return the ASCII string parsed from *stream_rdr* at *value_offset*. The length of the string, including a terminating \'\' (NUL) character, is in *value_count*.'
@classmethod def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
return stream_rdr.read_str((value_count - 1), value_offset)
'Return the short int value contained in the *value_offset* field of this entry. Only supports single values at present.'
@classmethod def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
if (value_count == 1): return stream_rdr.read_short(offset, 8) else: return 'Multi-value short integer NOT IMPLEMENTED'
'Return the long int value contained in the *value_offset* field of this entry. Only supports single values at present.'
@classmethod def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
if (value_count == 1): return stream_rdr.read_long(offset, 8) else: return 'Multi-value long integer NOT IMPLEMENTED'
'Return the rational (numerator / denominator) value at *value_offset* in *stream_rdr* as a floating-point number. Only supports single values at present.'
@classmethod def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
if (value_count == 1): numerator = stream_rdr.read_long(value_offset) denominator = stream_rdr.read_long(value_offset, 4) return (numerator / denominator) else: return 'Multi-value Rational NOT IMPLEMENTED'
'MIME content type for this image, unconditionally `image/jpeg` for JPEG images.'
@property def content_type(self):
return MIME_TYPE.JPEG
'Default filename extension, always \'jpg\' for JPG images.'
@property def default_ext(self):
return 'jpg'
'Return |Exif| instance having header properties parsed from Exif image in *stream*.'
@classmethod def from_stream(cls, stream):
markers = _JfifMarkers.from_stream(stream) px_width = markers.sof.px_width px_height = markers.sof.px_height horz_dpi = markers.app1.horz_dpi vert_dpi = markers.app1.vert_dpi return cls(px_width, px_height, horz_dpi, vert_dpi)
'Return a |Jfif| instance having header properties parsed from image in *stream*.'
@classmethod def from_stream(cls, stream):
markers = _JfifMarkers.from_stream(stream) px_width = markers.sof.px_width px_height = markers.sof.px_height horz_dpi = markers.app0.horz_dpi vert_dpi = markers.app0.vert_dpi return cls(px_width, px_height, horz_dpi, vert_dpi)
'Returns a tabular listing of the markers in this instance, which can be handy for debugging and perhaps other uses.'
def __str__(self):
header = ' offset seglen mc name\n======= ====== == =====' tmpl = '%7d %6d %02X %s' rows = [] for marker in self._markers: rows.append((tmpl % (marker.offset, marker.segment_length, ord(marker.marker_code), marker.name))) lines = ([header] + rows) return '\n'.join(lines)
'Return a |_JfifMarkers| instance containing a |_JfifMarker| subclass instance for each marker in *stream*.'
@classmethod def from_stream(cls, stream):
marker_parser = _MarkerParser.from_stream(stream) markers = [] for marker in marker_parser.iter_markers(): markers.append(marker) if (marker.marker_code == JPEG_MARKER_CODE.SOS): break return cls(markers)
'First APP0 marker in image markers.'
@property def app0(self):
for m in self._markers: if (m.marker_code == JPEG_MARKER_CODE.APP0): return m raise KeyError('no APP0 marker in image')
'First APP1 marker in image markers.'
@property def app1(self):
for m in self._markers: if (m.marker_code == JPEG_MARKER_CODE.APP1): return m raise KeyError('no APP1 marker in image')
'First start of frame (SOFn) marker in this sequence.'
@property def sof(self):
for m in self._markers: if (m.marker_code in JPEG_MARKER_CODE.SOF_MARKER_CODES): return m raise KeyError('no start of frame (SOFn) marker in image')
'Return a |_MarkerParser| instance to parse JFIF markers from *stream*.'
@classmethod def from_stream(cls, stream):
stream_reader = StreamReader(stream, BIG_ENDIAN) return cls(stream_reader)
'Generate a (marker_code, segment_offset) 2-tuple for each marker in the JPEG *stream*, in the order they occur in the stream.'
def iter_markers(self):
marker_finder = _MarkerFinder.from_stream(self._stream) start = 0 marker_code = None while (marker_code != JPEG_MARKER_CODE.EOI): (marker_code, segment_offset) = marker_finder.next(start) marker = _MarkerFactory(marker_code, self._stream, segment_offset) (yield marker) start = (segment_offset + marker.segment_length)
'Return a |_MarkerFinder| instance to find JFIF markers in *stream*.'
@classmethod def from_stream(cls, stream):
return cls(stream)
'Return a (marker_code, segment_offset) 2-tuple identifying and locating the first marker in *stream* occuring after offset *start*. The returned *segment_offset* points to the position immediately following the 2-byte marker code, the start of the marker segment, for those markers that have a segment.'
def next(self, start):
position = start while True: position = self._offset_of_next_ff_byte(start=position) (position, byte_) = self._next_non_ff_byte(start=(position + 1)) if (byte_ == '\x00'): continue (marker_code, segment_offset) = (byte_, (position + 1)) break return (marker_code, segment_offset)
'Return an offset, byte 2-tuple for the next byte in *stream* that is not \'ÿ\', starting with the byte at offset *start*. If the byte at offset *start* is not \'ÿ\', *start* and the returned *offset* will be the same.'
def _next_non_ff_byte(self, start):
self._stream.seek(start) byte_ = self._read_byte() while (byte_ == '\xff'): byte_ = self._read_byte() offset_of_non_ff_byte = (self._stream.tell() - 1) return (offset_of_non_ff_byte, byte_)
'Return the offset of the next \'ÿ\' byte in *stream* starting with the byte at offset *start*. Returns *start* if the byte at that offset is a hex 255; it does not necessarily advance in the stream.'
def _offset_of_next_ff_byte(self, start):
self._stream.seek(start) byte_ = self._read_byte() while (byte_ != '\xff'): byte_ = self._read_byte() offset_of_ff_byte = (self._stream.tell() - 1) return offset_of_ff_byte
'Return the next byte read from stream. Raise Exception if stream is at end of file.'
def _read_byte(self):
byte_ = self._stream.read(1) if (not byte_): raise Exception('unexpected end of file') return byte_
'Return a generic |_Marker| instance for the marker at *offset* in *stream* having *marker_code*.'
@classmethod def from_stream(cls, stream, marker_code, offset):
if JPEG_MARKER_CODE.is_standalone(marker_code): segment_length = 0 else: segment_length = stream.read_short(offset) return cls(marker_code, offset, segment_length)
'The single-byte code that identifies the type of this marker, e.g. ``\'à\'`` for start of image (SOI).'
@property def marker_code(self):
return self._marker_code
'The length in bytes of this marker\'s segment'
@property def segment_length(self):
return self._segment_length
'Horizontal dots per inch specified in this marker, defaults to 72 if not specified.'
@property def horz_dpi(self):
return self._dpi(self._x_density)
'Vertical dots per inch specified in this marker, defaults to 72 if not specified.'
@property def vert_dpi(self):
return self._dpi(self._y_density)
'Return dots per inch corresponding to *density* value.'
def _dpi(self, density):
if (self._density_units == 1): dpi = density elif (self._density_units == 2): dpi = int(round((density * 2.54))) else: dpi = 72 return dpi
'Return an |_App0Marker| instance for the APP0 marker at *offset* in *stream*.'
@classmethod def from_stream(cls, stream, marker_code, offset):
segment_length = stream.read_short(offset) density_units = stream.read_byte(offset, 9) x_density = stream.read_short(offset, 10) y_density = stream.read_short(offset, 12) return cls(marker_code, offset, segment_length, density_units, x_density, y_density)
'Extract the horizontal and vertical dots-per-inch value from the APP1 header at *offset* in *stream*.'
@classmethod def from_stream(cls, stream, marker_code, offset):
segment_length = stream.read_short(offset) if cls._is_non_Exif_APP1_segment(stream, offset): return cls(marker_code, offset, segment_length, 72, 72) tiff = cls._tiff_from_exif_segment(stream, offset, segment_length) return cls(marker_code, offset, segment_length, tiff.horz_dpi, tiff.vert_dpi)
'Horizontal dots per inch specified in this marker, defaults to 72 if not specified.'
@property def horz_dpi(self):
return self._horz_dpi
'Vertical dots per inch specified in this marker, defaults to 72 if not specified.'
@property def vert_dpi(self):
return self._vert_dpi
'Return True if the APP1 segment at *offset* in *stream* is NOT an Exif segment, as determined by the ``\'Exif\'`` signature at offset 2 in the segment.'
@classmethod def _is_non_Exif_APP1_segment(cls, stream, offset):
stream.seek((offset + 2)) exif_signature = stream.read(6) return (exif_signature != 'Exif\x00\x00')
'Return a |Tiff| instance parsed from the Exif APP1 segment of *segment_length* at *offset* in *stream*.'
@classmethod def _tiff_from_exif_segment(cls, stream, offset, segment_length):
stream.seek((offset + 8)) segment_bytes = stream.read((segment_length - 8)) substream = BytesIO(segment_bytes) return Tiff.from_stream(substream)
'Return an |_SofMarker| instance for the SOFn marker at *offset* in stream.'
@classmethod def from_stream(cls, stream, marker_code, offset):
segment_length = stream.read_short(offset) px_height = stream.read_short(offset, 3) px_width = stream.read_short(offset, 5) return cls(marker_code, offset, segment_length, px_width, px_height)
'Image height in pixels'
@property def px_height(self):
return self._px_height
'Image width in pixels'
@property def px_width(self):
return self._px_width
'Allow pass-through read() call'
def read(self, count):
return self._stream.read(count)
'Return the int value of the byte at the file position defined by self._base_offset + *base* + *offset*. If *base* is None, the byte is read from the current position in the stream.'
def read_byte(self, base, offset=0):
fmt = 'B' return self._read_int(fmt, base, offset)
'Return the int value of the four bytes at the file position defined by self._base_offset + *base* + *offset*. If *base* is None, the long is read from the current position in the stream. The endian setting of this instance is used to interpret the byte layout of the long.'
def read_long(self, base, offset=0):
fmt = ('<L' if (self._byte_order is LITTLE_ENDIAN) else '>L') return self._read_int(fmt, base, offset)
'Return the int value of the two bytes at the file position determined by *base* and *offset*, similarly to ``read_long()`` above.'
def read_short(self, base, offset=0):
fmt = ('<H' if (self._byte_order is LITTLE_ENDIAN) else '>H') return self._read_int(fmt, base, offset)
'Return a string containing the *char_count* bytes at the file position determined by self._base_offset + *base* + *offset*.'
def read_str(self, char_count, base, offset=0):
def str_struct(char_count): format_ = ('%ds' % char_count) return Struct(format_) struct = str_struct(char_count) chars = self._unpack_item(struct, base, offset) unicode_str = chars.decode('UTF-8') return unicode_str
'Allow pass-through tell() call'
def tell(self):
return self._stream.tell()
'Return |Bmp| instance having header properties parsed from the BMP image in *stream*.'
@classmethod def from_stream(cls, stream):
stream_rdr = StreamReader(stream, LITTLE_ENDIAN) px_width = stream_rdr.read_long(18) px_height = stream_rdr.read_long(22) horz_px_per_meter = stream_rdr.read_long(38) vert_px_per_meter = stream_rdr.read_long(42) horz_dpi = cls._dpi(horz_px_per_meter) vert_dpi = cls._dpi(vert_px_per_meter) return cls(px_width, px_height, horz_dpi, vert_dpi)
'MIME content type for this image, unconditionally `image/bmp` for BMP images.'
@property def content_type(self):
return MIME_TYPE.BMP
'Default filename extension, always \'bmp\' for BMP images.'
@property def default_ext(self):
return 'bmp'
'Return the integer pixels per inch from *px_per_meter*, defaulting to 96 if *px_per_meter* is zero.'
@staticmethod def _dpi(px_per_meter):
if (px_per_meter == 0): return 96 return int(round((px_per_meter * 0.0254)))
'Return a new |Image| subclass instance parsed from the image binary contained in *blob*.'
@classmethod def from_blob(cls, blob):
stream = BytesIO(blob) return cls._from_stream(stream, blob)
'Return a new |Image| subclass instance loaded from the image file identified by *image_descriptor*, a path or file-like object.'
@classmethod def from_file(cls, image_descriptor):
if is_string(image_descriptor): path = image_descriptor with open(path, 'rb') as f: blob = f.read() stream = BytesIO(blob) filename = os.path.basename(path) else: stream = image_descriptor stream.seek(0) blob = stream.read() filename = None return cls._from_stream(stream, blob, filename)
'The bytes of the image \'file\''
@property def blob(self):
return self._blob
'MIME content type for this image, e.g. ``\'image/jpeg\'`` for a JPEG image'
@property def content_type(self):
return self._image_header.content_type
'The file extension for the image. If an actual one is available from a load filename it is used. Otherwise a canonical extension is assigned based on the content type. Does not contain the leading period, e.g. \'jpg\', not \'.jpg\'.'
@lazyproperty def ext(self):
return os.path.splitext(self._filename)[1][1:]
'Original image file name, if loaded from disk, or a generic filename if loaded from an anonymous stream.'
@property def filename(self):
return self._filename
'The horizontal pixel dimension of the image'
@property def px_width(self):
return self._image_header.px_width
'The vertical pixel dimension of the image'
@property def px_height(self):
return self._image_header.px_height
'Integer dots per inch for the width of this image. Defaults to 72 when not present in the file, as is often the case.'
@property def horz_dpi(self):
return self._image_header.horz_dpi
'Integer dots per inch for the height of this image. Defaults to 72 when not present in the file, as is often the case.'
@property def vert_dpi(self):
return self._image_header.vert_dpi
'A |Length| value representing the native width of the image, calculated from the values of `px_width` and `horz_dpi`.'
@property def width(self):
return Inches((self.px_width / self.horz_dpi))
'A |Length| value representing the native height of the image, calculated from the values of `px_height` and `vert_dpi`.'
@property def height(self):
return Inches((self.px_height / self.vert_dpi))
'Return a (cx, cy) 2-tuple representing the native dimensions of this image scaled by applying the following rules to *width* and *height*. If both *width* and *height* are specified, the return value is (*width*, *height*); no scaling is performed. If only one is specified, it is used to compute a scaling factor that is then applied to the unspecified dimension, preserving the aspect ratio of the image. If both *width* and *height* are |None|, the native dimensions are returned. The native dimensions are calculated using the dots-per-inch (dpi) value embedded in the image, defaulting to 72 dpi if no value is specified, as is often the case. The returned values are both |Length| objects.'
def scaled_dimensions(self, width=None, height=None):
if ((width is None) and (height is None)): return (self.width, self.height) if (width is None): scaling_factor = (float(height) / float(self.height)) width = round((self.width * scaling_factor)) if (height is None): scaling_factor = (float(width) / float(self.width)) height = round((self.height * scaling_factor)) return (Emu(width), Emu(height))
'SHA1 hash digest of the image blob'
@lazyproperty def sha1(self):
return hashlib.sha1(self._blob).hexdigest()
'Return an instance of the |Image| subclass corresponding to the format of the image in *stream*.'
@classmethod def _from_stream(cls, stream, blob, filename=None):
image_header = _ImageHeaderFactory(stream) if (filename is None): filename = ('image.%s' % image_header.default_ext) return cls(blob, filename, image_header)
'Abstract property definition, must be implemented by all subclasses.'
@property def content_type(self):
msg = 'content_type property must be implemented by all subclasses of BaseImageHeader' raise NotImplementedError(msg)
'Default filename extension for images of this type. An abstract property definition, must be implemented by all subclasses.'
@property def default_ext(self):
msg = 'default_ext property must be implemented by all subclasses of BaseImageHeader' raise NotImplementedError(msg)
'The horizontal pixel dimension of the image'
@property def px_width(self):
return self._px_width
'The vertical pixel dimension of the image'
@property def px_height(self):
return self._px_height
'Integer dots per inch for the width of this image. Defaults to 72 when not present in the file, as is often the case.'
@property def horz_dpi(self):
return self._horz_dpi
'Integer dots per inch for the height of this image. Defaults to 72 when not present in the file, as is often the case.'
@property def vert_dpi(self):
return self._vert_dpi
'Return |Gif| instance having header properties parsed from GIF image in *stream*.'
@classmethod def from_stream(cls, stream):
(px_width, px_height) = cls._dimensions_from_stream(stream) return cls(px_width, px_height, 72, 72)
'MIME content type for this image, unconditionally `image/gif` for GIF images.'
@property def content_type(self):
return MIME_TYPE.GIF
'Default filename extension, always \'gif\' for GIF images.'
@property def default_ext(self):
return 'gif'
'Append a run to this paragraph containing *text* and having character style identified by style ID *style*. *text* can contain tab (``\t``) characters, which are converted to the appropriate XML form for a tab. *text* can also include newline (``\n``) or carriage return (``\r``) characters, each of which is converted to a line break.'
def add_run(self, text=None, style=None):
r = self._p.add_r() run = Run(r, self) if text: run.text = text if style: run.style = style return run
'A member of the :ref:`WdParagraphAlignment` enumeration specifying the justification setting for this paragraph. A value of |None| indicates the paragraph has no directly-applied alignment value and will inherit its alignment value from its style hierarchy. Assigning |None| to this property removes any directly-applied alignment value.'
@property def alignment(self):
return self._p.alignment
'Return this same paragraph after removing all its content. Paragraph-level formatting, such as style, is preserved.'
def clear(self):
self._p.clear_content() return self
'Return a newly created paragraph, inserted directly before this paragraph. If *text* is supplied, the new paragraph contains that text in a single run. If *style* is provided, that style is assigned to the new paragraph.'
def insert_paragraph_before(self, text=None, style=None):
paragraph = self._insert_paragraph_before() if text: paragraph.add_run(text) if (style is not None): paragraph.style = style return paragraph
'The |ParagraphFormat| object providing access to the formatting properties for this paragraph, such as line spacing and indentation.'
@property def paragraph_format(self):
return ParagraphFormat(self._element)
'Sequence of |Run| instances corresponding to the <w:r> elements in this paragraph.'
@property def runs(self):
return [Run(r, self) for r in self._p.r_lst]
'Read/Write. |_ParagraphStyle| object representing the style assigned to this paragraph. If no explicit style is assigned to this paragraph, its value is the default paragraph style for the document. A paragraph style name can be assigned in lieu of a paragraph style object. Assigning |None| removes any applied style, making its effective value the default paragraph style for the document.'
@property def style(self):
style_id = self._p.style return self.part.get_style(style_id, WD_STYLE_TYPE.PARAGRAPH)
'String formed by concatenating the text of each run in the paragraph. Tabs and line breaks in the XML are mapped to ``\t`` and ``\n`` characters respectively. Assigning text to this property causes all existing paragraph content to be replaced with a single run containing the assigned text. A ``\t`` character in the text is mapped to a ``<w:tab/>`` element and each ``\n`` or ``\r`` character is mapped to a line break. Paragraph-level formatting, such as style, is preserved. All run-level formatting, such as bold or italic, is removed.'
@property def text(self):
text = u'' for run in self.runs: text += run.text return text
'Return a newly created paragraph, inserted directly before this paragraph.'
def _insert_paragraph_before(self):
p = self._p.add_p_before() return Paragraph(p, self._parent)
'Read/write. Causes text in this font to appear in capital letters.'
@property def all_caps(self):
return self._get_bool_prop(u'caps')
'Read/write. Causes text in this font to appear in bold.'
@property def bold(self):
return self._get_bool_prop(u'b')
'A |ColorFormat| object providing a way to get and set the text color for this font.'
@property def color(self):
return ColorFormat(self._element)
'Read/write tri-state value. When |True|, causes the characters in the run to be treated as complex script regardless of their Unicode values.'
@property def complex_script(self):
return self._get_bool_prop(u'cs')
'Read/write tri-state value. When |True|, causes the complex script characters in the run to be displayed in bold typeface.'
@property def cs_bold(self):
return self._get_bool_prop(u'bCs')
'Read/write tri-state value. When |True|, causes the complex script characters in the run to be displayed in italic typeface.'
@property def cs_italic(self):
return self._get_bool_prop(u'iCs')