code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if index_names: df = df.set_index(index_names) # Remove names from unnamed indexes index_names = _denormalize_index_names(index_names) df.index.names = index_names return df
def _update_index_on_df(df, index_names)
Helper function to restore index information after collection. Doesn't use self so we can serialize this.
3.720037
3.622205
1.027009
columns = self._schema_rdd.columns index_names = self._index_names def fromRecords(records): if not records: return [] else: loaded_df = pd.DataFrame.from_records([records], co...
def _rdd(self)
Return an RDD of Panda DataFrame objects. This can be expensive especially if we don't do a narrow transformation after and get it back to Spark SQL land quickly.
4.910696
4.401955
1.115571
index_names = set(_normalize_index_names(self._index_names)) column_names = [col_name for col_name in self._schema_rdd.columns if col_name not in index_names] return column_names
def _column_names(self)
Return the column names
4.663956
4.242093
1.099447
source_rdd = self._rdd() result_rdd = func(source_rdd) # By default we don't know what the columns & indexes are so we let # from_rdd_of_dataframes look at the first partition to determine them. column_idxs = None if preserves_cols: index_names = self...
def _evil_apply_with_dataframes(self, func, preserves_cols=False)
Convert the underlying SchmeaRDD to an RDD of DataFrames. apply the provide function and convert the result back. This is hella slow.
5.634604
5.099059
1.105028
columns = self._schema_rdd.columns df = pd.DataFrame.from_records( [self._schema_rdd.first()], columns=self._schema_rdd.columns) df = _update_index_on_df(df, self._index_names) return df
def _first_as_df(self)
Gets the first row as a Panda's DataFrame. Useful for functions like dtypes & ftypes
4.999991
4.421137
1.130929
def frame_to_spark_sql(frame): return [r.tolist() for r in frame.to_records()] def frame_to_schema_and_idx_names(frames): try: frame = frames.next() return [(list(frame.columns), list(frame.index.names))] ...
def from_rdd_of_dataframes(self, rdd, column_idxs=None)
Take an RDD of Panda's DataFrames and return a Dataframe. If the columns and indexes are already known (e.g. applyMap) then supplying them with columnsIndexes will skip eveluating the first partition to determine index info.
4.935381
4.656383
1.059918
result = DataFrame(None, sql_ctx) return result.from_rdd_of_dataframes(rdd)
def fromDataFrameRDD(cls, rdd, sql_ctx)
Construct a DataFrame from an RDD of DataFrames. No checking or validation occurs.
8.416659
5.72635
1.469812
def transform_rdd(rdd): return rdd.map(lambda data: data.applymap(f), **kwargs) return self._evil_apply_with_dataframes(transform_rdd, preserves_cols=True)
def applymap(self, f, **kwargs)
Return a new DataFrame by applying a function to each element of each Panda DataFrame.
9.620307
10.306971
0.933379
from sparklingpandas.groupby import GroupBy return GroupBy(self, by=by, axis=axis, level=level, as_index=as_index, sort=sort, group_keys=group_keys, squeeze=squeeze)
def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False)
Returns a groupby on the schema rdd. This returns a GroupBy object. Note that grouping by a column name will be faster than most other options due to implementation.
2.033337
1.97613
1.028949
local_df = self._schema_rdd.toPandas() correct_idx_df = _update_index_on_df(local_df, self._index_names) return correct_idx_df
def collect(self)
Collect the elements in an DataFrame and concatenate the partition.
10.640224
8.971355
1.186022
assert (not isinstance(columns, basestring)), "columns should be a " \ "list of strs, " \ "not a str!" assert isinstance(columns, list), "columns should be a list!" from pyspark...
def stats(self, columns)
Compute the stats for each column provided in columns. Parameters ---------- columns : list of str, contains all columns to compute stats on.
4.767192
4.860748
0.980753
return self.from_rdd( self._rdd.map(lambda data: data.applymap(func), **kwargs))
def applymap(self, func, **kwargs)
Return a new PRDD by applying a function to each element of each pandas DataFrame.
7.356698
6.455985
1.139516
from sparklingpandas.groupby import GroupBy return GroupBy(self._rdd, *args, **kwargs)
def groupby(self, *args, **kwargs)
Takes the same parameters as groupby on DataFrame. Like with groupby on DataFrame disabling sorting will result in an even larger performance improvement. This returns a Sparkling Pandas L{GroupBy} object which supports many of the same operations as regular GroupBy but not all.
5.831481
3.931386
1.483314
# The order of the frame order appends is based on the implementation # of reduce which calls our function with # f(valueToBeAdded, accumulator) so we do our reduce implementation. def append_frames(frame_a, frame_b): return frame_a.append(frame_b) return sel...
def collect(self)
Collect the elements in an PRDD and concatenate the partition.
17.561262
14.992385
1.171345
def accumulating_iter(iterator): acc = None for obj in iterator: if acc is None: acc = obj else: acc = reduce_func(acc, obj) if acc is not None: yield acc vals = self._rdd...
def _custom_rdd_reduce(self, reduce_func)
Provides a custom RDD reduce which preserves ordering if the RDD has been sorted. This is useful for us because we need this functionality as many pandas operations support sorting the results. The standard reduce in PySpark does not have this property. Note that when PySpark no longer ...
2.948543
2.842265
1.037392
def reduce_func(sc1, sc2): return sc1.merge_pstats(sc2) return self._rdd.mapPartitions(lambda partition: [ PStatCounter(dataframes=partition, columns=columns)])\ .reduce(reduce_func)
def stats(self, columns)
Compute the stats for each column provided in columns. Parameters ---------- columns : list of str, contains all columns to compute stats on.
9.696252
10.604432
0.914358
def csv_file(partition_number, files): # pylint: disable=unexpected-keyword-arg file_count = 0 for _, contents in files: # Only skip lines on the first file if partition_number == 0 and file_count == 0 and _skiprows > 0: ...
def read_csv(self, file_path, use_whole_file=False, names=None, skiprows=0, *args, **kwargs)
Read a CSV file in and parse it into Pandas DataFrames. By default, the first row from the first partition of that data is parsed and used as the column names for the data from. If no 'names' param is provided we parse the first row of the first partition of data and use it for column na...
3.289908
3.2115
1.024415
schema_rdd = self.sql_ctx.jsonFile(path, schema, sampling_ratio) return self.from_spark_rdd(schema_rdd)
def jsonFile(self, path, schema=None, sampling_ratio=1.0)
Loads a text file storing one JSON object per line as a L{DataFrame}. Parameters ---------- path: string The path of the json files to load. Should be Hadoop style paths (e.g. hdfs://..., file://... etc.). schema: StructType, optional If you...
5.252553
6.841201
0.767782
def frame_to_rows(frame): # TODO: Convert to row objects directly? return [r.tolist() for r in frame.to_records()] schema = list(local_df.columns) index_names = list(local_df.index.names) index_names = _normalize_index_names(index_names) ...
def from_pd_data_frame(self, local_df)
Make a Sparkling Pandas dataframe from a local Pandas DataFrame. The intend use is for testing or joining distributed data with local data. The types are re-infered, so they may not match. Parameters ---------- local_df: Pandas DataFrame The data to turn into ...
5.555088
5.592452
0.993319
return DataFrame.from_spark_rdd(self.sql_ctx.sql(query), self.sql_ctx)
def sql(self, query)
Perform a SQL query and create a L{DataFrame} of the result. The SQL query is run using Spark SQL. This is not intended for querying arbitrary databases, but rather querying Spark SQL tables. Parameters ---------- query: string The SQL query to pass to Spark SQL to ex...
7.285645
7.331191
0.993787
return DataFrame.from_spark_rdd(self.sql_ctx.table(table), self.sql_ctx)
def table(self, table)
Returns the provided Spark SQL table as a L{DataFrame} Parameters ---------- table: string The name of the Spark SQL table to turn into a L{DataFrame} Returns ------- Sparkling Pandas DataFrame.
8.718139
8.362267
1.042557
return self.from_pd_data_frame(pandas.DataFrame( elements, *args, **kwargs))
def DataFrame(self, elements, *args, **kwargs)
Create a Sparkling Pandas DataFrame for the provided elements, following the same API as constructing a Panda's DataFrame. Note: since elements is local this is only useful for distributing dataframes which are small enough to fit on a single machine anyways. Parameters ---------...
5.98359
8.262319
0.724202
def json_file_to_df(files): for _, contents in files: yield pandas.read_json(sio(contents), *args, **kwargs) return self.from_pandas_rdd(self.spark_ctx.wholeTextFiles(file_path) .mapPartitions(json_file_to_df))
def read_json(self, file_path, *args, **kwargs)
Read a json file in and parse it into Pandas DataFrames. If no names is provided we use the first row for the names. Currently, it is not possible to skip the first n rows of a file. Headers are provided in the json file and not specified separately. Parameters ---------- ...
5.874828
6.605205
0.889424
# Load generator module and create instance if we haven't already if (not self.srcfile): raise IIIFError(text=("No generator specified")) if (not self.gen): try: (name, ext) = os.path.splitext(self.srcfile) (pack, mod) = os.path.sp...
def do_first(self)
Load generator, set size. We take the generator module name from self.srcfile so that this manipulator will work with different generators in a similar way to how the ordinary generators work with different images
4.575465
4.123003
1.109741
if (x is None): self.rx = 0 self.ry = 0 self.rw = self.width self.rh = self.height else: self.rx = x self.ry = y self.rw = w self.rh = h
def do_region(self, x, y, w, h)
Record region.
2.034848
1.887265
1.078199
if (w is None): self.sw = self.rw self.sh = self.rh else: self.sw = w self.sh = h # Now we have region and size, generate the image image = Image.new("RGB", (self.sw, self.sh), self.gen.background_color) for y in range(0, s...
def do_size(self, w, h)
Record size.
2.528916
2.482242
1.018803
headers = {} headers['Access-control-allow-origin'] = '*' headers['Content-type'] = 'text/html' auth = request.authorization if (auth and auth.username == auth.password): return self.set_cookie_close_window_response( "valid-http-basic-login") ...
def login_handler(self, config=None, prefix=None, **args)
HTTP Basic login handler. Respond with 401 and WWW-Authenticate header if there are no credentials or bad credentials. If there are credentials then simply check for username equal to password for validity.
6.389725
5.724393
1.116227
desc = super(IIIFAuthClickthrough, self).login_service_description() desc['confirmLabel'] = self.confirm_label return desc
def login_service_description(self)
Clickthrough login service description. The login service description _MUST_ include the token service description. Additionally, for a clickthroudh loginThe authentication pattern is indicated via the profile URI which is built using self.auth_pattern.
13.914603
12.781752
1.08863
# API parameters self.identifier = None self.region = None self.size = None self.rotation = None self.quality = None self.format = None self.info = None # Derived data and flags self.region_full = False self.region_square =...
def clear(self)
Clear all data that might pertain to an individual IIIF URL. Does not change/reset the baseurl or API version which might be useful in a sequence of calls.
4.294648
3.868928
1.110036
self._api_version = v if (self._api_version >= '2.0'): self.default_quality = 'default' self.allowed_qualities = ['default', 'color', 'bitonal', 'gray'] else: # versions 1.0 and 1.1 self.default_quality = 'native' self.allowed_qualities =...
def api_version(self, v)
Set the api_version and associated configurations.
3.440366
3.353125
1.026018
self._setattrs(**params) path = self.baseurl + self.quote(self.identifier) + "/" if (self.info): # info request path += "info" format = self.format if self.format else "json" else: # region if self.region: ...
def url(self, **params)
Build a URL path for image or info request. An IIIF Image request with parameterized form is assumed unless the info parameter is specified, in which case an Image Information request URI is constructred.
2.626194
2.306211
1.138749
self.split_url(url) if (not self.info): self.parse_parameters() return(self)
def parse_url(self, url)
Parse an IIIF API URL path and each component. Will parse a URL or URL path that accords with either the parametrized or info request forms. Will raise an IIIFRequestError on failure. A wrapper for the split_url() and parse_parameters() methods. Note that behavior of split_url(...
8.657424
8.36296
1.035211
# clear data first identifier = self.identifier self.clear() # url must start with baseurl if set (including slash) if (self.baseurl is not None): (path, num) = re.subn('^' + self.baseurl, '', url, 1) if (num != 1): raise IIIFReque...
def split_url(self, url)
Parse an IIIF API URL path into components. Will parse a URL or URL path that accords with either the parametrized or info API forms. Will raise an IIIFRequestError on failure. If self.identifier is set then url is assumed not to include the identifier.
3.30303
3.192314
1.034682
m = re.match("(.+)\.([a-zA-Z]\w*)$", str_and_format) if (m): # There is a format string at end, chop off and store str_and_format = m.group(1) self.format = (m.group(2) if (m.group(2) is not None) else '') return(str_and_format)
def strip_format(self, str_and_format)
Look for optional .fmt at end of URI. The format must start with letter. Note that we want to catch the case of a dot and no format (format='') which is different from no dot (format=None) Sets self.format as side effect, returns possibly modified string
3.720695
2.905644
1.280506
self.parse_region() self.parse_size() self.parse_rotation() self.parse_quality() self.parse_format()
def parse_parameters(self)
Parse the parameters of an Image Information request. Will throw an IIIFRequestError on failure, set attributes on success. Care is taken not to change any of the artibutes which store path components. All parsed values are stored in new attributes.
3.986018
3.117526
1.278584
self.region_full = False self.region_square = False self.region_pct = False if (self.region is None or self.region == 'full'): self.region_full = True return if (self.api_version >= '2.1' and self.region == 'square'): self.region_squar...
def parse_region(self)
Parse the region component of the path. /full/ -> self.region_full = True (test this first) /square/ -> self.region_square = True (test this second) /x,y,w,h/ -> self.region_xywh = (x,y,w,h) /pct:x,y,w,h/ -> self.region_xywh and self.region_pct = True Will throw errors if the p...
3.297532
2.955945
1.115559
if (size is not None): self.size = size self.size_pct = None self.size_bang = False self.size_full = False self.size_wh = (None, None) if (self.size is None or self.size == 'full'): self.size_full = True return elif (se...
def parse_size(self, size=None)
Parse the size component of the path. /full/ -> self.size_full = True /max/ -> self.size_mac = True (2.1 and up) /w,/ -> self.size_wh = (w,None) /,h/ -> self.size_wh = (None,h) /w,h/ -> self.size_wh = (w,h) /pct:p/ -> self.size_pct = p /!w,h/ -> self.size_wh = (...
3.326919
2.837242
1.172589
try: (wstr, hstr) = whstr.split(',', 2) w = self._parse_non_negative_int(wstr, 'w') h = self._parse_non_negative_int(hstr, 'h') except ValueError as e: raise IIIFRequestError( code=400, parameter=param, text="Illega...
def _parse_w_comma_h(self, whstr, param)
Utility to parse "w,h" "w," or ",h" values. Returns (w,h) where w,h are either None or ineteger. Will throw a ValueError if there is a problem with one or both.
2.637373
2.561009
1.029818
if (istr == ''): return(None) try: i = int(istr) except ValueError: raise ValueError("Failed to extract integer value for %s" % (name)) if (i < 0): raise ValueError("Illegal negative value for %s" % (name)) return(i)
def _parse_non_negative_int(self, istr, name)
Parse integer from string (istr). The (name) parameter is used just for IIIFRequestError message generation to indicate what the error is in.
2.72689
2.78893
0.977755
if (rotation is not None): self.rotation = rotation self.rotation_deg = 0.0 self.rotation_mirror = False if (self.rotation is None): return # Look for ! prefix first if (self.rotation[0] == '!'): self.rotation_mirror = True ...
def parse_rotation(self, rotation=None)
Check and interpret rotation. Uses value of self.rotation as starting point unless rotation parameter is specified in the call. Sets self.rotation_deg to a floating point number 0 <= angle < 360. Includes translation of 360 to 0. If there is a prefix bang (!) then self.rotation_mirror ...
3.037367
2.569567
1.182054
if (self.quality is None): self.quality_val = self.default_quality elif (self.quality not in self.allowed_qualities): raise IIIFRequestError( code=400, parameter="quality", text="The quality parameter must be '%s', got '%s'." % ...
def parse_quality(self)
Check quality paramater. Sets self.quality_val based on simple substitution of 'native' for default. Checks for the three valid values else throws an IIIFRequestError.
3.644445
2.479827
1.469637
if (self.format is not None and not re.match(r'''\w{1,20}$''', self.format)): raise IIIFRequestError( parameter='format', text='Bad format parameter')
def parse_format(self)
Check format parameter. All formats values listed in the specification are lowercase alphanumeric value commonly used as file extensions. To leave opportunity for extension here just do a limited sanity check on characters and length.
8.649801
7.053654
1.226287
return(self.region_full and self.size_wh[0] is not None and self.size_wh[1] is not None and not self.size_bang and self.rotation_deg == 0.0 and self.quality == self.default_quality and self.format == 'jpg')
def is_scaled_full_image(self)
True if this request is for a scaled full image. To be used to determine whether this request should be used in the set of `sizes` specificed in the Image Information.
5.742511
5.211882
1.101812
p = configargparse.ArgParser(description='IIIF Image API Reference Service', default_config_files=[os.path.join(base_dir, 'iiif_reference_server.cfg')], formatter_class=configargparse.ArgumentDefaultsHelpFormatter) add_shared_configs(p, base...
def get_config(base_dir='')
Get config from defaults, config file and/or parse arguments. Uses configargparse to allow argments to be set from a config file or via command line arguments. base_dir - set a specific base directory for file/path defaults.
3.308564
3.369086
0.982036
# Create Flask app app = Flask(__name__) Flask.secret_key = "SECRET_HERE" app.debug = cfg.debug # Install request handlers client_prefixes = dict() for api_version in cfg.api_versions: handler_config = Config(cfg) handler_config.api_version = api_version handler_...
def create_reference_server_flask_app(cfg)
Create referece server Flask application with one or more IIIF handlers.
6.887955
6.312732
1.091121
if (size is None): size = self.sz # Have we go to the smallest element? if (size <= 3): if (_middle(x, y)): return (None) else: return (0, 0, 0) divisor = size // 3 if (_middle(x // divisor, y // divisor...
def pixel(self, x, y, size=None)
Return color for a pixel.
6.219067
6.046792
1.02849
id = '' if (self.server_and_prefix is not None and self.server_and_prefix != ''): id += self.server_and_prefix + '/' if (self.identifier is not None): id += self.identifier return id
def id(self)
id property based on server_and_prefix and identifier.
3.734461
2.037337
1.833011
i = value.rfind('/') if (i > 0): self.server_and_prefix = value[:i] self.identifier = value[(i + 1):] elif (i == 0): self.server_and_prefix = '' self.identifier = value[(i + 1):] else: self.server_and_prefix = '' ...
def id(self, value)
Split into server_and_prefix and identifier.
2.58285
1.736085
1.487744
if (api_version is None): api_version = self.api_version if (api_version not in CONF): raise IIIFInfoError("Unknown API version %s" % (api_version)) self.params = CONF[api_version]['params'] self.array_params = CONF[api_version]['array_params'] se...
def set_version_info(self, api_version=None)
Set up normal values for given api_version. Will use current value of self.api_version if a version number is not specified in the call. Will raise an IIIFInfoError
3.794533
3.327275
1.140433
if (self.api_version < '2.0'): self.profile = value else: try: self.profile[0] = value except AttributeError: # handle case where profile not initialized as array self.profile = [value]
def compliance(self, value)
Set the compliance profile URI.
5.931497
5.235283
1.132985
m = re.match( self.compliance_prefix + r'(\d)' + self.compliance_suffix + r'$', self.compliance) if (m): return int(m.group(1)) raise IIIFInfoError( "Bad compliance profile URI, failed to extract level n...
def level(self)
Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError
7.166693
3.861184
1.856087
self.compliance = self.compliance_prefix + \ ("%d" % value) + self.compliance_suffix
def level(self, value)
Build profile URI from level. Level should be an integer 0,1,2
10.372285
11.07996
0.93613
if (self.service is None): self.service = service elif (isinstance(self.service, dict)): self.service = [self.service, service] else: self.service.append(service)
def add_service(self, service)
Add a service description. Handles transition from self.service=None, self.service=dict for a single service, and then self.service=[dict,dict,...] for multiple
2.601396
2.323399
1.119651
errors = [] for param in self.required_params: if (not hasattr(self, param) or getattr(self, param) is None): errors.append("missing %s parameter" % (param)) if (len(errors) > 0): raise IIIFInfoError("Bad data for info.json: " + ", ".join(errors))...
def validate(self)
Validate this object as Image API data. Raise IIIFInfoError with helpful message if not valid.
4.000926
2.88183
1.388328
if (validate): self.validate() json_dict = {} if (self.api_version > '1.0'): json_dict['@context'] = self.context params_to_write = set(self.params) params_to_write.discard('identifier') if (self.identifier): if (self.api_versi...
def as_json(self, validate=True)
Return JSON serialization. Will raise IIIFInfoError if insufficient parameters are present to have a valid info.json response (unless validate is False).
2.467594
2.300153
1.072796
j = json.load(fh) # # @context and API version self.context = None if (api_version == '1.0'): # v1.0 did not have a @context so we simply take the version # passed in self.api_version = api_version elif ('@context' in j): ...
def read(self, fh, api_version=None)
Read info.json from file like object. Parameters: fh -- file like object supporting fh.read() api_version -- IIIF Image API version expected If api_version is set then the parsing will assume this API version, else the version will be determined from the incoming data. NOTE tha...
3.323804
3.063668
1.08491
if (pixels): Image.MAX_IMAGE_PIXELS = pixels Image.warnings.simplefilter( 'error', Image.DecompressionBombWarning)
def set_max_image_pixels(self, pixels)
Set PIL limit on pixel size of images to load if non-zero. WARNING: This is a global setting in PIL, it is not local to this manipulator instance! Setting a value here will not only set the given limit but also convert the PIL "DecompressionBombWarning" into an error. Thus sett...
5.533839
4.245174
1.30356
self.logger.debug("do_first: src=%s" % (self.srcfile)) try: self.image = Image.open(self.srcfile) except Image.DecompressionBombWarning as e: # This exception will be raised only if PIL has been # configured to raise an error in the case of images ...
def do_first(self)
Create PIL object from input image file. Image location must be in self.srcfile. Will result in self.width and self.height being set to the image dimensions. Will raise an IIIFError on failure to load the image
4.066747
3.365524
1.208355
if (x is None): self.logger.debug("region: full (nop)") else: self.logger.debug("region: (%d,%d,%d,%d)" % (x, y, w, h)) self.image = self.image.crop((x, y, x + w, y + h)) self.width = w self.height = h
def do_region(self, x, y, w, h)
Apply region selection.
2.968461
2.974004
0.998136
if (w is None): self.logger.debug("size: no scaling (nop)") else: self.logger.debug("size: scaling to (%d,%d)" % (w, h)) self.image = self.image.resize((w, h)) self.width = w self.height = h
def do_size(self, w, h)
Apply size scaling.
3.516372
3.137564
1.120733
if (not mirror and rot == 0.0): self.logger.debug("rotation: no rotation (nop)") else: # FIXME - with PIL one can use the transpose() method to do 90deg # FIXME - rotations as well as mirroring. This would be more efficient # FIXME - for these cas...
def do_rotation(self, mirror, rot)
Apply rotation and/or mirroring.
5.007245
4.808348
1.041365
if (quality == 'grey' or quality == 'gray'): # Checking for 1.1 gray or 20.0 grey elsewhere self.logger.debug("quality: converting to gray") self.image = self.image.convert('L') elif (quality == 'bitonal'): self.logger.debug("quality: converting t...
def do_quality(self, quality)
Apply value of quality parameter. For PIL docs see <http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.convert>
4.838577
4.639401
1.042931
fmt = ('jpg' if (format is None) else format) if (fmt == 'png'): self.logger.debug("format: png") self.mime_type = "image/png" self.output_format = fmt format = 'png' elif (fmt == 'jpg'): self.logger.debug("format: jpg") ...
def do_format(self, format)
Apply format selection. Assume that for tiling applications we want jpg so return that unless an explicit format is requested.
2.617742
2.523846
1.037203
if self.image: try: self.image.close() except Exception: pass if (self.outtmp is not None): try: os.unlink(self.outtmp) except OSError as e: self.logger.warning("Failed to cleanup tmp...
def cleanup(self)
Cleanup: ensure image closed and remove temporary output file.
3.543516
2.958002
1.197942
if (size is None): size = self.sz # Have we go to the smallest element? if (size <= 3): if (_num(x, y) % 2): return (red, 0, 0) else: return None divisor = size // 3 n = _num(x // divisor, y // divisor) ...
def pixel(self, x, y, size=None, red=0)
Return color for a pixel. The paremeter size is used to recursively follow down to smaller and smaller middle squares (number 5). The paremeter red is used to shade from black to red going toward the middle of the figure.
4.861413
4.302616
1.129874
html = "<html>\n<head><title>%s</title></head>\n<body>\n" % (title) html += "<h1>%s</h1>\n" % (title) html += body html += "</body>\n</html>\n" return html
def html_page(title="Page Title", body="")
Create HTML page as string.
1.860575
1.769295
1.051591
title = "IIIF Test Server on %s" % (config.host) body = "<ul>\n" for prefix in sorted(config.prefixes.keys()): body += '<li><a href="/%s">%s</a></li>\n' % (prefix, prefix) body += "</ul>\n" return html_page(title, body)
def top_level_index_page(config)
HTML top-level index page which provides a link to each handler.
3.40313
3.314818
1.026641
ids = [] if (config.klass_name == 'gen'): for generator in os.listdir(config.generator_dir): if (generator == '__init__.py'): continue (gid, ext) = os.path.splitext(generator) if (ext == '.py' and os.path.isfile(os.path.join(co...
def identifiers(config)
Show list of identifiers for this prefix. Handles both the case of local file based identifiers and also image generators. Arguments: config - configuration object in which: config.klass_name - 'gen' if a generator function config.generator_dir - directory for generator cod...
2.399394
1.861269
1.289117
title = "IIIF Image API services under %s" % (config.client_prefix) # details of this prefix handler body = '<p>\n' body += 'host = %s<br/>\n' % (config.host) body += 'api_version = %s<br/>\n' % (config.api_version) body += 'manipulator = %s<br/>\n' % (config.klass_name) body += 'auth_t...
def prefix_index_page(config)
HTML index page for a specific prefix. The prefix seen by the client is obtained from config.client_prefix as opposed to the local server prefix in config.prefix. Also uses the identifiers(config) function to get identifiers available. Arguments: config - configuration object in which: ...
2.973941
2.724424
1.091585
uri = "http://" + host if (port != 80): uri += ':' + str(port) if (prefix): uri += '/' + prefix return uri
def host_port_prefix(host, port, prefix)
Return URI composed of scheme, server, port, and prefix.
3.254084
2.485016
1.309482
template_dir = os.path.join(os.path.dirname(__file__), 'templates') with open(os.path.join(template_dir, 'testserver_osd.html'), 'r') as f: template = f.read() d = dict(prefix=prefix, identifier=identifier, api_version=config.api_version, osd_version='2.0....
def osd_page_handler(config=None, identifier=None, prefix=None, **args)
Flask handler to produce HTML response for OpenSeadragon view of identifier. Arguments: config - Config object for this IIIF handler identifier - identifier of image/generator prefix - path prefix **args - other aguments ignored
3.376614
3.171299
1.064742
if (not auth or degraded_request(identifier) or auth.info_authz()): # go ahead with request as made if (auth): logging.debug("Authorized for image %s" % identifier) i = IIIFHandler(prefix, identifier, config, klass, auth) try: return i.image_information_r...
def iiif_info_handler(prefix=None, identifier=None, config=None, klass=None, auth=None, **args)
Handler for IIIF Image Information requests.
6.669762
6.519824
1.022997
if (not auth or degraded_request(identifier) or auth.image_authz()): # serve image if (auth): logging.debug("Authorized for image %s" % identifier) i = IIIFHandler(prefix, identifier, config, klass, auth) try: return i.image_request_response(path) ...
def iiif_image_handler(prefix=None, identifier=None, path=None, config=None, klass=None, auth=None, **args)
Handler for IIIF Image Requests. Behaviour for case of a non-authn or non-authz case is to return 403.
6.07547
5.618177
1.081395
result = [] for media_range in accept.split(","): parts = media_range.split(";") media_type = parts.pop(0).strip() media_params = [] q = 1.0 for part in parts: (key, value) = part.lstrip().split("=", 1) if key == "q": q = float...
def parse_accept_header(accept)
Parse an HTTP Accept header. Parses *accept*, returning a list with pairs of (media_type, q_value), ordered by q values. Adapted from <https://djangosnippets.org/snippets/1042/>
2.008865
2.03261
0.988318
try: (auth_type, auth_info) = value.split(' ', 1) auth_type = auth_type.lower() except ValueError: return if (auth_type == 'basic'): try: decoded = base64.b64decode(auth_info).decode( 'utf-8') # b64decode gives bytes in python3 (u...
def parse_authorization_header(value)
Parse the Authenticate header. Returns nothing on failure, opts hash on success with type='basic' or 'digest' and other params. <http://nullege.com/codes/search/werkzeug.http.parse_authorization_header> <http://stackoverflow.com/questions/1349367/parse-an-http-request-authorization-header-with-python>...
2.300683
2.232641
1.030476
for result in parse_accept_header(accept): mime_type = result[0] if (mime_type in supported): return mime_type return None
def do_conneg(accept, supported)
Parse accept header and look for preferred type in supported list. Arguments: accept - HTTP Accept header supported - list of MIME type supported by the server Returns: supported MIME type with highest q value in request, else None. FIXME - Should replace this with negotiator2
3.914128
3.451855
1.13392
base = urljoin('/', prefix + '/') # Must end in slash app.add_url_rule(base + 'login', prefix + 'login_handler', auth.login_handler, defaults=params) app.add_url_rule(base + 'logout', prefix + 'logout_handler', auth.logout_handler, defaults=params) if (aut...
def setup_auth_paths(app, auth, prefix, params)
Add URL rules for auth paths.
2.024377
1.979847
1.022492
prefix = "%s_%s" % (api_version, manipulator) if (auth_type and auth_type != 'none'): prefix += '_' + auth_type return prefix
def make_prefix(api_version, manipulator, auth_type)
Make prefix string based on configuration parameters.
2.800062
2.679949
1.044819
terms = [] for term in comma_sep_str.split(','): if term: terms.append(term) return terms
def split_comma_argument(comma_sep_str)
Split a comma separated option into a list.
3.072287
2.992942
1.02651
p.add('--host', default='localhost', help="Service host") p.add('--port', '-p', type=int, default=8000, help="Service port") p.add('--app-host', default=None, help="Local application host for reverse proxy deployment, " "as opposed to service --host (must al...
def add_shared_configs(p, base_dir='')
Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults.
2.869283
2.882346
0.995468
if not basedir: basedir = os.path.join(os.path.dirname(__file__), 'third_party') return send_from_directory(os.path.join(basedir, prefix), filename)
def serve_static(filename=None, prefix='', basedir=None)
Handler for static files: server filename in basedir/prefix. If not specified then basedir defaults to the local third_party directory.
2.468393
2.211659
1.116082
pidfile = os.path.basename(sys.argv[0])[:-3] + '.pid' # strip .py, add .pid with open(pidfile, 'w') as fh: fh.write("%d\n" % os.getpid()) fh.close()
def write_pid_file()
Write a file with the PID of this server instance. Call when setting up a command line testserver.
2.736414
2.826676
0.968068
# Set up app_host and app_port in case that we are running # under reverse proxy setup, otherwise they default to # config.host and config.port. if (cfg.app_host and cfg.app_port): logging.warning("Reverse proxy for service at http://%s:%d/ ..." % (cfg.host, cfg.port)) app.wsgi_app ...
def setup_app(app, cfg)
Setup Flask app and handle reverse proxy setup if configured. Arguments: app - Flask application cfg - configuration data
3.422948
3.399592
1.00687
return(host_port_prefix(self.config.host, self.config.port, self.prefix))
def server_and_prefix(self)
Server and prefix from config.
8.266179
6.694118
1.234842
mime_type = "application/json" if (self.api_version >= '1.1' and 'Accept' in request.headers): mime_type = do_conneg(request.headers['Accept'], [ 'application/ld+json']) or mime_type return mime_type
def json_mime_type(self)
Return the MIME type for a JSON response. For version 2.0+ the server must return json-ld MIME type if that format is requested. Implement for 1.1 also. http://iiif.io/api/image/2.1/#information-request
5.070995
4.34782
1.166331
file = None if (self.config.klass_name == 'gen'): for ext in ['.py']: file = os.path.join( self.config.generator_dir, self.identifier + ext) if (os.path.isfile(file)): return file else: for e...
def file(self)
Filename property for the source image for the current identifier.
4.630033
4.26775
1.084889
if (self.manipulator.compliance_uri is not None): self.headers['Link'] = '<' + \ self.manipulator.compliance_uri + '>;rel="profile"'
def add_compliance_header(self)
Add IIIF Compliance level header to response.
6.78472
4.889988
1.387472
if headers: for header in headers: self.headers[header] = headers[header] return make_response(content, code, self.headers)
def make_response(self, content, code=200, headers=None)
Wrapper around Flask.make_response which also adds any local headers.
2.861079
2.512166
1.138889
dr = degraded_request(self.identifier) if (dr): self.logger.info("image_information: degraded %s -> %s" % (self.identifier, dr)) self.degraded = self.identifier self.identifier = dr else: self.logger.info("imag...
def image_information_response(self)
Parse image information request and create response.
4.169374
4.148865
1.004943
# Parse the request in path if (len(path) > 1024): raise IIIFError(code=414, text="URI Too Long: Max 1024 chars, got %d\n" % len(path)) try: self.iiif.identifier = self.identifier self.iiif.parse_url(path) except II...
def image_request_response(self, path)
Parse image request and create response.
4.631508
4.626367
1.001111
self.add_compliance_header() return self.make_response(*e.image_server_response(self.api_version))
def error_response(self, e)
Make response for an IIIFError e. Also add compliance header.
16.194099
8.310901
1.948537
self.send_response(code) self.send_header('Content-Type', 'text/xml') self.add_compliance_header() self.end_headers() self.wfile.write(content)
def error_response(self, code, content='')
Construct and send error response.
2.62417
2.395551
1.095435
self.compliance_uri = None self.iiif = IIIFRequest(baseurl='/') try: (of, mime_type) = self.do_GET_body() if (not of): raise IIIFError("Unexpected failure to open result image") self.send_response(200, 'OK') if (mime_type i...
def do_GET(self)
Implement the HTTP GET method. The bulk of this code is wrapped in a big try block and anywhere within the code may raise an IIIFError which then results in an IIIF error response (section 5 of spec).
3.8448
3.531605
1.088683
iiif = self.iiif if (len(self.path) > 1024): raise IIIFError(code=414, text="URI Too Long: Max 1024 chars, got %d\n" % len(self.path)) try: # self.path has leading / then identifier/params... self.path = self.path.lstrip('/...
def do_GET_body(self)
Create body of GET.
4.666954
4.639129
1.005998
if (cookie_prefix is None): self.cookie_prefix = "%06d_" % int(random.random() * 1000000) else: self.cookie_prefix = cookie_prefix
def set_cookie_prefix(self, cookie_prefix=None)
Set a random cookie prefix unless one is specified. In order to run multiple demonstration auth services on the same server we need to have different cookie names for each auth domain. Unless cookie_prefix is set, generate a random one.
2.843912
2.53841
1.120352
if (self.login_uri): svc = self.login_service_description() svcs = [] if (self.logout_uri): svcs.append(self.logout_service_description()) if (self.client_id_uri): svcs.append(self.client_id_service_description()) ...
def add_services(self, info)
Add auth service descriptions to an IIIFInfo object. Login service description is the wrapper for all other auth service descriptions so we have nothing unless self.login_uri is specified. If we do then add any other auth services at children. Exactly the same structure is used...
3.173129
2.750813
1.153524
label = 'Login to ' + self.name if (self.auth_type): label = label + ' (' + self.auth_type + ')' desc = {"@id": self.login_uri, "profile": self.profile_base + self.auth_pattern, "label": label} if (self.header): desc['heade...
def login_service_description(self)
Login service description. The login service description _MUST_ include the token service description. The authentication pattern is indicated via the profile URI which is built using self.auth_pattern.
4.11698
3.40516
1.209041
label = 'Logout from ' + self.name if (self.auth_type): label = label + ' (' + self.auth_type + ')' return({"@id": self.logout_uri, "profile": self.profile_base + 'logout', "label": label})
def logout_service_description(self)
Logout service description.
6.07914
6.239717
0.974265
if (token): data = {"accessToken": token, "expiresIn": self.access_token_lifetime} if (message_id): data['messageId'] = message_id else: data = {"error": "client_unauthorized", "description": "No authori...
def access_token_response(self, token, message_id=None)
Access token response structure. Success if token is set, otherwise (None, empty string) give error response. If message_id is set then an extra messageId attribute is set in the response to handle postMessage() responses.
3.7221
3.907502
0.952552
uri = scheme + '://' + host if (port and not ((scheme == 'http' and port == 80) or (scheme == 'https' and port == 443))): uri += ':' + str(port) if (prefix): uri += '/' + prefix return uri
def scheme_host_port_prefix(self, scheme='http', host='host', port=None, prefix=None)
Return URI composed of scheme, server, port, and prefix.
2.150217
2.065581
1.040974