code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
OPENJP2.opj_decode_tile_data.argtypes = [CODEC_TYPE,
ctypes.c_uint32,
ctypes.POINTER(ctypes.c_uint8),
ctypes.c_uint32,
STREAM_TYPE_P]
OPENJP2.opj_decode_tile_data.restype = check_error
datap = data.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
OPENJP2.opj_decode_tile_data(codec,
ctypes.c_uint32(tidx),
datap,
ctypes.c_uint32(data_size),
stream)
|
def decode_tile_data(codec, tidx, data, data_size, stream)
|
Reads tile data.
Wraps the openjp2 library function opj_decode_tile_data.
Parameters
----------
codec : CODEC_TYPE
The JPEG2000 codec
tile_index : int
The index of the tile being decoded
data : array
Holds a memory block into which data will be decoded.
data_size : int
The size of data in bytes
stream : STREAM_TYPE_P
The stream to decode.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_decode fails.
| 2.459902
| 2.293536
| 1.072537
|
OPENJP2.opj_create_decompress.argtypes = [CODEC_FORMAT_TYPE]
OPENJP2.opj_create_decompress.restype = CODEC_TYPE
codec = OPENJP2.opj_create_decompress(codec_format)
return codec
|
def create_decompress(codec_format)
|
Creates a J2K/JP2 decompress structure.
Wraps the openjp2 library function opj_create_decompress.
Parameters
----------
codec_format : int
Specifies codec to select. Should be one of CODEC_J2K or CODEC_JP2.
Returns
-------
codec : Reference to CODEC_TYPE instance.
| 3.16206
| 3.017767
| 1.047814
|
OPENJP2.opj_destroy_codec.argtypes = [CODEC_TYPE]
OPENJP2.opj_destroy_codec.restype = ctypes.c_void_p
OPENJP2.opj_destroy_codec(codec)
|
def destroy_codec(codec)
|
Destroy a decompressor handle.
Wraps the openjp2 library function opj_destroy_codec.
Parameters
----------
codec : CODEC_TYPE
Decompressor handle to destroy.
| 3.347893
| 2.826657
| 1.1844
|
OPENJP2.opj_encode.argtypes = [CODEC_TYPE, STREAM_TYPE_P]
OPENJP2.opj_encode.restype = check_error
OPENJP2.opj_encode(codec, stream)
|
def encode(codec, stream)
|
Wraps openjp2 library function opj_encode.
Encode an image into a JPEG 2000 codestream.
Parameters
----------
codec : CODEC_TYPE
The jpeg2000 codec.
stream : STREAM_TYPE_P
The stream to which data is written.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_encode fails.
| 5.743344
| 3.745041
| 1.533586
|
OPENJP2.opj_get_decoded_tile.argtypes = [CODEC_TYPE,
STREAM_TYPE_P,
ctypes.POINTER(ImageType),
ctypes.c_uint32]
OPENJP2.opj_get_decoded_tile.restype = check_error
OPENJP2.opj_get_decoded_tile(codec, stream, imagep, tile_index)
|
def get_decoded_tile(codec, stream, imagep, tile_index)
|
get the decoded tile from the codec
Wraps the openjp2 library function opj_get_decoded_tile.
Parameters
----------
codec : CODEC_TYPE
The jpeg2000 codec.
stream : STREAM_TYPE_P
The input stream.
image : ImageType
Output image structure.
tiler_index : int
Index of the tile which will be decoded.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_get_decoded_tile fails.
| 3.553562
| 2.676682
| 1.3276
|
OPENJP2.opj_end_compress.argtypes = [CODEC_TYPE, STREAM_TYPE_P]
OPENJP2.opj_end_compress.restype = check_error
OPENJP2.opj_end_compress(codec, stream)
|
def end_compress(codec, stream)
|
End of compressing the current image.
Wraps the openjp2 library function opj_end_compress.
Parameters
----------
codec : CODEC_TYPE
Compressor handle.
stream : STREAM_TYPE_P
Output stream buffer.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_end_compress fails.
| 4.196396
| 3.177088
| 1.320831
|
OPENJP2.opj_end_decompress.argtypes = [CODEC_TYPE, STREAM_TYPE_P]
OPENJP2.opj_end_decompress.restype = check_error
OPENJP2.opj_end_decompress(codec, stream)
|
def end_decompress(codec, stream)
|
End of decompressing the current image.
Wraps the openjp2 library function opj_end_decompress.
Parameters
----------
codec : CODEC_TYPE
Compressor handle.
stream : STREAM_TYPE_P
Output stream buffer.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_end_decompress fails.
| 3.934242
| 2.941031
| 1.337708
|
OPENJP2.opj_image_destroy.argtypes = [ctypes.POINTER(ImageType)]
OPENJP2.opj_image_destroy.restype = ctypes.c_void_p
OPENJP2.opj_image_destroy(image)
|
def image_destroy(image)
|
Deallocate any resources associated with an image.
Wraps the openjp2 library function opj_image_destroy.
Parameters
----------
image : ImageType pointer
Image resource to be disposed.
| 3.909357
| 3.072242
| 1.272477
|
OPENJP2.opj_image_create.argtypes = [ctypes.c_uint32,
ctypes.POINTER(ImageComptParmType),
COLOR_SPACE_TYPE]
OPENJP2.opj_image_create.restype = ctypes.POINTER(ImageType)
image = OPENJP2.opj_image_create(len(comptparms),
comptparms,
clrspc)
return image
|
def image_create(comptparms, clrspc)
|
Creates a new image structure.
Wraps the openjp2 library function opj_image_create.
Parameters
----------
cmptparms : comptparms_t
The component parameters.
clrspc : int
Specifies the color space.
Returns
-------
image : ImageType
Reference to ImageType instance.
| 3.997983
| 3.825583
| 1.045065
|
ARGTYPES = [ctypes.c_uint32,
ctypes.POINTER(ImageComptParmType),
COLOR_SPACE_TYPE]
OPENJP2.opj_image_tile_create.argtypes = ARGTYPES
OPENJP2.opj_image_tile_create.restype = ctypes.POINTER(ImageType)
image = OPENJP2.opj_image_tile_create(len(comptparms),
comptparms,
clrspc)
return image
|
def image_tile_create(comptparms, clrspc)
|
Creates a new image structure.
Wraps the openjp2 library function opj_image_tile_create.
Parameters
----------
cmptparms : comptparms_t
The component parameters.
clrspc : int
Specifies the color space.
Returns
-------
image : ImageType
Reference to ImageType instance.
| 3.853431
| 3.742248
| 1.02971
|
ARGTYPES = [STREAM_TYPE_P, CODEC_TYPE,
ctypes.POINTER(ctypes.POINTER(ImageType))]
OPENJP2.opj_read_header.argtypes = ARGTYPES
OPENJP2.opj_read_header.restype = check_error
imagep = ctypes.POINTER(ImageType)()
OPENJP2.opj_read_header(stream, codec, ctypes.byref(imagep))
return imagep
|
def read_header(stream, codec)
|
Decodes an image header.
Wraps the openjp2 library function opj_read_header.
Parameters
----------
stream: STREAM_TYPE_P
The JPEG2000 stream.
codec: codec_t
The JPEG2000 codec to read.
Returns
-------
imagep : reference to ImageType instance
The image structure initialized with image characteristics.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_read_header fails.
| 4.638935
| 3.313737
| 1.39991
|
ARGTYPES = [CODEC_TYPE,
STREAM_TYPE_P,
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_int32),
ctypes.POINTER(ctypes.c_int32),
ctypes.POINTER(ctypes.c_int32),
ctypes.POINTER(ctypes.c_int32),
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(BOOL_TYPE)]
OPENJP2.opj_read_tile_header.argtypes = ARGTYPES
OPENJP2.opj_read_tile_header.restype = check_error
tile_index = ctypes.c_uint32()
data_size = ctypes.c_uint32()
col0 = ctypes.c_int32()
row0 = ctypes.c_int32()
col1 = ctypes.c_int32()
row1 = ctypes.c_int32()
ncomps = ctypes.c_uint32()
go_on = BOOL_TYPE()
OPENJP2.opj_read_tile_header(codec,
stream,
ctypes.byref(tile_index),
ctypes.byref(data_size),
ctypes.byref(col0),
ctypes.byref(row0),
ctypes.byref(col1),
ctypes.byref(row1),
ctypes.byref(ncomps),
ctypes.byref(go_on))
go_on = bool(go_on.value)
return (tile_index.value,
data_size.value,
col0.value,
row0.value,
col1.value,
row1.value,
ncomps.value,
go_on)
|
def read_tile_header(codec, stream)
|
Reads a tile header.
Wraps the openjp2 library function opj_read_tile_header.
Parameters
----------
codec : codec_t
The JPEG2000 codec to read.
stream : STREAM_TYPE_P
The JPEG2000 stream.
Returns
-------
tile_index : int
index of the tile being decoded
data_size : int
number of bytes for the decoded area
x0, y0 : int
upper left-most coordinate of tile
x1, y1 : int
lower right-most coordinate of tile
ncomps : int
number of components in the tile
go_on : bool
indicates that decoding should continue
Raises
------
RuntimeError
If the OpenJPEG library routine opj_read_tile_header fails.
| 1.77494
| 1.564373
| 1.134602
|
OPENJP2.opj_set_decode_area.argtypes = [CODEC_TYPE,
ctypes.POINTER(ImageType),
ctypes.c_int32,
ctypes.c_int32,
ctypes.c_int32,
ctypes.c_int32]
OPENJP2.opj_set_decode_area.restype = check_error
OPENJP2.opj_set_decode_area(codec, image,
ctypes.c_int32(start_x),
ctypes.c_int32(start_y),
ctypes.c_int32(end_x),
ctypes.c_int32(end_y))
|
def set_decode_area(codec, image, start_x=0, start_y=0, end_x=0, end_y=0)
|
Wraps openjp2 library function opj_set_decode area.
Sets the given area to be decoded. This function should be called right
after read_header and before any tile header reading.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_decompress function.
image : ImageType pointer
The decoded image previously set by read_header.
start_x, start_y : optional, int
The left and upper position of the rectangle to decode.
end_x, end_y : optional, int
The right and lower position of the rectangle to decode.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_set_decode_area fails.
| 1.926038
| 1.822749
| 1.056667
|
ARGTYPES = [ctypes.POINTER(DecompressionParametersType)]
OPENJP2.opj_set_default_decoder_parameters.argtypes = ARGTYPES
OPENJP2.opj_set_default_decoder_parameters.restype = ctypes.c_void_p
dparams = DecompressionParametersType()
OPENJP2.opj_set_default_decoder_parameters(ctypes.byref(dparams))
return dparams
|
def set_default_decoder_parameters()
|
Wraps openjp2 library function opj_set_default_decoder_parameters.
Sets decoding parameters to default values.
Returns
-------
dparam : DecompressionParametersType
Decompression parameters.
| 3.315639
| 2.354946
| 1.407947
|
ARGTYPES = [ctypes.POINTER(CompressionParametersType)]
OPENJP2.opj_set_default_encoder_parameters.argtypes = ARGTYPES
OPENJP2.opj_set_default_encoder_parameters.restype = ctypes.c_void_p
cparams = CompressionParametersType()
OPENJP2.opj_set_default_encoder_parameters(ctypes.byref(cparams))
return cparams
|
def set_default_encoder_parameters()
|
Wraps openjp2 library function opj_set_default_encoder_parameters.
Sets encoding parameters to default values. That means
lossless
1 tile
size of precinct : 2^15 x 2^15 (means 1 precinct)
size of code-block : 64 x 64
number of resolutions: 6
no SOP marker in the codestream
no EPH marker in the codestream
no sub-sampling in x or y direction
no mode switch activated
progression order: LRCP
no index file
no ROI upshifted
no offset of the origin of the image
no offset of the origin of the tiles
reversible DWT 5-3
The signature for this function differs from its C library counterpart, as
the the C function pass-by-reference parameter becomes the Python return
value.
Returns
-------
cparameters : CompressionParametersType
Compression parameters.
| 3.298639
| 2.411221
| 1.368037
|
OPENJP2.opj_set_error_handler.argtypes = [CODEC_TYPE,
ctypes.c_void_p,
ctypes.c_void_p]
OPENJP2.opj_set_error_handler.restype = check_error
OPENJP2.opj_set_error_handler(codec, handler, data)
|
def set_error_handler(codec, handler, data=None)
|
Wraps openjp2 library function opj_set_error_handler.
Set the error handler use by openjpeg.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_compress function.
handler : python function
The callback function to be used.
user_data : anything
User/client data.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_set_error_handler fails.
| 2.834312
| 2.589952
| 1.094349
|
OPENJP2.opj_set_info_handler.argtypes = [CODEC_TYPE,
ctypes.c_void_p,
ctypes.c_void_p]
OPENJP2.opj_set_info_handler.restype = check_error
OPENJP2.opj_set_info_handler(codec, handler, data)
|
def set_info_handler(codec, handler, data=None)
|
Wraps openjp2 library function opj_set_info_handler.
Set the info handler use by openjpeg.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_compress function.
handler : python function
The callback function to be used.
user_data : anything
User/client data.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_set_info_handler fails.
| 2.863484
| 2.549581
| 1.12312
|
OPENJP2.opj_set_warning_handler.argtypes = [CODEC_TYPE,
ctypes.c_void_p,
ctypes.c_void_p]
OPENJP2.opj_set_warning_handler.restype = check_error
OPENJP2.opj_set_warning_handler(codec, handler, data)
|
def set_warning_handler(codec, handler, data=None)
|
Wraps openjp2 library function opj_set_warning_handler.
Set the warning handler use by openjpeg.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_compress function.
handler : python function
The callback function to be used.
user_data : anything
User/client data.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_set_warning_handler fails.
| 2.931956
| 2.646526
| 1.107851
|
ARGTYPES = [CODEC_TYPE, ctypes.POINTER(DecompressionParametersType)]
OPENJP2.opj_setup_decoder.argtypes = ARGTYPES
OPENJP2.opj_setup_decoder.restype = check_error
OPENJP2.opj_setup_decoder(codec, ctypes.byref(dparams))
|
def setup_decoder(codec, dparams)
|
Wraps openjp2 library function opj_setup_decoder.
Setup the decoder with decompression parameters.
Parameters
----------
codec: CODEC_TYPE
Codec initialized by create_compress function.
dparams: DecompressionParametersType
Decompression parameters.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_setup_decoder fails.
| 5.240896
| 3.202051
| 1.636731
|
ARGTYPES = [CODEC_TYPE,
ctypes.POINTER(CompressionParametersType),
ctypes.POINTER(ImageType)]
OPENJP2.opj_setup_encoder.argtypes = ARGTYPES
OPENJP2.opj_setup_encoder.restype = check_error
OPENJP2.opj_setup_encoder(codec, ctypes.byref(cparams), image)
|
def setup_encoder(codec, cparams, image)
|
Wraps openjp2 library function opj_setup_encoder.
Setup the encoder parameters using the current image and using user
parameters.
Parameters
----------
codec : CODEC_TYPE
codec initialized by create_compress function
cparams : CompressionParametersType
compression parameters
image : ImageType
input-filled image
Raises
------
RuntimeError
If the OpenJPEG library routine opj_setup_encoder fails.
| 4.367958
| 3.061871
| 1.426565
|
OPENJP2.opj_start_compress.argtypes = [CODEC_TYPE,
ctypes.POINTER(ImageType),
STREAM_TYPE_P]
OPENJP2.opj_start_compress.restype = check_error
OPENJP2.opj_start_compress(codec, image, stream)
|
def start_compress(codec, image, stream)
|
Wraps openjp2 library function opj_start_compress.
Start to compress the current image.
Parameters
----------
codec : CODEC_TYPE
Compressor handle.
image : pointer to ImageType
Input filled image.
stream : STREAM_TYPE_P
Input stream.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_start_compress fails.
| 4.492912
| 3.148629
| 1.426942
|
ARGTYPES = [ctypes.c_char_p, ctypes.c_int32]
OPENJP2.opj_stream_create_default_file_stream.argtypes = ARGTYPES
OPENJP2.opj_stream_create_default_file_stream.restype = STREAM_TYPE_P
read_stream = 1 if isa_read_stream else 0
file_argument = ctypes.c_char_p(fname.encode())
stream = OPENJP2.opj_stream_create_default_file_stream(file_argument,
read_stream)
return stream
|
def stream_create_default_file_stream(fname, isa_read_stream)
|
Wraps openjp2 library function opj_stream_create_default_vile_stream.
Sets the stream to be a file stream. This function is only valid for the
2.1 version of the openjp2 library.
Parameters
----------
fname : str
Specifies a file.
isa_read_stream: bool
True (read) or False (write)
Returns
-------
stream : stream_t
An OpenJPEG file stream.
| 3.091166
| 2.845359
| 1.086389
|
OPENJP2.opj_stream_destroy.argtypes = [STREAM_TYPE_P]
OPENJP2.opj_stream_destroy.restype = ctypes.c_void_p
OPENJP2.opj_stream_destroy(stream)
|
def stream_destroy(stream)
|
Wraps openjp2 library function opj_stream_destroy.
Destroys the stream created by create_stream.
Parameters
----------
stream : STREAM_TYPE_P
The file stream.
| 3.813633
| 2.603522
| 1.464798
|
OPENJP2.opj_write_tile.argtypes = [CODEC_TYPE,
ctypes.c_uint32,
ctypes.POINTER(ctypes.c_uint8),
ctypes.c_uint32,
STREAM_TYPE_P]
OPENJP2.opj_write_tile.restype = check_error
datap = data.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
OPENJP2.opj_write_tile(codec,
ctypes.c_uint32(int(tile_index)),
datap,
ctypes.c_uint32(int(data_size)),
stream)
|
def write_tile(codec, tile_index, data, data_size, stream)
|
Wraps openjp2 library function opj_write_tile.
Write a tile into an image.
Parameters
----------
codec : CODEC_TYPE
The jpeg2000 codec
tile_index : int
The index of the tile to write, zero-indexing assumed
data : array
Image data arranged in usual C-order
data_size : int
Size of a tile in bytes
stream : STREAM_TYPE_P
The stream to write data to
Raises
------
RuntimeError
If the OpenJPEG library routine opj_write_tile fails.
| 2.573149
| 2.314654
| 1.111678
|
''' Function to calculate the length of the required padding
Input: (int) str_len - String length of the text
(int) blocksize - block size of the algorithm
Returns: (int) number of required pad bytes for string of size.'''
assert 0 < blocksize < 255, 'blocksize must be between 0 and 255'
assert str_len > 0 , 'string length should be non-negative'
'If the last block is already full, append an extra block of padding'
pad_len = blocksize - (str_len % blocksize)
return pad_len
|
def paddingLength(str_len, blocksize=AES_blocksize)
|
Function to calculate the length of the required padding
Input: (int) str_len - String length of the text
(int) blocksize - block size of the algorithm
Returns: (int) number of required pad bytes for string of size.
| 5.57778
| 2.653243
| 2.10225
|
'''CMS padding: Remove padding with bytes containing the number of padding bytes '''
try:
pad_len = ord(str[-1]) # last byte contains number of padding bytes
except TypeError:
pad_len = str[-1]
assert pad_len <= blocksize, 'padding error'
assert pad_len <= len(str), 'padding error'
return str[:-pad_len]
|
def removeCMSPadding(str, blocksize=AES_blocksize)
|
CMS padding: Remove padding with bytes containing the number of padding bytes
| 6.167215
| 3.901879
| 1.580576
|
'''Bit padding a.k.a. One and Zeroes Padding
A single set ('1') bit is added to the message and then as many reset ('0') bits as required (possibly none) are added.
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
Return: Padded string according to ANSI X.923 standart
Used in when padding bit strings.
0x80 in binary is 10000000
0x00 in binary is 00000000
Defined in ANSI X.923 (based on NIST Special Publication 800-38A) and ISO/IEC 9797-1 as Padding Method 2.
Used in hash functions MD5 and SHA, described in RFC 1321 step 3.1.
'''
pad_len = paddingLength(len(str), blocksize) - 1
padding = chr(0x80)+'\0'*pad_len
return str + padding
|
def appendBitPadding(str, blocksize=AES_blocksize)
|
Bit padding a.k.a. One and Zeroes Padding
A single set ('1') bit is added to the message and then as many reset ('0') bits as required (possibly none) are added.
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
Return: Padded string according to ANSI X.923 standart
Used in when padding bit strings.
0x80 in binary is 10000000
0x00 in binary is 00000000
Defined in ANSI X.923 (based on NIST Special Publication 800-38A) and ISO/IEC 9797-1 as Padding Method 2.
Used in hash functions MD5 and SHA, described in RFC 1321 step 3.1.
| 8.532208
| 1.543234
| 5.528783
|
'Remove bit padding with 0x80 followed by zero (null) bytes'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == '\0':
pad_len += 1
else:
break
pad_len += 1
str = str[:-pad_len]
return str
|
def removeBitPadding(str, blocksize=AES_blocksize)
|
Remove bit padding with 0x80 followed by zero (null) bytes
| 5.365757
| 3.577829
| 1.499724
|
'Remove Padding with zeroes + last byte equal to the number of padding bytes'
try:
pad_len = ord(str[-1]) # last byte contains number of padding bytes
except TypeError:
pad_len = str[-1]
assert pad_len < blocksize, 'padding error'
assert pad_len < len(str), 'padding error'
return str[:-pad_len]
|
def removeZeroLenPadding(str, blocksize=AES_blocksize)
|
Remove Padding with zeroes + last byte equal to the number of padding bytes
| 5.873479
| 3.886566
| 1.511226
|
'Pad with null bytes'
pad_len = paddingLength(len(str), blocksize)
padding = '\0'*pad_len
return str + padding
|
def appendNullPadding(str, blocksize=AES_blocksize)
|
Pad with null bytes
| 8.676059
| 8.105521
| 1.070389
|
'Remove padding with null bytes'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == '\0':
pad_len += 1
else:
break
str = str[:-pad_len]
return str
|
def removeNullPadding(str, blocksize=AES_blocksize)
|
Remove padding with null bytes
| 4.118583
| 3.917571
| 1.051311
|
'Pad with spaces'
pad_len = paddingLength(len(str), blocksize)
padding = '\0'*pad_len
return str + padding
|
def appendSpacePadding(str, blocksize=AES_blocksize)
|
Pad with spaces
| 10.298545
| 9.065825
| 1.135974
|
'Remove padding with spaces'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == ' ':
pad_len += 1
else:
break
str = str[:-pad_len]
return str
|
def removeSpacePadding(str, blocksize=AES_blocksize)
|
Remove padding with spaces
| 5.122557
| 4.58153
| 1.118089
|
'ISO 10126 Padding (withdrawn, 2007): Pad with random bytes + last byte equal to the number of padding bytes'
pad_len = paddingLength(len(str), blocksize) - 1
from os import urandom
padding = urandom(pad_len)+chr(pad_len)
return str + padding
|
def appendRandomLenPadding(str, blocksize=AES_blocksize)
|
ISO 10126 Padding (withdrawn, 2007): Pad with random bytes + last byte equal to the number of padding bytes
| 9.915067
| 3.299091
| 3.005394
|
'ISO 10126 Padding (withdrawn, 2007): Remove Padding with random bytes + last byte equal to the number of padding bytes'
pad_len = ord(str[-1]) # last byte contains number of padding bytes
assert pad_len < blocksize, 'padding error'
assert pad_len < len(str), 'padding error'
return str[:-pad_len]
|
def removeRandomLenPadding(str, blocksize=AES_blocksize)
|
ISO 10126 Padding (withdrawn, 2007): Remove Padding with random bytes + last byte equal to the number of padding bytes
| 8.479912
| 2.986717
| 2.839208
|
''' Pad (append padding to) string for use with symmetric encryption algorithm
Input: (string) str - String to be padded
(int) blocksize - block size of the encryption algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Padded string according to chosen padding mode
'''
if mode not in (0,'CMS'):
for k in MODES.keys():
if mode in k:
return globals()['append'+k[1]+'Padding'](str, blocksize)
else:
return appendCMSPadding(str, blocksize)
else:
return appendCMSPadding(str, blocksize)
|
def appendPadding(str, blocksize=AES_blocksize, mode='CMS')
|
Pad (append padding to) string for use with symmetric encryption algorithm
Input: (string) str - String to be padded
(int) blocksize - block size of the encryption algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Padded string according to chosen padding mode
| 8.50696
| 2.72971
| 3.116433
|
''' Remove padding from string
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Decrypted string without padding
'''
if mode not in (0,'CMS'):
for k in MODES.keys():
if mode in k:
return globals()['append'+k[1]+'Padding'](str, blocksize)
else:
return removeCMSPadding(str, blocksize)
else:
return removeCMSPadding(str, blocksize)
|
def removePadding(str, blocksize=AES_blocksize, mode='CMS')
|
Remove padding from string
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Decrypted string without padding
| 9.377034
| 3.494151
| 2.683637
|
msg = "OpenJPEG library error: {0}".format(msg.decode('utf-8').rstrip())
opj2.set_error_message(msg)
|
def _default_error_handler(msg, _)
|
Default error handler callback for libopenjp2.
| 11.601921
| 7.273788
| 1.595031
|
library_msg = library_msg.decode('utf-8').rstrip()
msg = "OpenJPEG library warning: {0}".format(library_msg)
warnings.warn(msg, UserWarning)
|
def _default_warning_handler(library_msg, _)
|
Default warning handler callback.
| 4.730823
| 4.526074
| 1.045237
|
self.length = os.path.getsize(self.filename)
with open(self.filename, 'rb') as fptr:
# Make sure we have a JPEG2000 file. It could be either JP2 or
# J2C. Check for J2C first, single box in that case.
read_buffer = fptr.read(2)
signature, = struct.unpack('>H', read_buffer)
if signature == 0xff4f:
self._codec_format = opj2.CODEC_J2K
# That's it, we're done. The codestream object is only
# produced upon explicit request.
return
self._codec_format = opj2.CODEC_JP2
# Should be JP2.
# First 4 bytes should be 12, the length of the 'jP ' box.
# 2nd 4 bytes should be the box ID ('jP ').
# 3rd 4 bytes should be the box signature (13, 10, 135, 10).
fptr.seek(0)
read_buffer = fptr.read(12)
values = struct.unpack('>I4s4B', read_buffer)
box_length = values[0]
box_id = values[1]
signature = values[2:]
if (((box_length != 12) or (box_id != b'jP ') or
(signature != (13, 10, 135, 10)))):
msg = '{filename} is not a JPEG 2000 file.'
msg = msg.format(filename=self.filename)
raise IOError(msg)
# Back up and start again, we know we have a superbox (box of
# boxes) here.
fptr.seek(0)
self.box = self.parse_superbox(fptr)
self._validate()
|
def parse(self)
|
Parses the JPEG 2000 file.
Raises
------
IOError
The file was not JPEG 2000.
| 4.225542
| 4.090886
| 1.032916
|
# A JP2 file must contain certain boxes. The 2nd box must be a file
# type box.
if not isinstance(self.box[1], FileTypeBox):
msg = "{filename} does not contain a valid File Type box."
msg = msg.format(filename=self.filename)
raise IOError(msg)
# A jp2-branded file cannot contain an "any ICC profile
ftyp = self.box[1]
if ftyp.brand == 'jp2 ':
jp2h = [box for box in self.box if box.box_id == 'jp2h'][0]
colrs = [box for box in jp2h.box if box.box_id == 'colr']
for colr in colrs:
if colr.method not in (core.ENUMERATED_COLORSPACE,
core.RESTRICTED_ICC_PROFILE):
msg = ("Color Specification box method must specify "
"either an enumerated colorspace or a restricted "
"ICC profile if the file type box brand is 'jp2 '.")
warnings.warn(msg, UserWarning)
|
def _validate(self)
|
Validate the JPEG 2000 outermost superbox. These checks must be
done at a file level.
| 5.81827
| 5.190063
| 1.12104
|
if re.match("1.5|2.0", version.openjpeg_version) is not None:
msg = ("Writing Cinema2K or Cinema4K files is not supported with "
"OpenJPEG library versions less than 2.1.0. The installed "
"version of OpenJPEG is {version}.")
msg = msg.format(version=version.openjpeg_version)
raise IOError(msg)
# Cinema modes imply MCT.
self._cparams.tcp_mct = 1
if cinema_mode == 'cinema2k':
if fps not in [24, 48]:
msg = 'Cinema2K frame rate must be either 24 or 48.'
raise IOError(msg)
if fps == 24:
self._cparams.rsiz = core.OPJ_PROFILE_CINEMA_2K
self._cparams.max_comp_size = core.OPJ_CINEMA_24_COMP
self._cparams.max_cs_size = core.OPJ_CINEMA_24_CS
else:
self._cparams.rsiz = core.OPJ_PROFILE_CINEMA_2K
self._cparams.max_comp_size = core.OPJ_CINEMA_48_COMP
self._cparams.max_cs_size = core.OPJ_CINEMA_48_CS
else:
# cinema4k
self._cparams.rsiz = core.OPJ_PROFILE_CINEMA_4K
|
def _set_cinema_params(self, cinema_mode, fps)
|
Populate compression parameters structure for cinema2K.
Parameters
----------
params : ctypes struct
Corresponds to compression parameters structure used by the
library.
cinema_mode : {'cinema2k', 'cinema4k}
Use either Cinema2K or Cinema4K profile.
fps : {24, 48}
Frames per second.
| 3.069323
| 2.790583
| 1.099886
|
if re.match("0|1.[0-4]", version.openjpeg_version) is not None:
msg = ("You must have at least version 1.5 of OpenJPEG "
"in order to write images.")
raise RuntimeError(msg)
self._determine_colorspace(**kwargs)
self._populate_cparams(img_array, **kwargs)
if opj2.OPENJP2 is not None:
self._write_openjp2(img_array, verbose=verbose)
else:
self._write_openjpeg(img_array, verbose=verbose)
|
def _write(self, img_array, verbose=False, **kwargs)
|
Write image data to a JP2/JPX/J2k file. Intended usage of the
various parameters follows that of OpenJPEG's opj_compress utility.
This method can only be used to create JPEG 2000 images that can fit
in memory.
| 5.601061
| 5.527263
| 1.013352
|
if img_array.ndim == 2:
# Force the image to be 3D. Just makes things easier later on.
img_array = img_array.reshape(img_array.shape[0],
img_array.shape[1],
1)
self._populate_comptparms(img_array)
with ExitStack() as stack:
image = opj.image_create(self._comptparms, self._colorspace)
stack.callback(opj.image_destroy, image)
numrows, numcols, numlayers = img_array.shape
# set image offset and reference grid
image.contents.x0 = self._cparams.image_offset_x0
image.contents.y0 = self._cparams.image_offset_y0
image.contents.x1 = (image.contents.x0 +
(numcols - 1) * self._cparams.subsampling_dx +
1)
image.contents.y1 = (image.contents.y0 +
(numrows - 1) * self._cparams.subsampling_dy +
1)
# Stage the image data to the openjpeg data structure.
for k in range(0, numlayers):
layer = np.ascontiguousarray(img_array[:, :, k],
dtype=np.int32)
dest = image.contents.comps[k].data
src = layer.ctypes.data
ctypes.memmove(dest, src, layer.nbytes)
cinfo = opj.create_compress(self._cparams.codec_fmt)
stack.callback(opj.destroy_compress, cinfo)
# Setup the info, warning, and error handlers.
# Always use the warning and error handler. Use of an info
# handler is optional.
event_mgr = opj.EventMgrType()
_info_handler = _INFO_CALLBACK if verbose else None
event_mgr.info_handler = _info_handler
event_mgr.warning_handler = ctypes.cast(_WARNING_CALLBACK,
ctypes.c_void_p)
event_mgr.error_handler = ctypes.cast(_ERROR_CALLBACK,
ctypes.c_void_p)
opj.setup_encoder(cinfo, ctypes.byref(self._cparams), image)
cio = opj.cio_open(cinfo)
stack.callback(opj.cio_close, cio)
if not opj.encode(cinfo, cio, image):
raise IOError("Encode error.")
pos = opj.cio_tell(cio)
blob = ctypes.string_at(cio.contents.buffer, pos)
fptr = open(self.filename, 'wb')
stack.callback(fptr.close)
fptr.write(blob)
self.parse()
|
def _write_openjpeg(self, img_array, verbose=False)
|
Write JPEG 2000 file using OpenJPEG 1.5 interface.
| 3.515585
| 3.46456
| 1.014728
|
if cparams.codec_fmt == opj2.CODEC_J2K and colorspace is not None:
msg = 'Do not specify a colorspace when writing a raw codestream.'
raise IOError(msg)
|
def _validate_j2k_colorspace(self, cparams, colorspace)
|
Cannot specify a colorspace with J2K.
| 9.939561
| 8.235937
| 1.206852
|
if cparams.cblockw_init != 0 and cparams.cblockh_init != 0:
# These fields ARE zero if uninitialized.
width = cparams.cblockw_init
height = cparams.cblockh_init
if height * width > 4096 or height < 4 or width < 4:
msg = ("The code block area is specified as "
"{height} x {width} = {area} square pixels. "
"Code block area cannot exceed 4096 square pixels. "
"Code block height and width dimensions must be larger "
"than 4 pixels.")
msg = msg.format(height=height, width=width,
area=height * width)
raise IOError(msg)
if ((math.log(height, 2) != math.floor(math.log(height, 2)) or
math.log(width, 2) != math.floor(math.log(width, 2)))):
msg = ("Bad code block size ({height} x {width}). "
"The dimensions must be powers of 2.")
msg = msg.format(height=height, width=width)
raise IOError(msg)
|
def _validate_codeblock_size(self, cparams)
|
Code block dimensions must satisfy certain restrictions.
They must both be a power of 2 and the total area defined by the width
and height cannot be either too great or too small for the codec.
| 3.040788
| 2.847071
| 1.068041
|
code_block_specified = False
if cparams.cblockw_init != 0 and cparams.cblockh_init != 0:
code_block_specified = True
if cparams.res_spec != 0:
# precinct size was not specified if this field is zero.
for j in range(cparams.res_spec):
prch = cparams.prch_init[j]
prcw = cparams.prcw_init[j]
if j == 0 and code_block_specified:
height, width = cparams.cblockh_init, cparams.cblockw_init
if prch < height * 2 or prcw < width * 2:
msg = ("The highest resolution precinct size "
"({prch} x {prcw}) must be at least twice that "
"of the code block size "
"({cbh} x {cbw}).")
msg = msg.format(prch=prch, prcw=prcw,
cbh=height, cbw=width)
raise IOError(msg)
if ((math.log(prch, 2) != math.floor(math.log(prch, 2)) or
math.log(prcw, 2) != math.floor(math.log(prcw, 2)))):
msg = ("Bad precinct size ({height} x {width}). "
"Precinct dimensions must be powers of 2.")
msg = msg.format(height=prch, width=prcw)
raise IOError(msg)
|
def _validate_precinct_size(self, cparams)
|
Precinct dimensions must satisfy certain restrictions if specified.
They must both be a power of 2 and must both be at least twice the
size of their codeblock size counterparts.
| 2.787969
| 2.569859
| 1.084872
|
if img_array.ndim == 1 or img_array.ndim > 3:
msg = "{0}D imagery is not allowed.".format(img_array.ndim)
raise IOError(msg)
|
def _validate_image_rank(self, img_array)
|
Images must be either 2D or 3D.
| 3.851944
| 3.417691
| 1.12706
|
if img_array.dtype != np.uint8 and img_array.dtype != np.uint16:
msg = ("Only uint8 and uint16 datatypes are currently supported "
"when writing.")
raise RuntimeError(msg)
|
def _validate_image_datatype(self, img_array)
|
Only uint8 and uint16 images are currently supported.
| 3.241579
| 2.688522
| 1.205711
|
self._validate_j2k_colorspace(cparams, colorspace)
self._validate_codeblock_size(cparams)
self._validate_precinct_size(cparams)
self._validate_image_rank(img_array)
self._validate_image_datatype(img_array)
|
def _validate_compression_params(self, img_array, cparams, colorspace)
|
Check that the compression parameters are valid.
Parameters
----------
img_array : ndarray
Image data to be written to file.
cparams : CompressionParametersType(ctypes.Structure)
Corresponds to cparameters_t type in openjp2 headers.
| 3.730128
| 3.805552
| 0.98018
|
if colorspace is None:
# Must infer the colorspace from the image dimensions.
if len(self.shape) < 3:
# A single channel image is grayscale.
self._colorspace = opj2.CLRSPC_GRAY
elif self.shape[2] == 1 or self.shape[2] == 2:
# A single channel image or an image with two channels is going
# to be greyscale.
self._colorspace = opj2.CLRSPC_GRAY
else:
# Anything else must be RGB, right?
self._colorspace = opj2.CLRSPC_SRGB
else:
if colorspace.lower() not in ('rgb', 'grey', 'gray'):
msg = 'Invalid colorspace "{0}".'.format(colorspace)
raise IOError(msg)
elif colorspace.lower() == 'rgb' and self.shape[2] < 3:
msg = 'RGB colorspace requires at least 3 components.'
raise IOError(msg)
# Turn the colorspace from a string to the enumerated value that
# the library expects.
COLORSPACE_MAP = {'rgb': opj2.CLRSPC_SRGB,
'gray': opj2.CLRSPC_GRAY,
'grey': opj2.CLRSPC_GRAY,
'ycc': opj2.CLRSPC_YCC}
self._colorspace = COLORSPACE_MAP[colorspace.lower()]
|
def _determine_colorspace(self, colorspace=None, **kwargs)
|
Determine the colorspace from the supplied inputs.
Parameters
----------
colorspace : str, optional
Either 'rgb' or 'gray'.
| 2.728587
| 2.802135
| 0.973753
|
if img_array.ndim == 2:
# Force the image to be 3D. Just makes things easier later on.
numrows, numcols = img_array.shape
img_array = img_array.reshape(numrows, numcols, 1)
self._populate_comptparms(img_array)
with ExitStack() as stack:
image = opj2.image_create(self._comptparms, self._colorspace)
stack.callback(opj2.image_destroy, image)
self._populate_image_struct(image, img_array)
codec = opj2.create_compress(self._cparams.codec_fmt)
stack.callback(opj2.destroy_codec, codec)
if self._verbose or verbose:
info_handler = _INFO_CALLBACK
else:
info_handler = None
opj2.set_info_handler(codec, info_handler)
opj2.set_warning_handler(codec, _WARNING_CALLBACK)
opj2.set_error_handler(codec, _ERROR_CALLBACK)
opj2.setup_encoder(codec, self._cparams, image)
strm = opj2.stream_create_default_file_stream(self.filename,
False)
stack.callback(opj2.stream_destroy, strm)
opj2.start_compress(codec, image, strm)
opj2.encode(codec, strm)
opj2.end_compress(codec, strm)
# Refresh the metadata.
self.parse()
|
def _write_openjp2(self, img_array, verbose=False)
|
Write JPEG 2000 file using OpenJPEG 2.x interface.
| 3.616432
| 3.537549
| 1.022299
|
if self._codec_format == opj2.CODEC_J2K:
msg = "Only JP2 files can currently have boxes appended to them."
raise IOError(msg)
if not ((box.box_id == 'xml ') or
(box.box_id == 'uuid' and
box.uuid == UUID('be7acfcb-97a9-42e8-9c71-999491e3afac'))):
msg = ("Only XML boxes and XMP UUID boxes can currently be "
"appended.")
raise IOError(msg)
# Check the last box. If the length field is zero, then rewrite
# the length field to reflect the true length of the box.
with open(self.filename, 'rb') as ifile:
offset = self.box[-1].offset
ifile.seek(offset)
read_buffer = ifile.read(4)
box_length, = struct.unpack('>I', read_buffer)
if box_length == 0:
# Reopen the file in write mode and rewrite the length field.
true_box_length = os.path.getsize(ifile.name) - offset
with open(self.filename, 'r+b') as ofile:
ofile.seek(offset)
write_buffer = struct.pack('>I', true_box_length)
ofile.write(write_buffer)
# Can now safely append the box.
with open(self.filename, 'ab') as ofile:
box.write(ofile)
self.parse()
|
def append(self, box)
|
Append a JP2 box to the file in-place.
Parameters
----------
box : Jp2Box
Instance of a JP2 box. Only UUID and XML boxes can currently be
appended.
| 4.128146
| 3.877584
| 1.064618
|
if boxes is None:
boxes = self._get_default_jp2_boxes()
self._validate_jp2_box_sequence(boxes)
with open(filename, 'wb') as ofile:
for box in boxes:
if box.box_id != 'jp2c':
box.write(ofile)
else:
self._write_wrapped_codestream(ofile, box)
ofile.flush()
jp2 = Jp2k(filename)
return jp2
|
def wrap(self, filename, boxes=None)
|
Create a new JP2/JPX file wrapped in a new set of JP2 boxes.
This method is primarily aimed at wrapping a raw codestream in a set of
of JP2 boxes (turning it into a JP2 file instead of just a raw
codestream), or rewrapping a codestream in a JP2 file in a new "jacket"
of JP2 boxes.
Parameters
----------
filename : str
JP2 file to be created from a raw codestream.
boxes : list
JP2 box definitions to define the JP2 file format. If not
provided, a default ""jacket" is assumed, consisting of JP2
signature, file type, JP2 header, and contiguous codestream boxes.
A JPX file rewrapped without the boxes argument results in a JP2
file encompassing the first codestream.
Returns
-------
Jp2k
Newly wrapped Jp2k object.
Examples
--------
>>> import glymur, tempfile
>>> jfile = glymur.data.goodstuff()
>>> j2k = glymur.Jp2k(jfile)
>>> tfile = tempfile.NamedTemporaryFile(suffix='jp2')
>>> jp2 = j2k.wrap(tfile.name)
| 4.080906
| 3.845164
| 1.061309
|
# Codestreams require a bit more care.
# Am I a raw codestream?
if len(self.box) == 0:
# Yes, just write the codestream box header plus all
# of myself out to file.
ofile.write(struct.pack('>I', self.length + 8))
ofile.write(b'jp2c')
with open(self.filename, 'rb') as ifile:
ofile.write(ifile.read())
return
# OK, I'm a jp2/jpx file. Need to find out where the raw codestream
# actually starts.
offset = box.offset
if offset == -1:
if self.box[1].brand == 'jpx ':
msg = ("The codestream box must have its offset and length "
"attributes fully specified if the file type brand is "
"JPX.")
raise IOError(msg)
# Find the first codestream in the file.
jp2c = [_box for _box in self.box if _box.box_id == 'jp2c']
offset = jp2c[0].offset
# Ready to write the codestream.
with open(self.filename, 'rb') as ifile:
ifile.seek(offset)
# Verify that the specified codestream is right.
read_buffer = ifile.read(8)
L, T = struct.unpack_from('>I4s', read_buffer, 0)
if T != b'jp2c':
msg = "Unable to locate the specified codestream."
raise IOError(msg)
if L == 0:
# The length of the box is presumed to last until the end of
# the file. Compute the effective length of the box.
L = os.path.getsize(ifile.name) - ifile.tell() + 8
elif L == 1:
# The length of the box is in the XL field, a 64-bit value.
read_buffer = ifile.read(8)
L, = struct.unpack('>Q', read_buffer)
ifile.seek(offset)
read_buffer = ifile.read(L)
ofile.write(read_buffer)
|
def _write_wrapped_codestream(self, ofile, box)
|
Write wrapped codestream.
| 4.113712
| 4.086976
| 1.006542
|
# Try to create a reasonable default.
boxes = [JPEG2000SignatureBox(),
FileTypeBox(),
JP2HeaderBox(),
ContiguousCodestreamBox()]
height = self.codestream.segment[1].ysiz
width = self.codestream.segment[1].xsiz
num_components = len(self.codestream.segment[1].xrsiz)
if num_components < 3:
colorspace = core.GREYSCALE
else:
if len(self.box) == 0:
# Best guess is SRGB
colorspace = core.SRGB
else:
# Take whatever the first jp2 header / color specification
# says.
jp2hs = [box for box in self.box if box.box_id == 'jp2h']
colorspace = jp2hs[0].box[1].colorspace
boxes[2].box = [ImageHeaderBox(height=height, width=width,
num_components=num_components),
ColourSpecificationBox(colorspace=colorspace)]
return boxes
|
def _get_default_jp2_boxes(self)
|
Create a default set of JP2 boxes.
| 4.749409
| 4.555532
| 1.042559
|
# Remove the first ellipsis we find.
rows = slice(0, numrows)
cols = slice(0, numcols)
bands = slice(0, numbands)
if index[0] is Ellipsis:
if len(index) == 2:
# jp2k[..., other_slice]
newindex = (rows, cols, index[1])
else:
# jp2k[..., cols, bands]
newindex = (rows, index[1], index[2])
elif index[1] is Ellipsis:
if len(index) == 2:
# jp2k[rows, ...]
newindex = (index[0], cols, bands)
else:
# jp2k[rows, ..., bands]
newindex = (index[0], cols, index[2])
else:
# Assume that we don't have 4D imagery, of course.
newindex = (index[0], index[1], bands)
return newindex
|
def _remove_ellipsis(self, index, numrows, numcols, numbands)
|
resolve the first ellipsis in the index so that it references the image
Parameters
----------
index : tuple
tuple of index arguments, presumably one of them is the Ellipsis
numrows, numcols, numbands : int
image dimensions
Returns
-------
tuple
Same as index, except that the first Ellipsis is replaced with
a proper slice whose start and stop members are not None
| 2.687404
| 2.770465
| 0.970019
|
if re.match("0|1.[01234]", version.openjpeg_version):
msg = ("You must have a version of OpenJPEG at least as high as "
"1.5.0 before you can read JPEG2000 images with glymur. "
"Your version is {version}")
raise TypeError(msg.format(version=version.openjpeg_version))
if version.openjpeg_version_tuple[0] < 2:
img = self._read_openjpeg(**kwargs)
else:
img = self._read_openjp2(**kwargs)
return img
|
def _read(self, **kwargs)
|
Read a JPEG 2000 image.
Returns
-------
ndarray
The image data.
Raises
------
RuntimeError
if the proper version of the OpenJPEG library is not available
| 5.229651
| 4.897444
| 1.067833
|
dxs = np.array(self.codestream.segment[1].xrsiz)
dys = np.array(self.codestream.segment[1].yrsiz)
if np.any(dxs - dxs[0]) or np.any(dys - dys[0]):
msg = ("The read_bands method should be used with the subsampling "
"factors are different. "
"\n\n{siz_segment}")
msg = msg.format(siz_segment=str(self.codestream.segment[1]))
raise IOError(msg)
|
def _subsampling_sanity_check(self)
|
Check for differing subsample factors.
| 5.388247
| 4.802732
| 1.121913
|
self._subsampling_sanity_check()
self._populate_dparams(rlevel)
with ExitStack() as stack:
try:
self._dparams.decod_format = self._codec_format
dinfo = opj.create_decompress(self._dparams.decod_format)
event_mgr = opj.EventMgrType()
handler = ctypes.cast(_INFO_CALLBACK, ctypes.c_void_p)
event_mgr.info_handler = handler if self.verbose else None
event_mgr.warning_handler = ctypes.cast(_WARNING_CALLBACK,
ctypes.c_void_p)
event_mgr.error_handler = ctypes.cast(_ERROR_CALLBACK,
ctypes.c_void_p)
opj.set_event_mgr(dinfo, ctypes.byref(event_mgr))
opj.setup_decoder(dinfo, self._dparams)
with open(self.filename, 'rb') as fptr:
src = fptr.read()
cio = opj.cio_open(dinfo, src)
raw_image = opj.decode(dinfo, cio)
stack.callback(opj.image_destroy, raw_image)
stack.callback(opj.destroy_decompress, dinfo)
stack.callback(opj.cio_close, cio)
image = self._extract_image(raw_image)
except ValueError:
opj2.check_error(0)
if area is not None:
x0, y0, x1, y1 = area
extent = 2 ** rlevel
area = [int(round(float(x) / extent + 2 ** -20)) for x in area]
rows = slice(area[0], area[2], None)
cols = slice(area[1], area[3], None)
image = image[rows, cols]
return image
|
def _read_openjpeg(self, rlevel=0, verbose=False, area=None)
|
Read a JPEG 2000 image using libopenjpeg.
Parameters
----------
rlevel : int, optional
Factor by which to rlevel output resolution. Use -1 to get the
lowest resolution thumbnail.
verbose : bool, optional
Print informational messages produced by the OpenJPEG library.
area : tuple, optional
Specifies decoding image area,
(first_row, first_col, last_row, last_col)
Returns
-------
ndarray
The image data.
Raises
------
RuntimeError
If the image has differing subsample factors.
| 3.711572
| 3.731481
| 0.994665
|
self.layer = layer
self._subsampling_sanity_check()
self._populate_dparams(rlevel, tile=tile, area=area)
image = self._read_openjp2_common()
return image
|
def _read_openjp2(self, rlevel=0, layer=None, area=None, tile=None,
verbose=False)
|
Read a JPEG 2000 image using libopenjp2.
Parameters
----------
layer : int, optional
Number of quality layer to decode.
rlevel : int, optional
Factor by which to rlevel output resolution. Use -1 to get the
lowest resolution thumbnail.
area : tuple, optional
Specifies decoding image area,
(first_row, first_col, last_row, last_col)
tile : int, optional
Number of tile to decode.
verbose : bool, optional
Print informational messages produced by the OpenJPEG library.
Returns
-------
ndarray
The image data.
Raises
------
RuntimeError
If the image has differing subsample factors.
| 8.025135
| 11.205548
| 0.716175
|
with ExitStack() as stack:
filename = self.filename
stream = opj2.stream_create_default_file_stream(filename, True)
stack.callback(opj2.stream_destroy, stream)
codec = opj2.create_decompress(self._codec_format)
stack.callback(opj2.destroy_codec, codec)
opj2.set_error_handler(codec, _ERROR_CALLBACK)
opj2.set_warning_handler(codec, _WARNING_CALLBACK)
if self._verbose:
opj2.set_info_handler(codec, _INFO_CALLBACK)
else:
opj2.set_info_handler(codec, None)
opj2.setup_decoder(codec, self._dparams)
raw_image = opj2.read_header(stream, codec)
stack.callback(opj2.image_destroy, raw_image)
if self._dparams.nb_tile_to_decode:
opj2.get_decoded_tile(codec, stream, raw_image,
self._dparams.tile_index)
else:
opj2.set_decode_area(codec, raw_image,
self._dparams.DA_x0, self._dparams.DA_y0,
self._dparams.DA_x1, self._dparams.DA_y1)
opj2.decode(codec, stream, raw_image)
opj2.end_decompress(codec, stream)
image = self._extract_image(raw_image)
return image
|
def _read_openjp2_common(self)
|
Read a JPEG 2000 image using libopenjp2.
Returns
-------
ndarray or lst
Either the image as an ndarray or a list of ndarrays, each item
corresponding to one band.
| 2.957278
| 2.933218
| 1.008203
|
if opj2.OPENJP2 is not None:
dparam = opj2.set_default_decoder_parameters()
else:
dparam = opj.DecompressionParametersType()
opj.set_default_decoder_parameters(ctypes.byref(dparam))
infile = self.filename.encode()
nelts = opj2.PATH_LEN - len(infile)
infile += b'0' * nelts
dparam.infile = infile
# Return raw codestream components instead of "interpolating" the
# colormap?
dparam.flags |= 1 if self.ignore_pclr_cmap_cdef else 0
dparam.decod_format = self._codec_format
dparam.cp_layer = self._layer
# Must check the specified rlevel against the maximum.
if rlevel != 0:
# Must check the specified rlevel against the maximum.
max_rlevel = self.codestream.segment[2].num_res
if rlevel == -1:
# -1 is shorthand for the largest rlevel
rlevel = max_rlevel
elif rlevel < -1 or rlevel > max_rlevel:
msg = ("rlevel must be in the range [-1, {max_rlevel}] "
"for this image.")
msg = msg.format(max_rlevel=max_rlevel)
raise IOError(msg)
dparam.cp_reduce = rlevel
if area is not None:
if area[0] < 0 or area[1] < 0 or area[2] <= 0 or area[3] <= 0:
msg = ("The upper left corner coordinates must be nonnegative "
"and the lower right corner coordinates must be "
"positive. The specified upper left and lower right "
"coordinates are ({y0}, {x0}) and ({y1}, {x1}).")
msg = msg.format(x0=area[1], y0=area[0],
x1=area[3], y1=area[2])
raise IOError(msg)
dparam.DA_y0 = area[0]
dparam.DA_x0 = area[1]
dparam.DA_y1 = area[2]
dparam.DA_x1 = area[3]
if tile is not None:
dparam.tile_index = tile
dparam.nb_tile_to_decode = 1
self._dparams = dparam
|
def _populate_dparams(self, rlevel, tile=None, area=None)
|
Populate decompression structure with appropriate input parameters.
Parameters
----------
rlevel : int
Factor by which to rlevel output resolution.
area : tuple
Specifies decoding image area,
(first_row, first_col, last_row, last_col)
tile : int
Number of tile to decode.
| 3.889696
| 3.716107
| 1.046713
|
if version.openjpeg_version < '2.1.0':
msg = ("You must have at least version 2.1.0 of OpenJPEG "
"installed before using this method. Your version of "
"OpenJPEG is {version}.")
msg = msg.format(version=version.openjpeg_version)
raise IOError(msg)
self.ignore_pclr_cmap_cdef = ignore_pclr_cmap_cdef
self.layer = layer
self._populate_dparams(rlevel, tile=tile, area=area)
lst = self._read_openjp2_common()
return lst
|
def read_bands(self, rlevel=0, layer=None, area=None, tile=None,
verbose=False, ignore_pclr_cmap_cdef=False)
|
Read a JPEG 2000 image.
The only time you should use this method is when the image has
different subsampling factors across components. Otherwise you should
use the read method.
Parameters
----------
layer : int, optional
Number of quality layer to decode.
rlevel : int, optional
Factor by which to rlevel output resolution.
area : tuple, optional
Specifies decoding image area,
(first_row, first_col, last_row, last_col)
tile : int, optional
Number of tile to decode.
ignore_pclr_cmap_cdef : bool
Whether or not to ignore the pclr, cmap, or cdef boxes during any
color transformation. Defaults to False.
verbose : bool, optional
Print informational messages produced by the OpenJPEG library.
Returns
-------
list
List of the individual image components.
See also
--------
read : read JPEG 2000 image
Examples
--------
>>> import glymur
>>> jfile = glymur.data.nemo()
>>> jp = glymur.Jp2k(jfile)
>>> components_lst = jp.read_bands(rlevel=1)
| 3.850727
| 4.600368
| 0.837048
|
ncomps = raw_image.contents.numcomps
# Make a pass thru the image, see if any of the band datatypes or
# dimensions differ.
dtypes, nrows, ncols = [], [], []
for k in range(raw_image.contents.numcomps):
component = raw_image.contents.comps[k]
dtypes.append(self._component2dtype(component))
nrows.append(component.h)
ncols.append(component.w)
is_cube = all(r == nrows[0] and c == ncols[0] and d == dtypes[0]
for r, c, d in zip(nrows, ncols, dtypes))
if is_cube:
image = np.zeros((nrows[0], ncols[0], ncomps), dtypes[0])
else:
image = []
for k in range(raw_image.contents.numcomps):
component = raw_image.contents.comps[k]
self._validate_nonzero_image_size(nrows[k], ncols[k], k)
addr = ctypes.addressof(component.data.contents)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
nelts = nrows[k] * ncols[k]
band = np.ctypeslib.as_array(
(ctypes.c_int32 * nelts).from_address(addr))
if is_cube:
image[:, :, k] = np.reshape(band.astype(dtypes[k]),
(nrows[k], ncols[k]))
else:
image.append(np.reshape(band.astype(dtypes[k]),
(nrows[k], ncols[k])))
if is_cube and image.shape[2] == 1:
# The third dimension has just a single layer. Make the image
# data 2D instead of 3D.
image.shape = image.shape[0:2]
return image
|
def _extract_image(self, raw_image)
|
Extract unequally-sized image bands.
Parameters
----------
raw_image : reference to openjpeg ImageType instance
The image structure initialized with image characteristics.
Returns
-------
list or ndarray
If the JPEG 2000 image has unequally-sized components, they are
extracted into a list, otherwise a numpy array.
| 2.816924
| 2.76121
| 1.020177
|
if component.prec > 16:
msg = "Unhandled precision: {0} bits.".format(component.prec)
raise IOError(msg)
if component.sgnd:
dtype = np.int8 if component.prec <=8 else np.int16
else:
dtype = np.uint8 if component.prec <=8 else np.uint16
return dtype
|
def _component2dtype(self, component)
|
Determin the appropriate numpy datatype for an OpenJPEG component.
Parameters
----------
component : ctypes pointer to ImageCompType (image_comp_t)
single image component structure.
Returns
-------
builtins.type
numpy datatype to be used to construct an image array
| 3.928677
| 4.157628
| 0.944932
|
with open(self.filename, 'rb') as fptr:
if self._codec_format == opj2.CODEC_J2K:
codestream = Codestream(fptr, self.length,
header_only=header_only)
else:
box = [x for x in self.box if x.box_id == 'jp2c']
fptr.seek(box[0].offset)
read_buffer = fptr.read(8)
(box_length, _) = struct.unpack('>I4s', read_buffer)
if box_length == 0:
# The length of the box is presumed to last until the end
# of the file. Compute the effective length of the box.
box_length = os.path.getsize(fptr.name) - fptr.tell() + 8
elif box_length == 1:
# Seek past the XL field.
read_buffer = fptr.read(8)
box_length, = struct.unpack('>Q', read_buffer)
codestream = Codestream(fptr, box_length - 8,
header_only=header_only)
return codestream
|
def get_codestream(self, header_only=True)
|
Retrieve codestream.
Parameters
----------
header_only : bool, optional
If True, only marker segments in the main header are parsed.
Supplying False may impose a large performance penalty.
Returns
-------
Codestream
Object describing the codestream syntax.
Examples
--------
>>> import glymur
>>> jfile = glymur.data.nemo()
>>> jp2 = glymur.Jp2k(jfile)
>>> codestream = jp2.get_codestream()
>>> print(codestream.segment[1])
SIZ marker segment @ (3233, 47)
Profile: no profile
Reference Grid Height, Width: (1456 x 2592)
Vertical, Horizontal Reference Grid Offset: (0 x 0)
Reference Tile Height, Width: (1456 x 2592)
Vertical, Horizontal Reference Tile Offset: (0 x 0)
Bitdepth: (8, 8, 8)
Signed: (False, False, False)
Vertical, Horizontal Subsampling: ((1, 1), (1, 1), (1, 1))
| 3.77187
| 4.247666
| 0.887986
|
numrows, numcols, num_comps = imgdata.shape
for k in range(num_comps):
self._validate_nonzero_image_size(numrows, numcols, k)
# set image offset and reference grid
image.contents.x0 = self._cparams.image_offset_x0
image.contents.y0 = self._cparams.image_offset_y0
image.contents.x1 = (image.contents.x0 +
(numcols - 1) * self._cparams.subsampling_dx + 1)
image.contents.y1 = (image.contents.y0 +
(numrows - 1) * self._cparams.subsampling_dy + 1)
# Stage the image data to the openjpeg data structure.
for k in range(0, num_comps):
if self._cparams.rsiz in (core.OPJ_PROFILE_CINEMA_2K,
core.OPJ_PROFILE_CINEMA_4K):
image.contents.comps[k].prec = 12
image.contents.comps[k].bpp = 12
layer = np.ascontiguousarray(imgdata[:, :, k], dtype=np.int32)
dest = image.contents.comps[k].data
src = layer.ctypes.data
ctypes.memmove(dest, src, layer.nbytes)
return image
|
def _populate_image_struct(self, image, imgdata)
|
Populates image struct needed for compression.
Parameters
----------
image : ImageType(ctypes.Structure)
Corresponds to image_t type in openjp2 headers.
img_array : ndarray
Image data to be written to file.
| 3.529183
| 3.53643
| 0.997951
|
# Only two precisions are possible.
if img_array.dtype == np.uint8:
comp_prec = 8
else:
comp_prec = 16
numrows, numcols, num_comps = img_array.shape
if version.openjpeg_version_tuple[0] == 1:
comptparms = (opj.ImageComptParmType * num_comps)()
else:
comptparms = (opj2.ImageComptParmType * num_comps)()
for j in range(num_comps):
comptparms[j].dx = self._cparams.subsampling_dx
comptparms[j].dy = self._cparams.subsampling_dy
comptparms[j].w = numcols
comptparms[j].h = numrows
comptparms[j].x0 = self._cparams.image_offset_x0
comptparms[j].y0 = self._cparams.image_offset_y0
comptparms[j].prec = comp_prec
comptparms[j].bpp = comp_prec
comptparms[j].sgnd = 0
self._comptparms = comptparms
|
def _populate_comptparms(self, img_array)
|
Instantiate and populate comptparms structure.
This structure defines the image components.
Parameters
----------
img_array : ndarray
Image data to be written to file.
| 2.844812
| 2.907592
| 0.978408
|
if nrows == 0 or ncols == 0:
# Letting this situation continue would segfault openjpeg.
msg = "Component {0} has dimensions {1} x {2}"
msg = msg.format(component_index, nrows, ncols)
raise IOError(msg)
|
def _validate_nonzero_image_size(self, nrows, ncols, component_index)
|
The image cannot have area of zero.
| 5.672947
| 5.171959
| 1.096866
|
JP2_IDS = ['colr', 'cdef', 'cmap', 'jp2c', 'ftyp', 'ihdr', 'jp2h',
'jP ', 'pclr', 'res ', 'resc', 'resd', 'xml ', 'ulst',
'uinf', 'url ', 'uuid']
self._validate_signature_compatibility(boxes)
self._validate_jp2h(boxes)
self._validate_jp2c(boxes)
if boxes[1].brand == 'jpx ':
self._validate_jpx_box_sequence(boxes)
else:
# Validate the JP2 box IDs.
count = self._collect_box_count(boxes)
for box_id in count.keys():
if box_id not in JP2_IDS:
msg = ("The presence of a '{0}' box requires that the "
"file type brand be set to 'jpx '.")
raise IOError(msg.format(box_id))
self._validate_jp2_colr(boxes)
|
def _validate_jp2_box_sequence(self, boxes)
|
Run through series of tests for JP2 box legality.
This is non-exhaustive.
| 4.942582
| 4.932213
| 1.002102
|
lst = [box for box in boxes if box.box_id == 'jp2h']
jp2h = lst[0]
for colr in [box for box in jp2h.box if box.box_id == 'colr']:
if colr.approximation != 0:
msg = ("A JP2 colr box cannot have a non-zero approximation "
"field.")
raise IOError(msg)
|
def _validate_jp2_colr(self, boxes)
|
Validate JP2 requirements on colour specification boxes.
| 4.432118
| 4.15693
| 1.0662
|
self._validate_label(boxes)
self._validate_jpx_compatibility(boxes, boxes[1].compatibility_list)
self._validate_singletons(boxes)
self._validate_top_level(boxes)
|
def _validate_jpx_box_sequence(self, boxes)
|
Run through series of tests for JPX box legality.
| 7.673061
| 6.308832
| 1.216241
|
# Check for a bad sequence of boxes.
# 1st two boxes must be 'jP ' and 'ftyp'
if boxes[0].box_id != 'jP ' or boxes[1].box_id != 'ftyp':
msg = ("The first box must be the signature box and the second "
"must be the file type box.")
raise IOError(msg)
# The compatibility list must contain at a minimum 'jp2 '.
if 'jp2 ' not in boxes[1].compatibility_list:
msg = "The ftyp box must contain 'jp2 ' in the compatibility list."
raise IOError(msg)
|
def _validate_signature_compatibility(self, boxes)
|
Validate the file signature and compatibility status.
| 5.341023
| 4.583126
| 1.165367
|
# jp2c must be preceeded by jp2h
jp2h_lst = [idx for (idx, box) in enumerate(boxes)
if box.box_id == 'jp2h']
jp2h_idx = jp2h_lst[0]
jp2c_lst = [idx for (idx, box) in enumerate(boxes)
if box.box_id == 'jp2c']
if len(jp2c_lst) == 0:
msg = ("A codestream box must be defined in the outermost "
"list of boxes.")
raise IOError(msg)
jp2c_idx = jp2c_lst[0]
if jp2h_idx >= jp2c_idx:
msg = "The codestream box must be preceeded by a jp2 header box."
raise IOError(msg)
|
def _validate_jp2c(self, boxes)
|
Validate the codestream box in relation to other boxes.
| 2.748242
| 2.562622
| 1.072433
|
self._check_jp2h_child_boxes(boxes, 'top-level')
jp2h_lst = [box for box in boxes if box.box_id == 'jp2h']
jp2h = jp2h_lst[0]
# 1st jp2 header box cannot be empty.
if len(jp2h.box) == 0:
msg = "The JP2 header superbox cannot be empty."
raise IOError(msg)
# 1st jp2 header box must be ihdr
if jp2h.box[0].box_id != 'ihdr':
msg = ("The first box in the jp2 header box must be the image "
"header box.")
raise IOError(msg)
# colr must be present in jp2 header box.
colr_lst = [j for (j, box) in enumerate(jp2h.box)
if box.box_id == 'colr']
if len(colr_lst) == 0:
msg = "The jp2 header box must contain a color definition box."
raise IOError(msg)
colr = jp2h.box[colr_lst[0]]
self._validate_channel_definition(jp2h, colr)
|
def _validate_jp2h(self, boxes)
|
Validate the JP2 Header box.
| 2.788621
| 2.657312
| 1.049414
|
cdef_lst = [j for (j, box) in enumerate(jp2h.box)
if box.box_id == 'cdef']
if len(cdef_lst) > 1:
msg = ("Only one channel definition box is allowed in the "
"JP2 header.")
raise IOError(msg)
elif len(cdef_lst) == 1:
cdef = jp2h.box[cdef_lst[0]]
if colr.colorspace == core.SRGB:
if any([chan + 1 not in cdef.association or
cdef.channel_type[chan] != 0 for chan in [0, 1, 2]]):
msg = ("All color channels must be defined in the "
"channel definition box.")
raise IOError(msg)
elif colr.colorspace == core.GREYSCALE:
if 0 not in cdef.channel_type:
msg = ("All color channels must be defined in the "
"channel definition box.")
raise IOError(msg)
|
def _validate_channel_definition(self, jp2h, colr)
|
Validate the channel definition box.
| 3.001297
| 2.780045
| 1.079586
|
JP2H_CHILDREN = set(['bpcc', 'cdef', 'cmap', 'ihdr', 'pclr'])
box_ids = set([box.box_id for box in boxes])
intersection = box_ids.intersection(JP2H_CHILDREN)
if len(intersection) > 0 and parent_box_name not in ['jp2h', 'jpch']:
msg = "A {0} box can only be nested in a JP2 header box."
raise IOError(msg.format(list(intersection)[0]))
# Recursively check any contained superboxes.
for box in boxes:
if hasattr(box, 'box'):
self._check_jp2h_child_boxes(box.box, box.box_id)
|
def _check_jp2h_child_boxes(self, boxes, parent_box_name)
|
Certain boxes can only reside in the JP2 header.
| 3.874486
| 3.511369
| 1.103412
|
count = Counter([box.box_id for box in boxes])
# Add the counts in the superboxes.
for box in boxes:
if hasattr(box, 'box'):
count.update(self._collect_box_count(box.box))
return count
|
def _collect_box_count(self, boxes)
|
Count the occurences of each box type.
| 4.350389
| 4.007709
| 1.085505
|
# We are only looking at the boxes contained in a superbox, so if any
# of the blacklisted boxes show up here, it's an error.
TOP_LEVEL_ONLY_BOXES = set(['dtbl'])
box_ids = set([box.box_id for box in boxes])
intersection = box_ids.intersection(TOP_LEVEL_ONLY_BOXES)
if len(intersection) > 0:
msg = "A {0} box cannot be nested in a superbox."
raise IOError(msg.format(list(intersection)[0]))
# Recursively check any contained superboxes.
for box in boxes:
if hasattr(box, 'box'):
self._check_superbox_for_top_levels(box.box)
|
def _check_superbox_for_top_levels(self, boxes)
|
Several boxes can only occur at the top level.
| 4.14121
| 3.922942
| 1.055639
|
# Add the counts in the superboxes.
for box in boxes:
if hasattr(box, 'box'):
self._check_superbox_for_top_levels(box.box)
count = self._collect_box_count(boxes)
# If there is one data reference box, then there must also be one ftbl.
if 'dtbl' in count and 'ftbl' not in count:
msg = ('The presence of a data reference box requires the '
'presence of a fragment table box as well.')
raise IOError(msg)
|
def _validate_top_level(self, boxes)
|
Several boxes can only occur at the top level.
| 7.069323
| 6.517454
| 1.084676
|
count = self._collect_box_count(boxes)
# Which boxes occur more than once?
multiples = [box_id for box_id, bcount in count.items() if bcount > 1]
if 'dtbl' in multiples:
raise IOError('There can only be one dtbl box in a file.')
|
def _validate_singletons(self, boxes)
|
Several boxes can only occur once.
| 7.258257
| 6.050281
| 1.199656
|
JPX_IDS = ['asoc', 'nlst']
jpx_cl = set(compatibility_list)
for box in boxes:
if box.box_id in JPX_IDS:
if len(set(['jpx ', 'jpxb']).intersection(jpx_cl)) == 0:
msg = ("A JPX box requires that either 'jpx ' or 'jpxb' "
"be present in the ftype compatibility list.")
raise RuntimeError(msg)
if hasattr(box, 'box') != 0:
# Same set of checks on any child boxes.
self._validate_jpx_compatibility(box.box, compatibility_list)
|
def _validate_jpx_compatibility(self, boxes, compatibility_list)
|
If there is a JPX box then the compatibility list must also contain
'jpx '.
| 5.629922
| 4.680677
| 1.202801
|
for box in boxes:
if box.box_id != 'asoc':
if hasattr(box, 'box'):
for boxi in box.box:
if boxi.box_id == 'lbl ':
msg = ("A label box cannot be nested inside a "
"{0} box.")
msg = msg.format(box.box_id)
raise IOError(msg)
# Same set of checks on any child boxes.
self._validate_label(box.box)
|
def _validate_label(self, boxes)
|
Label boxes can only be inside association, codestream headers, or
compositing layer header boxes.
| 5.854906
| 4.505378
| 1.299537
|
return getattr(self.session, method)(*args, **kwargs)
|
def fulfill(self, method, *args, **kwargs)
|
Fulfill an HTTP request to Keen's API.
| 5.618339
| 7.070571
| 0.794609
|
url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url, self.api_version,
self.project_id,
event.event_collection)
headers = utilities.headers(self.write_key)
payload = event.to_json()
response = self.fulfill(HTTPMethods.POST, url, data=payload, headers=headers, timeout=self.post_timeout)
self._error_handling(response)
|
def post_event(self, event)
|
Posts a single event to the Keen IO API. The write key must be set first.
:param event: an Event to upload
| 4.80848
| 4.037106
| 1.191071
|
url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version,
self.project_id)
headers = utilities.headers(self.write_key)
payload = json.dumps(events)
response = self.fulfill(HTTPMethods.POST, url, data=payload, headers=headers, timeout=self.post_timeout)
self._error_handling(response)
return self._get_response_json(response)
|
def post_events(self, events)
|
Posts a single event to the Keen IO API. The write key must be set first.
:param events: an Event to upload
| 4.293031
| 3.831754
| 1.120383
|
if not "order_by" in params or not params["order_by"]:
return True
def _order_by_dict_is_not_well_formed(d):
if not isinstance(d, dict):
# Bad type.
return True
if "property_name" in d and d["property_name"]:
if "direction" in d and not direction.is_valid_direction(d["direction"]):
# Bad direction provided.
return True
for k in d:
if k != "property_name" and k != "direction":
# Unexpected key.
return True
# Everything looks good!
return False
# Missing required key.
return True
# order_by is converted to a list before this point if it wasn't one before.
order_by_list = json.loads(params["order_by"])
for order_by in order_by_list:
if _order_by_dict_is_not_well_formed(order_by):
return False
if not "group_by" in params or not params["group_by"]:
# We must have group_by to have order_by make sense.
return False
return True
|
def _order_by_is_valid_or_none(self, params)
|
Validates that a given order_by has proper syntax.
:param params: Query params.
:return: Returns True if either no order_by is present, or if the order_by is well-formed.
| 3.039159
| 3.001899
| 1.012412
|
if not "limit" in params or not params["limit"]:
return True
if not isinstance(params["limit"], int) or params["limit"] < 1:
return False
if not "order_by" in params:
return False
return True
|
def _limit_is_valid_or_none(self, params)
|
Validates that a given limit is not present or is well-formed.
:param params: Query params.
:return: Returns True if a limit is present or is well-formed.
| 2.747102
| 3.00975
| 0.912734
|
if not self._order_by_is_valid_or_none(params):
raise ValueError("order_by given is invalid or is missing required group_by.")
if not self._limit_is_valid_or_none(params):
raise ValueError("limit given is invalid or is missing required order_by.")
url = "{0}/{1}/projects/{2}/queries/{3}".format(self.base_url, self.api_version,
self.project_id, analysis_type)
headers = utilities.headers(self.read_key)
payload = params
response = self.fulfill(HTTPMethods.GET, url, params=payload, headers=headers, timeout=self.get_timeout)
self._error_handling(response)
response = response.json()
if not all_keys:
response = response["result"]
return response
|
def query(self, analysis_type, params, all_keys=False)
|
Performs a query using the Keen IO analysis API. A read key must be set first.
| 4.059164
| 3.797947
| 1.068779
|
url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url,
self.api_version,
self.project_id,
event_collection)
headers = utilities.headers(self.master_key)
response = self.fulfill(HTTPMethods.DELETE, url, params=params, headers=headers, timeout=self.post_timeout)
self._error_handling(response)
return True
|
def delete_events(self, event_collection, params)
|
Deletes events via the Keen IO API. A master key must be set first.
:param event_collection: string, the event collection from which event are being deleted
| 4.568332
| 4.246463
| 1.075797
|
url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url, self.api_version,
self.project_id, event_collection)
headers = utilities.headers(self.read_key)
response = self.fulfill(HTTPMethods.GET, url, headers=headers, timeout=self.get_timeout)
self._error_handling(response)
return response.json()
|
def get_collection(self, event_collection)
|
Extracts info about a collection using the Keen IO API. A master key must be set first.
:param event_collection: the name of the collection to retrieve info for
| 4.621239
| 4.914088
| 0.940406
|
# Get current state via HTTPS.
current_access_key = self.get_access_key(access_key_id)
# Copy and only change the single parameter.
payload_dict = KeenApi._build_access_key_dict(current_access_key)
payload_dict[key] = val
# Now just treat it like a full update.
return self.update_access_key_full(access_key_id, **payload_dict)
|
def _update_access_key_pair(self, access_key_id, key, val)
|
Helper for updating access keys in a DRY fashion.
| 6.519588
| 5.841893
| 1.116006
|
# Get current state via HTTPS.
current_access_key = self.get_access_key(access_key_id)
# Copy and only change the single parameter.
payload_dict = KeenApi._build_access_key_dict(current_access_key)
# Turn into sets to avoid duplicates.
old_permissions = set(payload_dict["permitted"])
new_permissions = set(permissions)
combined_permissions = old_permissions.union(new_permissions)
payload_dict["permitted"] = list(combined_permissions)
# Now just treat it like a full update.
return self.update_access_key_full(access_key_id, **payload_dict)
|
def add_access_key_permissions(self, access_key_id, permissions)
|
Adds to the existing list of permissions on this key with the contents of this list.
Will not remove any existing permissions or modify the remainder of the key.
:param access_key_id: the 'key' value of the access key to add permissions to
:param permissions: the new permissions to add to the existing list of permissions
| 4.95466
| 5.104641
| 0.970619
|
# Get current state via HTTPS.
current_access_key = self.get_access_key(access_key_id)
# Copy and only change the single parameter.
payload_dict = KeenApi._build_access_key_dict(current_access_key)
# Turn into sets to avoid duplicates.
old_permissions = set(payload_dict["permitted"])
removal_permissions = set(permissions)
reduced_permissions = old_permissions.difference(removal_permissions)
payload_dict["permitted"] = list(reduced_permissions)
# Now just treat it like a full update.
return self.update_access_key_full(access_key_id, **payload_dict)
|
def remove_access_key_permissions(self, access_key_id, permissions)
|
Removes a list of permissions from the existing list of permissions.
Will not remove all existing permissions unless all such permissions are included
in this list. Not to be confused with key revocation.
See also: revoke_access_key()
:param access_key_id: the 'key' value of the access key to remove some permissions from
:param permissions: the permissions you wish to remove from this access key
| 5.435302
| 5.515591
| 0.985443
|
url = "{0}/{1}/projects/{2}/keys/{3}".format(self.base_url, self.api_version,
self.project_id, access_key_id)
headers = utilities.headers(self.master_key)
payload_dict = {
"name": name,
"is_active": is_active,
"permitted": permitted,
"options": options
}
payload = json.dumps(payload_dict)
response = self.fulfill(HTTPMethods.POST, url, data=payload, headers=headers, timeout=self.get_timeout)
self._error_handling(response)
return response.json()
|
def update_access_key_full(self, access_key_id, name, is_active, permitted, options)
|
Replaces the 'name', 'is_active', 'permitted', and 'options' values of a given key.
A master key must be set first.
:param access_key_id: the 'key' value of the access key for which the values will be replaced
:param name: the new name desired for this access key
:param is_active: whether the key should become enabled (True) or revoked (False)
:param permitted: the new list of permissions desired for this access key
:param options: the new dictionary of options for this access key
| 2.916498
| 3.086667
| 0.94487
|
# making the error handling generic so if an status_code starting with 2 doesn't exist, we raise the error
if res.status_code // 100 != 2:
error = self._get_response_json(res)
raise exceptions.KeenApiError(error)
|
def _error_handling(self, res)
|
Helper function to do the error handling
:params res: the response from a request
| 10.002773
| 9.804706
| 1.020201
|
try:
error = res.json()
except ValueError:
error = {
"message": "The API did not respond with JSON, but: {0}".format(res.text[:1000]),
"error_code": "{0}".format(res.status_code)
}
return error
|
def _get_response_json(self, res)
|
Helper function to extract the JSON body out of a response OR throw an exception.
:param res: the response from a request
:return: the JSON body OR throws an exception
| 4.127701
| 4.167201
| 0.990521
|
return self._get_json(HTTPMethods.GET,
self._cached_datasets_url,
self._get_master_key())
|
def all(self)
|
Fetch all Cached Datasets for a Project. Read key must be set.
| 17.030678
| 8.079444
| 2.107902
|
url = "{0}/{1}".format(self._cached_datasets_url, dataset_name)
return self._get_json(HTTPMethods.GET, url, self._get_read_key())
|
def get(self, dataset_name)
|
Fetch a single Cached Dataset for a Project. Read key must be set.
:param dataset_name: Name of Cached Dataset (not `display_name`)
| 6.811543
| 7.073317
| 0.962991
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.