repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
sparklingpandas/sparklingpandas
sparklingpandas/dataframe.py
DataFrame.fromDataFrameRDD
def fromDataFrameRDD(cls, rdd, sql_ctx): """Construct a DataFrame from an RDD of DataFrames. No checking or validation occurs.""" result = DataFrame(None, sql_ctx) return result.from_rdd_of_dataframes(rdd)
python
def fromDataFrameRDD(cls, rdd, sql_ctx): """Construct a DataFrame from an RDD of DataFrames. No checking or validation occurs.""" result = DataFrame(None, sql_ctx) return result.from_rdd_of_dataframes(rdd)
Construct a DataFrame from an RDD of DataFrames. No checking or validation occurs.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/dataframe.py#L145-L149
sparklingpandas/sparklingpandas
sparklingpandas/dataframe.py
DataFrame.applymap
def applymap(self, f, **kwargs): """Return a new DataFrame by applying a function to each element of each Panda DataFrame.""" def transform_rdd(rdd): return rdd.map(lambda data: data.applymap(f), **kwargs) return self._evil_apply_with_dataframes(transform_rdd, preserves_cols=True)
python
def applymap(self, f, **kwargs): """Return a new DataFrame by applying a function to each element of each Panda DataFrame.""" def transform_rdd(rdd): return rdd.map(lambda data: data.applymap(f), **kwargs) return self._evil_apply_with_dataframes(transform_rdd, preserves_cols=True)
Return a new DataFrame by applying a function to each element of each Panda DataFrame.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/dataframe.py#L165-L171
sparklingpandas/sparklingpandas
sparklingpandas/dataframe.py
DataFrame.groupby
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.""" 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)
python
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.""" 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)
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.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/dataframe.py#L181-L188
sparklingpandas/sparklingpandas
sparklingpandas/dataframe.py
DataFrame.collect
def collect(self): """Collect the elements in an DataFrame and concatenate the partition.""" local_df = self._schema_rdd.toPandas() correct_idx_df = _update_index_on_df(local_df, self._index_names) return correct_idx_df
python
def collect(self): """Collect the elements in an DataFrame and concatenate the partition.""" local_df = self._schema_rdd.toPandas() correct_idx_df = _update_index_on_df(local_df, self._index_names) return correct_idx_df
Collect the elements in an DataFrame and concatenate the partition.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/dataframe.py#L233-L238
sparklingpandas/sparklingpandas
sparklingpandas/dataframe.py
DataFrame.stats
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. """ 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.sql import functions as F functions = [F.min, F.max, F.avg, F.count] aggs = list( self._flatmap(lambda column: map(lambda f: f(column), functions), columns)) return PStats(self.from_schema_rdd(self._schema_rdd.agg(*aggs)))
python
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. """ 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.sql import functions as F functions = [F.min, F.max, F.avg, F.count] aggs = list( self._flatmap(lambda column: map(lambda f: f(column), functions), columns)) return PStats(self.from_schema_rdd(self._schema_rdd.agg(*aggs)))
Compute the stats for each column provided in columns. Parameters ---------- columns : list of str, contains all columns to compute stats on.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/dataframe.py#L240-L256
sparklingpandas/sparklingpandas
sparklingpandas/prdd.py
PRDD.applymap
def applymap(self, func, **kwargs): """Return a new PRDD by applying a function to each element of each pandas DataFrame.""" return self.from_rdd( self._rdd.map(lambda data: data.applymap(func), **kwargs))
python
def applymap(self, func, **kwargs): """Return a new PRDD by applying a function to each element of each pandas DataFrame.""" return self.from_rdd( self._rdd.map(lambda data: data.applymap(func), **kwargs))
Return a new PRDD by applying a function to each element of each pandas DataFrame.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/prdd.py#L49-L53
sparklingpandas/sparklingpandas
sparklingpandas/prdd.py
PRDD.groupby
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.""" from sparklingpandas.groupby import GroupBy return GroupBy(self._rdd, *args, **kwargs)
python
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.""" from sparklingpandas.groupby import GroupBy return GroupBy(self._rdd, *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.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/prdd.py#L59-L66
sparklingpandas/sparklingpandas
sparklingpandas/prdd.py
PRDD.collect
def collect(self): """Collect the elements in an PRDD and concatenate the partition.""" # 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 self._custom_rdd_reduce(append_frames)
python
def collect(self): """Collect the elements in an PRDD and concatenate the partition.""" # 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 self._custom_rdd_reduce(append_frames)
Collect the elements in an PRDD and concatenate the partition.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/prdd.py#L108-L115
sparklingpandas/sparklingpandas
sparklingpandas/prdd.py
PRDD._custom_rdd_reduce
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 does partition reduces locally this code will also need to be updated.""" 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.mapPartitions(accumulating_iter).collect() return reduce(accumulating_iter, vals)
python
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 does partition reduces locally this code will also need to be updated.""" 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.mapPartitions(accumulating_iter).collect() return reduce(accumulating_iter, vals)
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 does partition reduces locally this code will also need to be updated.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/prdd.py#L117-L134
sparklingpandas/sparklingpandas
sparklingpandas/prdd.py
PRDD.stats
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. """ def reduce_func(sc1, sc2): return sc1.merge_pstats(sc2) return self._rdd.mapPartitions(lambda partition: [ PStatCounter(dataframes=partition, columns=columns)])\ .reduce(reduce_func)
python
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. """ def reduce_func(sc1, sc2): return sc1.merge_pstats(sc2) return self._rdd.mapPartitions(lambda partition: [ PStatCounter(dataframes=partition, columns=columns)])\ .reduce(reduce_func)
Compute the stats for each column provided in columns. Parameters ---------- columns : list of str, contains all columns to compute stats on.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/prdd.py#L136-L147
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
PSparkContext.read_csv
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 names. Parameters ---------- file_path: string Path to input. Any valid file path in Spark works here, eg: 'file:///my/path/in/local/file/system' or 'hdfs:/user/juliet/' use_whole_file: boolean Whether of not to use the whole file. names: list of strings, optional skiprows: integer, optional indicates how many rows of input to skip. This will only be applied to the first partition of the data (so if #skiprows > #row in first partition this will not work). Generally this shouldn't be an issue for small values of skiprows. No other value of header is supported. All additional parameters available in pandas.read_csv() are usable here. Returns ------- A SparklingPandas DataFrame that contains the data from the specified file. """ 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: yield pandas.read_csv( sio(contents), *args, header=None, names=mynames, skiprows=_skiprows, **kwargs) else: file_count += 1 yield pandas.read_csv( sio(contents), *args, header=None, names=mynames, **kwargs) def csv_rows(partition_number, rows): # pylint: disable=unexpected-keyword-arg in_str = "\n".join(rows) if partition_number == 0: return iter([ pandas.read_csv( sio(in_str), *args, header=None, names=mynames, skiprows=_skiprows, **kwargs)]) else: # could use .iterows instead? return iter([pandas.read_csv(sio(in_str), *args, header=None, names=mynames, **kwargs)]) # If we need to peak at the first partition and determine the column # names mynames = None _skiprows = skiprows if names: mynames = names else: # In the future we could avoid this expensive call. first_line = self.spark_ctx.textFile(file_path).first() frame = pandas.read_csv(sio(first_line), **kwargs) # pylint sees frame as a tuple despite it being a DataFrame mynames = list(frame.columns) _skiprows += 1 # Do the actual load if use_whole_file: return self.from_pandas_rdd( self.spark_ctx.wholeTextFiles(file_path) .mapPartitionsWithIndex(csv_file)) else: return self.from_pandas_rdd( self.spark_ctx.textFile(file_path) .mapPartitionsWithIndex(csv_rows))
python
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 names. Parameters ---------- file_path: string Path to input. Any valid file path in Spark works here, eg: 'file:///my/path/in/local/file/system' or 'hdfs:/user/juliet/' use_whole_file: boolean Whether of not to use the whole file. names: list of strings, optional skiprows: integer, optional indicates how many rows of input to skip. This will only be applied to the first partition of the data (so if #skiprows > #row in first partition this will not work). Generally this shouldn't be an issue for small values of skiprows. No other value of header is supported. All additional parameters available in pandas.read_csv() are usable here. Returns ------- A SparklingPandas DataFrame that contains the data from the specified file. """ 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: yield pandas.read_csv( sio(contents), *args, header=None, names=mynames, skiprows=_skiprows, **kwargs) else: file_count += 1 yield pandas.read_csv( sio(contents), *args, header=None, names=mynames, **kwargs) def csv_rows(partition_number, rows): # pylint: disable=unexpected-keyword-arg in_str = "\n".join(rows) if partition_number == 0: return iter([ pandas.read_csv( sio(in_str), *args, header=None, names=mynames, skiprows=_skiprows, **kwargs)]) else: # could use .iterows instead? return iter([pandas.read_csv(sio(in_str), *args, header=None, names=mynames, **kwargs)]) # If we need to peak at the first partition and determine the column # names mynames = None _skiprows = skiprows if names: mynames = names else: # In the future we could avoid this expensive call. first_line = self.spark_ctx.textFile(file_path).first() frame = pandas.read_csv(sio(first_line), **kwargs) # pylint sees frame as a tuple despite it being a DataFrame mynames = list(frame.columns) _skiprows += 1 # Do the actual load if use_whole_file: return self.from_pandas_rdd( self.spark_ctx.wholeTextFiles(file_path) .mapPartitionsWithIndex(csv_file)) else: return self.from_pandas_rdd( self.spark_ctx.textFile(file_path) .mapPartitionsWithIndex(csv_rows))
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 names. Parameters ---------- file_path: string Path to input. Any valid file path in Spark works here, eg: 'file:///my/path/in/local/file/system' or 'hdfs:/user/juliet/' use_whole_file: boolean Whether of not to use the whole file. names: list of strings, optional skiprows: integer, optional indicates how many rows of input to skip. This will only be applied to the first partition of the data (so if #skiprows > #row in first partition this will not work). Generally this shouldn't be an issue for small values of skiprows. No other value of header is supported. All additional parameters available in pandas.read_csv() are usable here. Returns ------- A SparklingPandas DataFrame that contains the data from the specified file.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L68-L155
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
PSparkContext.jsonFile
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 know the schema of your input data you can specify it. The schema is specified using Spark SQL's schema format. If not specified will sample the json records to determine the schema. Spark SQL's schema format is documented (somewhat) in the "Programmatically Specifying the Schema" of the Spark SQL programming guide at: http://bit.ly/sparkSQLprogrammingGuide sampling_ratio: int, default=1.0 Percentage of the records to sample when infering schema. Defaults to all records for safety, but you may be able to set to a lower ratio if the same fields are present accross records or your input is of sufficient size. Returns ------- A L{DataFrame} of the contents of the json files. """ schema_rdd = self.sql_ctx.jsonFile(path, schema, sampling_ratio) return self.from_spark_rdd(schema_rdd)
python
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 know the schema of your input data you can specify it. The schema is specified using Spark SQL's schema format. If not specified will sample the json records to determine the schema. Spark SQL's schema format is documented (somewhat) in the "Programmatically Specifying the Schema" of the Spark SQL programming guide at: http://bit.ly/sparkSQLprogrammingGuide sampling_ratio: int, default=1.0 Percentage of the records to sample when infering schema. Defaults to all records for safety, but you may be able to set to a lower ratio if the same fields are present accross records or your input is of sufficient size. Returns ------- A L{DataFrame} of the contents of the json files. """ schema_rdd = self.sql_ctx.jsonFile(path, schema, sampling_ratio) return self.from_spark_rdd(schema_rdd)
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 know the schema of your input data you can specify it. The schema is specified using Spark SQL's schema format. If not specified will sample the json records to determine the schema. Spark SQL's schema format is documented (somewhat) in the "Programmatically Specifying the Schema" of the Spark SQL programming guide at: http://bit.ly/sparkSQLprogrammingGuide sampling_ratio: int, default=1.0 Percentage of the records to sample when infering schema. Defaults to all records for safety, but you may be able to set to a lower ratio if the same fields are present accross records or your input is of sufficient size. Returns ------- A L{DataFrame} of the contents of the json files.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L171-L196
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
PSparkContext.from_pd_data_frame
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 a distributed Sparkling Pandas DataFrame. See http://bit.ly/pandasDataFrame for docs. Returns ------- A Sparkling Pandas DataFrame. """ def frame_to_rows(frame): """Convert a Pandas DataFrame into a list of Spark SQL Rows""" # 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) schema = index_names + schema rows = self.spark_ctx.parallelize(frame_to_rows(local_df)) sp_df = DataFrame.from_schema_rdd( self.sql_ctx.createDataFrame( rows, schema=schema, # Look at all the rows, should be ok since coming from # a local dataset samplingRatio=1)) sp_df._index_names = index_names return sp_df
python
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 a distributed Sparkling Pandas DataFrame. See http://bit.ly/pandasDataFrame for docs. Returns ------- A Sparkling Pandas DataFrame. """ def frame_to_rows(frame): """Convert a Pandas DataFrame into a list of Spark SQL Rows""" # 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) schema = index_names + schema rows = self.spark_ctx.parallelize(frame_to_rows(local_df)) sp_df = DataFrame.from_schema_rdd( self.sql_ctx.createDataFrame( rows, schema=schema, # Look at all the rows, should be ok since coming from # a local dataset samplingRatio=1)) sp_df._index_names = index_names return sp_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 a distributed Sparkling Pandas DataFrame. See http://bit.ly/pandasDataFrame for docs. Returns ------- A Sparkling Pandas DataFrame.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L198-L229
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
PSparkContext.sql
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 execute. Returns ------- Sparkling Pandas DataFrame. """ return DataFrame.from_spark_rdd(self.sql_ctx.sql(query), self.sql_ctx)
python
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 execute. Returns ------- Sparkling Pandas DataFrame. """ return DataFrame.from_spark_rdd(self.sql_ctx.sql(query), self.sql_ctx)
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 execute. Returns ------- Sparkling Pandas DataFrame.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L231-L243
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
PSparkContext.table
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. """ return DataFrame.from_spark_rdd(self.sql_ctx.table(table), self.sql_ctx)
python
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. """ return DataFrame.from_spark_rdd(self.sql_ctx.table(table), self.sql_ctx)
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.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L245-L256
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
PSparkContext.DataFrame
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 ---------- elements: numpy ndarray (structured or homogeneous), dict, or Pandas DataFrame. Input elements to use with the DataFrame. Additional parameters as defined by L{pandas.DataFrame}. Returns ------- Sparkling Pandas DataFrame.""" return self.from_pd_data_frame(pandas.DataFrame( elements, *args, **kwargs))
python
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 ---------- elements: numpy ndarray (structured or homogeneous), dict, or Pandas DataFrame. Input elements to use with the DataFrame. Additional parameters as defined by L{pandas.DataFrame}. Returns ------- Sparkling Pandas DataFrame.""" return self.from_pd_data_frame(pandas.DataFrame( 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 ---------- elements: numpy ndarray (structured or homogeneous), dict, or Pandas DataFrame. Input elements to use with the DataFrame. Additional parameters as defined by L{pandas.DataFrame}. Returns ------- Sparkling Pandas DataFrame.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L272-L289
sparklingpandas/sparklingpandas
sparklingpandas/pcontext.py
PSparkContext.read_json
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 ---------- file_path: string Path to input. Any valid file path in Spark works here, eg: 'my/path/in/local/file/system' or 'hdfs:/user/juliet/' Other than skipRows, all additional parameters available in pandas.read_csv() are usable here. Returns ------- A SparklingPandas DataFrame that contains the data from the specified file. """ def json_file_to_df(files): """ Transforms a JSON file into a list of data""" 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))
python
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 ---------- file_path: string Path to input. Any valid file path in Spark works here, eg: 'my/path/in/local/file/system' or 'hdfs:/user/juliet/' Other than skipRows, all additional parameters available in pandas.read_csv() are usable here. Returns ------- A SparklingPandas DataFrame that contains the data from the specified file. """ def json_file_to_df(files): """ Transforms a JSON file into a list of data""" 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))
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 ---------- file_path: string Path to input. Any valid file path in Spark works here, eg: 'my/path/in/local/file/system' or 'hdfs:/user/juliet/' Other than skipRows, all additional parameters available in pandas.read_csv() are usable here. Returns ------- A SparklingPandas DataFrame that contains the data from the specified file.
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/pcontext.py#L303-L329
zimeon/iiif
iiif/manipulator_gen.py
IIIFManipulatorGen.do_first
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 """ # 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.split(name) module_name = 'iiif.generators.' + mod try: module = sys.modules[module_name] except KeyError: self.logger.debug( "Loading generator module %s" % (module_name)) # Would be nice to use importlib but this is available only # in python 2.7 and higher pack = __import__(module_name) # returns iiif package module = getattr(pack.generators, mod) self.gen = module.PixelGen() except ImportError: raise IIIFError( text=("Failed to load generator %s" % (str(self.srcfile)))) (self.width, self.height) = self.gen.size
python
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 """ # 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.split(name) module_name = 'iiif.generators.' + mod try: module = sys.modules[module_name] except KeyError: self.logger.debug( "Loading generator module %s" % (module_name)) # Would be nice to use importlib but this is available only # in python 2.7 and higher pack = __import__(module_name) # returns iiif package module = getattr(pack.generators, mod) self.gen = module.PixelGen() except ImportError: raise IIIFError( text=("Failed to load generator %s" % (str(self.srcfile)))) (self.width, self.height) = self.gen.size
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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_gen.py#L31-L60
zimeon/iiif
iiif/manipulator_gen.py
IIIFManipulatorGen.do_region
def do_region(self, x, y, w, h): """Record region.""" 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
python
def do_region(self, x, y, w, h): """Record region.""" 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
Record region.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_gen.py#L62-L73
zimeon/iiif
iiif/manipulator_gen.py
IIIFManipulatorGen.do_size
def do_size(self, w, h): """Record size.""" 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, self.sh): for x in range(0, self.sw): ix = int((x * self.rw) // self.sw + self.rx) iy = int((y * self.rh) // self.sh + self.ry) color = self.gen.pixel(ix, iy) if (color is not None): image.putpixel((x, y), color) self.image = image
python
def do_size(self, w, h): """Record size.""" 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, self.sh): for x in range(0, self.sw): ix = int((x * self.rw) // self.sw + self.rx) iy = int((y * self.rh) // self.sh + self.ry) color = self.gen.pixel(ix, iy) if (color is not None): image.putpixel((x, y), color) self.image = image
Record size.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_gen.py#L75-L92
zimeon/iiif
iiif_static.py
main
def main(): """Parse arguments, instantiate IIIFStatic, run.""" if (sys.version_info < (2, 7)): sys.exit("This program requires python version 2.7 or later") # Options and arguments p = optparse.OptionParser(description='IIIF Image API static file generator', usage='usage: %prog [options] file [[file2..]] (-h for help)', version='%prog ' + __version__) p.add_option('--dst', '-d', action='store', default='/tmp', help="Destination directory for images [default '%default']") p.add_option('--tilesize', '-t', action='store', type='int', default=512, help="Tilesize in pixels [default %default]") p.add_option('--api-version', '--api', '-a', action='store', default='2.1', help="API version, may be 1.1, 2.0 or 2.1 [default %default]") p.add_option('--prefix', '-p', action='store', default=None, help="URI prefix for where the images will be served from (default '%default'). " "An empty prefix may be OK if the HTML page including the image shares the " "the same root on the same server as the images, otherwise a full URL should " "be specified. This is used to construct the @id in the info.json") p.add_option('--identifier', '-i', action='store', default=None, help="Identifier for the image that will be used in place of the filename " "(minus extension). Notes that this option cannot be used if more than " "one image file is to be processed") p.add_option('--extra', '-e', action='append', default=[], help="Extra request parameters to be used to generate static files, may be " "repeated (e.g. '/full/90,/0/default.jpg' for a 90 wide thumnail)") p.add_option('--write-html', action='store', default=None, help="Write HTML page to the specified directory using the 'identifier.html' " "as the filename. HTML will launch OpenSeadragon for this image and to " "display some of information about info.json and tile locations. HTML will " "assume OpenSeadragon at relative path openseadragonVVV/openseadragon.min.js " "and user-interface icons in openseadragonVVV/images, where VVV are the " "three parts of the version number. The --include-osd flag is also specified " "then OpenSeadragon will be copied to these locations") p.add_option('--include-osd', action='store_true', help="Include OpenSeadragon files with --write-html flag") p.add_option('--osd-version', action='store', default='2.0.0', help="Generate static images for older versions of OpenSeadragon. Use of versions " "prior to 1.2.1 will force use of /w,h/ for size parameter instead of /w,/. " "Likely useful only in combination with --api-version=1.1 " "[default %default]") p.add_option('--osd-width', action='store', type='int', default='500', help="Width of OpenSeadragon pane in pixels. Applies only with " "--write-html [default %default]") p.add_option('--osd-height', action='store', type='int', default='500', help="Height of OpenSeadragon pane in pixels. Applies only with " "--write-html [default %default]") p.add_option('--generator', action='store_true', default=False, help="Use named generator modules in iiif.generators package instead " "of a starting image [default %default]") p.add_option('--max-image-pixels', action='store', type='int', default=0, help="Set the maximum number of pixels in an image. A non-zero value " "will set a hard limit on the image size. If left unset then the " "default configuration of the Python Image Libary (PIL) will give " "a DecompressionBombWarning if the image size exceeds a default " "maximum, but otherwise continue as normal") p.add_option('--dryrun', '-n', action='store_true', help="Do not write anything, say what would be done") p.add_option('--quiet', '-q', action='store_true', help="Quite (no output unless there is a warning/error)") p.add_option('--verbose', '-v', action='store_true', help="Verbose") (opt, sources) = p.parse_args() level = logging.DEBUG if (opt.verbose) else \ logging.WARNING if (opt.quiet) else logging.INFO logging.basicConfig(format='%(name)s: %(message)s', level=level) logger = logging.getLogger(os.path.basename(__file__)) if (not opt.write_html and opt.include_osd): logger.warn( "--include-osd has no effect without --write-html, ignoring") if (len(sources) == 0): logger.warn("No sources specified, nothing to do, bye! (-h for help)") elif (len(sources) > 1 and opt.identifier): logger.error( "Cannot use --identifier/-i option with multiple sources, aborting.") else: try: sg = IIIFStatic(dst=opt.dst, tilesize=opt.tilesize, api_version=opt.api_version, dryrun=opt.dryrun, prefix=opt.prefix, osd_version=opt.osd_version, generator=opt.generator, max_image_pixels=opt.max_image_pixels, extras=opt.extra) for source in sources: # File or directory (or neither)? if (os.path.isfile(source) or opt.generator): logger.info("source file: %s" % (source)) sg.generate(source, identifier=opt.identifier) if (opt.write_html): sg.write_html(html_dir=opt.write_html, include_osd=opt.include_osd, osd_width=opt.osd_width, osd_height=opt.osd_height) elif (os.path.isdir(source)): logger.warn( "Ignoring source '%s': directory coversion not supported" % (source)) else: logger.warn( "Ignoring source '%s': neither file nor path" % (source)) except (IIIFStaticError, IIIFError) as e: # catch known errors and report nicely... logger.error("Error: " + str(e))
python
def main(): """Parse arguments, instantiate IIIFStatic, run.""" if (sys.version_info < (2, 7)): sys.exit("This program requires python version 2.7 or later") # Options and arguments p = optparse.OptionParser(description='IIIF Image API static file generator', usage='usage: %prog [options] file [[file2..]] (-h for help)', version='%prog ' + __version__) p.add_option('--dst', '-d', action='store', default='/tmp', help="Destination directory for images [default '%default']") p.add_option('--tilesize', '-t', action='store', type='int', default=512, help="Tilesize in pixels [default %default]") p.add_option('--api-version', '--api', '-a', action='store', default='2.1', help="API version, may be 1.1, 2.0 or 2.1 [default %default]") p.add_option('--prefix', '-p', action='store', default=None, help="URI prefix for where the images will be served from (default '%default'). " "An empty prefix may be OK if the HTML page including the image shares the " "the same root on the same server as the images, otherwise a full URL should " "be specified. This is used to construct the @id in the info.json") p.add_option('--identifier', '-i', action='store', default=None, help="Identifier for the image that will be used in place of the filename " "(minus extension). Notes that this option cannot be used if more than " "one image file is to be processed") p.add_option('--extra', '-e', action='append', default=[], help="Extra request parameters to be used to generate static files, may be " "repeated (e.g. '/full/90,/0/default.jpg' for a 90 wide thumnail)") p.add_option('--write-html', action='store', default=None, help="Write HTML page to the specified directory using the 'identifier.html' " "as the filename. HTML will launch OpenSeadragon for this image and to " "display some of information about info.json and tile locations. HTML will " "assume OpenSeadragon at relative path openseadragonVVV/openseadragon.min.js " "and user-interface icons in openseadragonVVV/images, where VVV are the " "three parts of the version number. The --include-osd flag is also specified " "then OpenSeadragon will be copied to these locations") p.add_option('--include-osd', action='store_true', help="Include OpenSeadragon files with --write-html flag") p.add_option('--osd-version', action='store', default='2.0.0', help="Generate static images for older versions of OpenSeadragon. Use of versions " "prior to 1.2.1 will force use of /w,h/ for size parameter instead of /w,/. " "Likely useful only in combination with --api-version=1.1 " "[default %default]") p.add_option('--osd-width', action='store', type='int', default='500', help="Width of OpenSeadragon pane in pixels. Applies only with " "--write-html [default %default]") p.add_option('--osd-height', action='store', type='int', default='500', help="Height of OpenSeadragon pane in pixels. Applies only with " "--write-html [default %default]") p.add_option('--generator', action='store_true', default=False, help="Use named generator modules in iiif.generators package instead " "of a starting image [default %default]") p.add_option('--max-image-pixels', action='store', type='int', default=0, help="Set the maximum number of pixels in an image. A non-zero value " "will set a hard limit on the image size. If left unset then the " "default configuration of the Python Image Libary (PIL) will give " "a DecompressionBombWarning if the image size exceeds a default " "maximum, but otherwise continue as normal") p.add_option('--dryrun', '-n', action='store_true', help="Do not write anything, say what would be done") p.add_option('--quiet', '-q', action='store_true', help="Quite (no output unless there is a warning/error)") p.add_option('--verbose', '-v', action='store_true', help="Verbose") (opt, sources) = p.parse_args() level = logging.DEBUG if (opt.verbose) else \ logging.WARNING if (opt.quiet) else logging.INFO logging.basicConfig(format='%(name)s: %(message)s', level=level) logger = logging.getLogger(os.path.basename(__file__)) if (not opt.write_html and opt.include_osd): logger.warn( "--include-osd has no effect without --write-html, ignoring") if (len(sources) == 0): logger.warn("No sources specified, nothing to do, bye! (-h for help)") elif (len(sources) > 1 and opt.identifier): logger.error( "Cannot use --identifier/-i option with multiple sources, aborting.") else: try: sg = IIIFStatic(dst=opt.dst, tilesize=opt.tilesize, api_version=opt.api_version, dryrun=opt.dryrun, prefix=opt.prefix, osd_version=opt.osd_version, generator=opt.generator, max_image_pixels=opt.max_image_pixels, extras=opt.extra) for source in sources: # File or directory (or neither)? if (os.path.isfile(source) or opt.generator): logger.info("source file: %s" % (source)) sg.generate(source, identifier=opt.identifier) if (opt.write_html): sg.write_html(html_dir=opt.write_html, include_osd=opt.include_osd, osd_width=opt.osd_width, osd_height=opt.osd_height) elif (os.path.isdir(source)): logger.warn( "Ignoring source '%s': directory coversion not supported" % (source)) else: logger.warn( "Ignoring source '%s': neither file nor path" % (source)) except (IIIFStaticError, IIIFError) as e: # catch known errors and report nicely... logger.error("Error: " + str(e))
Parse arguments, instantiate IIIFStatic, run.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif_static.py#L17-L122
zimeon/iiif
iiif/auth_basic.py
IIIFAuthBasic.login_handler
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. """ 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") else: headers['WWW-Authenticate'] = ( 'Basic realm="HTTP-Basic-Auth at %s (u=p to login)"' % (self.name)) return make_response("", 401, headers)
python
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. """ 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") else: headers['WWW-Authenticate'] = ( 'Basic realm="HTTP-Basic-Auth at %s (u=p to login)"' % (self.name)) return make_response("", 401, headers)
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_basic.py#L26-L44
zimeon/iiif
iiif/auth_clickthrough.py
IIIFAuthClickthrough.login_service_description
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. """ desc = super(IIIFAuthClickthrough, self).login_service_description() desc['confirmLabel'] = self.confirm_label return desc
python
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. """ desc = super(IIIFAuthClickthrough, self).login_service_description() desc['confirmLabel'] = self.confirm_label return desc
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_clickthrough.py#L22-L31
zimeon/iiif
iiif/request.py
IIIFRequest.clear
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. """ # 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 = False self.region_pct = False self.region_xywh = None # (x,y,w,h) self.size_full = False self.size_max = False # new in 2.1 self.size_pct = None self.size_bang = None self.size_wh = None # (w,h) self.rotation_mirror = False self.rotation_deg = 0.0
python
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. """ # 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 = False self.region_pct = False self.region_xywh = None # (x,y,w,h) self.size_full = False self.size_max = False # new in 2.1 self.size_pct = None self.size_bang = None self.size_wh = None # (w,h) self.rotation_mirror = False self.rotation_deg = 0.0
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L83-L108
zimeon/iiif
iiif/request.py
IIIFRequest.api_version
def api_version(self, v): """Set the api_version and associated configurations.""" 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 = ['native', 'color', 'bitonal', 'grey']
python
def api_version(self, v): """Set the api_version and associated configurations.""" 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 = ['native', 'color', 'bitonal', 'grey']
Set the api_version and associated configurations.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L116-L124
zimeon/iiif
iiif/request.py
IIIFRequest.url
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. """ 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: region = self.region elif self.region_xywh: region = "%d,%d,%d,%d" % tuple(self.region_xywh) else: region = "full" # size if self.size: size = self.size elif self.size_wh: if (self.size_wh[0] is None): size = ",%d" % (self.size_wh[1]) elif (self.size_wh[1] is None): size = "%d," % (self.size_wh[0]) else: size = "%d,%d" % (self.size_wh[0], self.size_wh[1]) elif (self.size_max and self.api_version >= '2.1'): size = 'max' else: size = "full" # rotation and quality rotation = self.rotation if self.rotation else "0" quality = self.quality if self.quality else self.default_quality # parameterized form path += self.quote(region) + "/" +\ self.quote(size) + "/" +\ self.quote(rotation) + "/" +\ self.quote(quality) format = self.format if (format): path += "." + format return(path)
python
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. """ 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: region = self.region elif self.region_xywh: region = "%d,%d,%d,%d" % tuple(self.region_xywh) else: region = "full" # size if self.size: size = self.size elif self.size_wh: if (self.size_wh[0] is None): size = ",%d" % (self.size_wh[1]) elif (self.size_wh[1] is None): size = "%d," % (self.size_wh[0]) else: size = "%d,%d" % (self.size_wh[0], self.size_wh[1]) elif (self.size_max and self.api_version >= '2.1'): size = 'max' else: size = "full" # rotation and quality rotation = self.rotation if self.rotation else "0" quality = self.quality if self.quality else self.default_quality # parameterized form path += self.quote(region) + "/" +\ self.quote(size) + "/" +\ self.quote(rotation) + "/" +\ self.quote(quality) format = self.format if (format): path += "." + format return(path)
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L148-L194
zimeon/iiif
iiif/request.py
IIIFRequest.parse_url
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() depends on whether self.identifier is set. """ self.split_url(url) if (not self.info): self.parse_parameters() return(self)
python
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() depends on whether self.identifier is set. """ self.split_url(url) if (not self.info): self.parse_parameters() return(self)
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() depends on whether self.identifier is set.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L196-L210
zimeon/iiif
iiif/request.py
IIIFRequest.split_url
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. """ # 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 IIIFRequestError( text="Request URL does not start with base URL") url = path # Break up by path segments, count to decide format segs = url.split('/') if (identifier is not None): segs.insert(0, identifier) elif (self.allow_slashes_in_identifier): segs = self._allow_slashes_in_identifier_munger(segs) # Now have segments with identifier as first if (len(segs) > 5): raise IIIFRequestPathError( text="Request URL (%s) has too many path segments" % url) elif (len(segs) == 5): self.identifier = urlunquote(segs[0]) self.region = urlunquote(segs[1]) self.size = urlunquote(segs[2]) self.rotation = urlunquote(segs[3]) self.quality = self.strip_format(urlunquote(segs[4])) self.info = False elif (len(segs) == 2): self.identifier = urlunquote(segs[0]) info_name = self.strip_format(urlunquote(segs[1])) if (info_name != "info"): raise IIIFRequestError( text="Bad name for Image Information") if (self.api_version == '1.0'): if (self.format not in ['json', 'xml']): raise IIIFRequestError( text="Invalid format for Image Information (json and xml allowed)") elif (self.format != 'json'): raise IIIFRequestError( text="Invalid format for Image Information (only json allowed)") self.info = True elif (len(segs) == 1): self.identifier = urlunquote(segs[0]) raise IIIFRequestBaseURI() else: raise IIIFRequestPathError( text="Bad number of path segments in request") return(self)
python
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. """ # 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 IIIFRequestError( text="Request URL does not start with base URL") url = path # Break up by path segments, count to decide format segs = url.split('/') if (identifier is not None): segs.insert(0, identifier) elif (self.allow_slashes_in_identifier): segs = self._allow_slashes_in_identifier_munger(segs) # Now have segments with identifier as first if (len(segs) > 5): raise IIIFRequestPathError( text="Request URL (%s) has too many path segments" % url) elif (len(segs) == 5): self.identifier = urlunquote(segs[0]) self.region = urlunquote(segs[1]) self.size = urlunquote(segs[2]) self.rotation = urlunquote(segs[3]) self.quality = self.strip_format(urlunquote(segs[4])) self.info = False elif (len(segs) == 2): self.identifier = urlunquote(segs[0]) info_name = self.strip_format(urlunquote(segs[1])) if (info_name != "info"): raise IIIFRequestError( text="Bad name for Image Information") if (self.api_version == '1.0'): if (self.format not in ['json', 'xml']): raise IIIFRequestError( text="Invalid format for Image Information (json and xml allowed)") elif (self.format != 'json'): raise IIIFRequestError( text="Invalid format for Image Information (only json allowed)") self.info = True elif (len(segs) == 1): self.identifier = urlunquote(segs[0]) raise IIIFRequestBaseURI() else: raise IIIFRequestPathError( text="Bad number of path segments in request") return(self)
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L228-L285
zimeon/iiif
iiif/request.py
IIIFRequest.strip_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 """ 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)
python
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 """ 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)
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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L287-L301
zimeon/iiif
iiif/request.py
IIIFRequest.parse_parameters
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. """ self.parse_region() self.parse_size() self.parse_rotation() self.parse_quality() self.parse_format()
python
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. """ self.parse_region() self.parse_size() self.parse_rotation() self.parse_quality() self.parse_format()
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L303-L315
zimeon/iiif
iiif/request.py
IIIFRequest.parse_region
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 parameters are illegal according to the specification but does not know about and thus cannot do any tests against any image being manipulated. """ 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_square = True return xywh = self.region pct_match = re.match('pct:(.*)$', self.region) if (pct_match): xywh = pct_match.group(1) self.region_pct = True # Now whether this was pct: or now, we expect 4 values... str_values = xywh.split(',', 5) if (len(str_values) != 4): raise IIIFRequestError( code=400, parameter="region", text="Bad number of values in region specification, " "must be x,y,w,h but got %d value(s) from '%s'" % (len(str_values), xywh)) values = [] for str_value in str_values: # Must be either integer (not pct) or interger/float (pct) if (pct_match): try: # This is rather more permissive that the iiif spec value = float(str_value) except ValueError: raise IIIFRequestError( parameter="region", text="Bad floating point value for percentage in " "region (%s)." % str_value) if (value > 100.0): raise IIIFRequestError( parameter="region", text="Percentage over value over 100.0 in region " "(%s)." % str_value) else: try: value = int(str_value) except ValueError: raise IIIFRequestError( parameter="region", text="Bad integer value in region (%s)." % str_value) if (value < 0): raise IIIFRequestError( parameter="region", text="Negative values not allowed in region (%s)." % str_value) values.append(value) # Zero size region is w or h are zero (careful that they may be float) if (values[2] == 0.0 or values[3] == 0.0): raise IIIFZeroSizeError( code=400, parameter="region", text="Zero size region specified (%s))." % xywh) self.region_xywh = values
python
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 parameters are illegal according to the specification but does not know about and thus cannot do any tests against any image being manipulated. """ 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_square = True return xywh = self.region pct_match = re.match('pct:(.*)$', self.region) if (pct_match): xywh = pct_match.group(1) self.region_pct = True # Now whether this was pct: or now, we expect 4 values... str_values = xywh.split(',', 5) if (len(str_values) != 4): raise IIIFRequestError( code=400, parameter="region", text="Bad number of values in region specification, " "must be x,y,w,h but got %d value(s) from '%s'" % (len(str_values), xywh)) values = [] for str_value in str_values: # Must be either integer (not pct) or interger/float (pct) if (pct_match): try: # This is rather more permissive that the iiif spec value = float(str_value) except ValueError: raise IIIFRequestError( parameter="region", text="Bad floating point value for percentage in " "region (%s)." % str_value) if (value > 100.0): raise IIIFRequestError( parameter="region", text="Percentage over value over 100.0 in region " "(%s)." % str_value) else: try: value = int(str_value) except ValueError: raise IIIFRequestError( parameter="region", text="Bad integer value in region (%s)." % str_value) if (value < 0): raise IIIFRequestError( parameter="region", text="Negative values not allowed in region (%s)." % str_value) values.append(value) # Zero size region is w or h are zero (careful that they may be float) if (values[2] == 0.0 or values[3] == 0.0): raise IIIFZeroSizeError( code=400, parameter="region", text="Zero size region specified (%s))." % xywh) self.region_xywh = values
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 parameters are illegal according to the specification but does not know about and thus cannot do any tests against any image being manipulated.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L317-L386
zimeon/iiif
iiif/request.py
IIIFRequest.parse_size
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 = (w,h), self.size_bang = True Expected use: (w,h) = iiif.size_to_apply(region_w,region_h) if (q is None): # full image else: # scale to w by h Returns (None,None) if no scaling is required. """ 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 (self.size == 'max' and self.api_version >= '2.1'): self.size_max = True return pct_match = re.match('pct:(.*)$', self.size) if (pct_match is not None): pct_str = pct_match.group(1) try: self.size_pct = float(pct_str) except ValueError: raise IIIFRequestError( code=400, parameter="size", text="Percentage size value must be a number, got " "'%s'." % (pct_str)) # Note that Image API specificaton places no upper limit on # size so none is implemented here. if (self.size_pct < 0.0): raise IIIFRequestError( code=400, parameter="size", text="Base size percentage, must be > 0.0, got %f." % (self.size_pct)) else: if (self.size[0] == '!'): # Have "!w,h" form size_no_bang = self.size[1:] (mw, mh) = self._parse_w_comma_h(size_no_bang, 'size') if (mw is None or mh is None): raise IIIFRequestError( code=400, parameter="size", text="Illegal size requested: both w,h must be " "specified in !w,h requests.") self.size_wh = (mw, mh) self.size_bang = True else: # Must now be "w,h", "w," or ",h" self.size_wh = self._parse_w_comma_h(self.size, 'size') # Sanity check w,h (w, h) = self.size_wh if ((w is not None and w <= 0) or (h is not None and h <= 0)): raise IIIFZeroSizeError( code=400, parameter='size', text="Size parameters request zero size result image.")
python
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 = (w,h), self.size_bang = True Expected use: (w,h) = iiif.size_to_apply(region_w,region_h) if (q is None): # full image else: # scale to w by h Returns (None,None) if no scaling is required. """ 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 (self.size == 'max' and self.api_version >= '2.1'): self.size_max = True return pct_match = re.match('pct:(.*)$', self.size) if (pct_match is not None): pct_str = pct_match.group(1) try: self.size_pct = float(pct_str) except ValueError: raise IIIFRequestError( code=400, parameter="size", text="Percentage size value must be a number, got " "'%s'." % (pct_str)) # Note that Image API specificaton places no upper limit on # size so none is implemented here. if (self.size_pct < 0.0): raise IIIFRequestError( code=400, parameter="size", text="Base size percentage, must be > 0.0, got %f." % (self.size_pct)) else: if (self.size[0] == '!'): # Have "!w,h" form size_no_bang = self.size[1:] (mw, mh) = self._parse_w_comma_h(size_no_bang, 'size') if (mw is None or mh is None): raise IIIFRequestError( code=400, parameter="size", text="Illegal size requested: both w,h must be " "specified in !w,h requests.") self.size_wh = (mw, mh) self.size_bang = True else: # Must now be "w,h", "w," or ",h" self.size_wh = self._parse_w_comma_h(self.size, 'size') # Sanity check w,h (w, h) = self.size_wh if ((w is not None and w <= 0) or (h is not None and h <= 0)): raise IIIFZeroSizeError( code=400, parameter='size', text="Size parameters request zero size result image.")
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 = (w,h), self.size_bang = True Expected use: (w,h) = iiif.size_to_apply(region_w,region_h) if (q is None): # full image else: # scale to w by h Returns (None,None) if no scaling is required.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L388-L457
zimeon/iiif
iiif/request.py
IIIFRequest._parse_w_comma_h
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. """ 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="Illegal %s value (%s)." % (param, str(e))) if (w is None and h is None): raise IIIFRequestError( code=400, parameter=param, text="Must specify at least one of w,h for %s." % (param)) return(w, h)
python
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. """ 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="Illegal %s value (%s)." % (param, str(e))) if (w is None and h is None): raise IIIFRequestError( code=400, parameter=param, text="Must specify at least one of w,h for %s." % (param)) return(w, h)
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L459-L477
zimeon/iiif
iiif/request.py
IIIFRequest._parse_non_negative_int
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. """ 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)
python
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. """ 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)
Parse integer from string (istr). The (name) parameter is used just for IIIFRequestError message generation to indicate what the error is in.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L479-L493
zimeon/iiif
iiif/request.py
IIIFRequest.parse_rotation
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 will be set True, otherwise it will be False. """ 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 self.rotation = self.rotation[1:] # Interpret value now try: self.rotation_deg = float(self.rotation) except ValueError: raise IIIFRequestError( code=400, parameter="rotation", text="Bad rotation value, must be a number, got '%s'." % (self.rotation)) if (self.rotation_deg < 0.0 or self.rotation_deg > 360.0): raise IIIFRequestError( code=400, parameter="rotation", text="Illegal rotation value, must be 0 <= rotation " "<= 360, got %f." % (self.rotation_deg)) elif (self.rotation_deg == 360.0): # The spec admits 360 as valid, but change to 0 self.rotation_deg = 0.0
python
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 will be set True, otherwise it will be False. """ 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 self.rotation = self.rotation[1:] # Interpret value now try: self.rotation_deg = float(self.rotation) except ValueError: raise IIIFRequestError( code=400, parameter="rotation", text="Bad rotation value, must be a number, got '%s'." % (self.rotation)) if (self.rotation_deg < 0.0 or self.rotation_deg > 360.0): raise IIIFRequestError( code=400, parameter="rotation", text="Illegal rotation value, must be 0 <= rotation " "<= 360, got %f." % (self.rotation_deg)) elif (self.rotation_deg == 360.0): # The spec admits 360 as valid, but change to 0 self.rotation_deg = 0.0
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 will be set True, otherwise it will be False.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L495-L529
zimeon/iiif
iiif/request.py
IIIFRequest.parse_quality
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. """ 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'." % ("', '".join(self.allowed_qualities), self.quality)) else: self.quality_val = self.quality
python
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. """ 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'." % ("', '".join(self.allowed_qualities), self.quality)) else: self.quality_val = self.quality
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L531-L546
zimeon/iiif
iiif/request.py
IIIFRequest.parse_format
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. """ if (self.format is not None and not re.match(r'''\w{1,20}$''', self.format)): raise IIIFRequestError( parameter='format', text='Bad format parameter')
python
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. """ if (self.format is not None and not re.match(r'''\w{1,20}$''', self.format)): raise IIIFRequestError( parameter='format', text='Bad format parameter')
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L548-L560
zimeon/iiif
iiif/request.py
IIIFRequest.is_scaled_full_image
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. """ 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')
python
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. """ 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')
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/request.py#L562-L574
zimeon/iiif
iiif_reference_server.py
get_config
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. """ 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_dir) p.add('--scale-factors', default='auto', help="Set of tile scale factors or 'auto' to calculate for each image " "such that there are tiles up to the full image") p.add('--api-versions', default='1.0,1.1,2.0,2.1', help="Set of API versions to support") args = p.parse_args() if (args.debug): args.verbose = True elif (args.verbose): args.quiet = False # Split list arguments args.scale_factors = split_comma_argument(args.scale_factors) args.api_versions = split_comma_argument(args.api_versions) logging_level = logging.WARNING if args.verbose: logging_level = logging.INFO elif args.quiet: logging_level = logging.ERROR logging.basicConfig(format='%(name)s: %(message)s', level=logging_level) return(args)
python
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. """ 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_dir) p.add('--scale-factors', default='auto', help="Set of tile scale factors or 'auto' to calculate for each image " "such that there are tiles up to the full image") p.add('--api-versions', default='1.0,1.1,2.0,2.1', help="Set of API versions to support") args = p.parse_args() if (args.debug): args.verbose = True elif (args.verbose): args.quiet = False # Split list arguments args.scale_factors = split_comma_argument(args.scale_factors) args.api_versions = split_comma_argument(args.api_versions) logging_level = logging.WARNING if args.verbose: logging_level = logging.INFO elif args.quiet: logging_level = logging.ERROR logging.basicConfig(format='%(name)s: %(message)s', level=logging_level) return(args)
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif_reference_server.py#L21-L56
zimeon/iiif
iiif_reference_server.py
create_reference_server_flask_app
def create_reference_server_flask_app(cfg): """Create referece server Flask application with one or more IIIF handlers.""" # 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_config.klass_name = 'pil' handler_config.auth_type = 'none' # Set same prefix on local server as expected on iiif.io handler_config.prefix = "api/image/%s/example/reference" % (api_version) handler_config.client_prefix = handler_config.prefix add_handler(app, handler_config) return app
python
def create_reference_server_flask_app(cfg): """Create referece server Flask application with one or more IIIF handlers.""" # 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_config.klass_name = 'pil' handler_config.auth_type = 'none' # Set same prefix on local server as expected on iiif.io handler_config.prefix = "api/image/%s/example/reference" % (api_version) handler_config.client_prefix = handler_config.prefix add_handler(app, handler_config) return app
Create referece server Flask application with one or more IIIF handlers.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif_reference_server.py#L59-L76
zimeon/iiif
iiif/generators/sierpinski_carpet.py
PixelGen.pixel
def pixel(self, x, y, size=None): """Return color for a pixel.""" 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)): return None return self.pixel(x % divisor, y % divisor, divisor)
python
def pixel(self, x, y, size=None): """Return color for a pixel.""" 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)): return None return self.pixel(x % divisor, y % divisor, divisor)
Return color for a pixel.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/generators/sierpinski_carpet.py#L33-L46
zimeon/iiif
iiif/info.py
IIIFInfo.id
def id(self): """id property based on server_and_prefix and identifier.""" 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
python
def id(self): """id property based on server_and_prefix and identifier.""" 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
id property based on server_and_prefix and identifier.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L227-L235
zimeon/iiif
iiif/info.py
IIIFInfo.id
def id(self, value): """Split into server_and_prefix and identifier.""" 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 = '' self.identifier = value
python
def id(self, value): """Split into server_and_prefix and identifier.""" 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 = '' self.identifier = value
Split into server_and_prefix and identifier.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L238-L249
zimeon/iiif
iiif/info.py
IIIFInfo.set_version_info
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 """ 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'] self.complex_params = CONF[api_version]['complex_params'] for a in ('context', 'compliance_prefix', 'compliance_suffix', 'protocol', 'required_params'): if (a in CONF[api_version]): self._setattr(a, CONF[api_version][a])
python
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 """ 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'] self.complex_params = CONF[api_version]['complex_params'] for a in ('context', 'compliance_prefix', 'compliance_suffix', 'protocol', 'required_params'): if (a in CONF[api_version]): self._setattr(a, CONF[api_version][a])
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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L251-L267
zimeon/iiif
iiif/info.py
IIIFInfo.compliance
def compliance(self, value): """Set the compliance profile URI.""" 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]
python
def compliance(self, value): """Set the compliance profile URI.""" 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]
Set the compliance profile URI.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L284-L293
zimeon/iiif
iiif/info.py
IIIFInfo.level
def level(self): """Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError """ 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 number")
python
def level(self): """Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError """ 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 number")
Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L296-L310
zimeon/iiif
iiif/info.py
IIIFInfo.level
def level(self, value): """Build profile URI from level. Level should be an integer 0,1,2 """ self.compliance = self.compliance_prefix + \ ("%d" % value) + self.compliance_suffix
python
def level(self, value): """Build profile URI from level. Level should be an integer 0,1,2 """ self.compliance = self.compliance_prefix + \ ("%d" % value) + self.compliance_suffix
Build profile URI from level. Level should be an integer 0,1,2
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L313-L319
zimeon/iiif
iiif/info.py
IIIFInfo.add_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 """ if (self.service is None): self.service = service elif (isinstance(self.service, dict)): self.service = [self.service, service] else: self.service.append(service)
python
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 """ if (self.service is None): self.service = service elif (isinstance(self.service, dict)): self.service = [self.service, service] else: self.service.append(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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L391-L402
zimeon/iiif
iiif/info.py
IIIFInfo.validate
def validate(self): """Validate this object as Image API data. Raise IIIFInfoError with helpful message if not valid. """ 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)) return True
python
def validate(self): """Validate this object as Image API data. Raise IIIFInfoError with helpful message if not valid. """ 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)) return True
Validate this object as Image API data. Raise IIIFInfoError with helpful message if not valid.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L417-L428
zimeon/iiif
iiif/info.py
IIIFInfo.as_json
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). """ 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_version == '1.0'): json_dict['identifier'] = self.identifier # local id else: json_dict['@id'] = self.id # URI params_to_write.discard('profile') if (self.compliance): if (self.api_version < '2.0'): json_dict['profile'] = self.compliance else: # FIXME - need to support extra profile features json_dict['profile'] = [self.compliance] d = {} if (self.formats is not None): d['formats'] = self.formats if (self.qualities is not None): d['qualities'] = self.qualities if (self.supports is not None): d['supports'] = self.supports if (len(d) > 0): json_dict['profile'].append(d) params_to_write.discard('formats') params_to_write.discard('qualities') params_to_write.discard('supports') for param in params_to_write: if (hasattr(self, param) and getattr(self, param) is not None): json_dict[param] = getattr(self, param) return(json.dumps(json_dict, sort_keys=True, indent=2))
python
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). """ 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_version == '1.0'): json_dict['identifier'] = self.identifier # local id else: json_dict['@id'] = self.id # URI params_to_write.discard('profile') if (self.compliance): if (self.api_version < '2.0'): json_dict['profile'] = self.compliance else: # FIXME - need to support extra profile features json_dict['profile'] = [self.compliance] d = {} if (self.formats is not None): d['formats'] = self.formats if (self.qualities is not None): d['qualities'] = self.qualities if (self.supports is not None): d['supports'] = self.supports if (len(d) > 0): json_dict['profile'].append(d) params_to_write.discard('formats') params_to_write.discard('qualities') params_to_write.discard('supports') for param in params_to_write: if (hasattr(self, param) and getattr(self, param) is not None): json_dict[param] = getattr(self, param) return(json.dumps(json_dict, sort_keys=True, indent=2))
Return JSON serialization. Will raise IIIFInfoError if insufficient parameters are present to have a valid info.json response (unless validate is False).
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L430-L471
zimeon/iiif
iiif/info.py
IIIFInfo.read
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 that the value of self.api_version is NOT used in this routine. If an api_version is specified and there is a @context specified then an IIIFInfoError will be raised unless these match. If no known @context is present and no api_version set then an IIIFInfoError will be raised. """ 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): # determine API version from context self.context = j['@context'] api_version_read = None for v in CONF: if (v > '1.0' and self.context == CONF[v]['context']): api_version_read = v break if (api_version_read is None): raise IIIFInfoError( "Unknown @context, cannot determine API version (%s)" % (self.context)) else: if (api_version is not None and api_version != api_version_read): raise IIIFInfoError( "Expected API version '%s' but got @context for API version '%s'" % (api_version, api_version_read)) else: self.api_version = api_version_read else: # no @context and not 1.0 if (api_version is None): raise IIIFInfoError("No @context (and no default given)") self.api_version = api_version self.set_version_info() # # @id or identifier if (self.api_version == '1.0'): if ('identifier' in j): self.id = j['identifier'] else: raise IIIFInfoError("Missing identifier in info.json") else: if ('@id' in j): self.id = j['@id'] else: raise IIIFInfoError("Missing @id in info.json") # # other params for param in self.params: if (param == 'identifier'): continue # dealt with above if (param in j): if (param in self.complex_params): # use function ref in complex_params to parse, optional # dst to map to a different property name self._setattr(param, self.complex_params[ param](self, j[param])) else: self._setattr(param, j[param]) return True
python
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 that the value of self.api_version is NOT used in this routine. If an api_version is specified and there is a @context specified then an IIIFInfoError will be raised unless these match. If no known @context is present and no api_version set then an IIIFInfoError will be raised. """ 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): # determine API version from context self.context = j['@context'] api_version_read = None for v in CONF: if (v > '1.0' and self.context == CONF[v]['context']): api_version_read = v break if (api_version_read is None): raise IIIFInfoError( "Unknown @context, cannot determine API version (%s)" % (self.context)) else: if (api_version is not None and api_version != api_version_read): raise IIIFInfoError( "Expected API version '%s' but got @context for API version '%s'" % (api_version, api_version_read)) else: self.api_version = api_version_read else: # no @context and not 1.0 if (api_version is None): raise IIIFInfoError("No @context (and no default given)") self.api_version = api_version self.set_version_info() # # @id or identifier if (self.api_version == '1.0'): if ('identifier' in j): self.id = j['identifier'] else: raise IIIFInfoError("Missing identifier in info.json") else: if ('@id' in j): self.id = j['@id'] else: raise IIIFInfoError("Missing @id in info.json") # # other params for param in self.params: if (param == 'identifier'): continue # dealt with above if (param in j): if (param in self.complex_params): # use function ref in complex_params to parse, optional # dst to map to a different property name self._setattr(param, self.complex_params[ param](self, j[param])) else: self._setattr(param, j[param]) return True
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 that the value of self.api_version is NOT used in this routine. If an api_version is specified and there is a @context specified then an IIIFInfoError will be raised unless these match. If no known @context is present and no api_version set then an IIIFInfoError will be raised.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L473-L546
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.set_max_image_pixels
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 setting a moderate limit sets a hard limit on image size loaded, setting a very large limit will have the effect of disabling the warning. """ if (pixels): Image.MAX_IMAGE_PIXELS = pixels Image.warnings.simplefilter( 'error', Image.DecompressionBombWarning)
python
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 setting a moderate limit sets a hard limit on image size loaded, setting a very large limit will have the effect of disabling the warning. """ if (pixels): Image.MAX_IMAGE_PIXELS = pixels Image.warnings.simplefilter( 'error', Image.DecompressionBombWarning)
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 setting a moderate limit sets a hard limit on image size loaded, setting a very large limit will have the effect of disabling the warning.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L42-L57
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.do_first
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 """ 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 # that exceeed Image.MAX_IMAGE_PIXELS, with # Image.warnings.simplefilter('error', Image.DecompressionBombWarning) raise IIIFError(text=("Image size limit exceeded (PIL: %s)" % (str(e)))) except Exception as e: raise IIIFError(text=("Failed to read image (PIL: %s)" % (str(e)))) (self.width, self.height) = self.image.size
python
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 """ 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 # that exceeed Image.MAX_IMAGE_PIXELS, with # Image.warnings.simplefilter('error', Image.DecompressionBombWarning) raise IIIFError(text=("Image size limit exceeded (PIL: %s)" % (str(e)))) except Exception as e: raise IIIFError(text=("Failed to read image (PIL: %s)" % (str(e)))) (self.width, self.height) = self.image.size
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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L59-L78
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.do_region
def do_region(self, x, y, w, h): """Apply region selection.""" 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
python
def do_region(self, x, y, w, h): """Apply region selection.""" 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
Apply region selection.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L80-L88
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.do_size
def do_size(self, w, h): """Apply size scaling.""" 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
python
def do_size(self, w, h): """Apply size scaling.""" 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
Apply size scaling.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L90-L98
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.do_rotation
def do_rotation(self, mirror, rot): """Apply rotation and/or mirroring.""" 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 cases than mirror _then_ rotate. if (mirror): self.logger.debug("rotation: mirror (about vertical axis)") self.image = self.image.transpose(Image.FLIP_LEFT_RIGHT) if (rot != 0.0): self.logger.debug("rotation: by %f degrees clockwise" % (rot)) self.image = self.image.rotate(-rot, expand=True)
python
def do_rotation(self, mirror, rot): """Apply rotation and/or mirroring.""" 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 cases than mirror _then_ rotate. if (mirror): self.logger.debug("rotation: mirror (about vertical axis)") self.image = self.image.transpose(Image.FLIP_LEFT_RIGHT) if (rot != 0.0): self.logger.debug("rotation: by %f degrees clockwise" % (rot)) self.image = self.image.rotate(-rot, expand=True)
Apply rotation and/or mirroring.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L100-L113
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.do_quality
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> """ 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 to bitonal") self.image = self.image.convert('1') else: # color or default/native (which we take as color) # Deal first with conversions from I;16* formats which Pillow # appears not to handle properly, resulting in mostly white images # if we convert directly. See: # <http://stackoverflow.com/questions/7247371/python-and-16-bit-tiff> if (self.image.mode.startswith('I;16')): self.logger.debug("quality: fudged conversion from mode %s to I" % (self.image.mode)) self.image = self.image.convert('I') self.image = self.image.point(lambda i: i * (1.0 / 256.0)) if (self.image.mode not in ('1', 'L', 'RGB', 'RGBA')): # Need to convert from palette etc. in order to write out self.logger.debug("quality: converting from mode %s to RGB" % (self.image.mode)) self.image = self.image.convert('RGB') else: self.logger.debug("quality: quality (nop)")
python
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> """ 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 to bitonal") self.image = self.image.convert('1') else: # color or default/native (which we take as color) # Deal first with conversions from I;16* formats which Pillow # appears not to handle properly, resulting in mostly white images # if we convert directly. See: # <http://stackoverflow.com/questions/7247371/python-and-16-bit-tiff> if (self.image.mode.startswith('I;16')): self.logger.debug("quality: fudged conversion from mode %s to I" % (self.image.mode)) self.image = self.image.convert('I') self.image = self.image.point(lambda i: i * (1.0 / 256.0)) if (self.image.mode not in ('1', 'L', 'RGB', 'RGBA')): # Need to convert from palette etc. in order to write out self.logger.debug("quality: converting from mode %s to RGB" % (self.image.mode)) self.image = self.image.convert('RGB') else: self.logger.debug("quality: quality (nop)")
Apply value of quality parameter. For PIL docs see <http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.convert>
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L115-L144
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.do_format
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. """ 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") self.mime_type = "image/jpeg" self.output_format = fmt format = 'jpeg' elif (fmt == 'webp'): self.logger.debug("format: webp") self.mime_type = "image/webp" self.output_format = fmt format = 'webp' else: raise IIIFError(code=415, parameter='format', text="Unsupported output file format (%s), only png,jpg,webp are supported." % (fmt)) if (self.outfile is None): # Create temp f = tempfile.NamedTemporaryFile(delete=False) self.outfile = f.name self.outtmp = f.name self.image.save(f, format=format) else: # Save to specified location self.image.save(self.outfile, format=format)
python
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. """ 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") self.mime_type = "image/jpeg" self.output_format = fmt format = 'jpeg' elif (fmt == 'webp'): self.logger.debug("format: webp") self.mime_type = "image/webp" self.output_format = fmt format = 'webp' else: raise IIIFError(code=415, parameter='format', text="Unsupported output file format (%s), only png,jpg,webp are supported." % (fmt)) if (self.outfile is None): # Create temp f = tempfile.NamedTemporaryFile(delete=False) self.outfile = f.name self.outtmp = f.name self.image.save(f, format=format) else: # Save to specified location self.image.save(self.outfile, format=format)
Apply format selection. Assume that for tiling applications we want jpg so return that unless an explicit format is requested.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L146-L179
zimeon/iiif
iiif/manipulator_pil.py
IIIFManipulatorPIL.cleanup
def cleanup(self): """Cleanup: ensure image closed and remove temporary output file.""" 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 output file %s" % (self.outtmp))
python
def cleanup(self): """Cleanup: ensure image closed and remove temporary output file.""" 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 output file %s" % (self.outtmp))
Cleanup: ensure image closed and remove temporary output file.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_pil.py#L181-L193
zimeon/iiif
iiif/generators/check.py
PixelGen.pixel
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. """ 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) if (n == 5): # Middle square further divided return self.pixel(x % divisor, y % divisor, divisor, min(red + 25, 255)) elif (n % 2): return (red, 0, 0) else: return None
python
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. """ 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) if (n == 5): # Middle square further divided return self.pixel(x % divisor, y % divisor, divisor, min(red + 25, 255)) elif (n % 2): return (red, 0, 0) else: return None
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/generators/check.py#L31-L55
zimeon/iiif
iiif/flask_utils.py
html_page
def html_page(title="Page Title", body=""): """Create HTML page as string.""" 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
python
def html_page(title="Page Title", body=""): """Create HTML page as string.""" 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
Create HTML page as string.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L49-L55
zimeon/iiif
iiif/flask_utils.py
top_level_index_page
def top_level_index_page(config): """HTML top-level index page which provides a link to each handler.""" 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)
python
def top_level_index_page(config): """HTML top-level index page which provides a link to each handler.""" 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)
HTML top-level index page which provides a link to each handler.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L58-L65
zimeon/iiif
iiif/flask_utils.py
identifiers
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 code config.image_dir - directory for images Returns: ids - a list of ids """ 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(config.generator_dir, generator))): ids.append(gid) else: for image_file in os.listdir(config.image_dir): (iid, ext) = os.path.splitext(image_file) if (ext in ['.jpg', '.png', '.tif'] and os.path.isfile(os.path.join(config.image_dir, image_file))): ids.append(iid) return ids
python
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 code config.image_dir - directory for images Returns: ids - a list of ids """ 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(config.generator_dir, generator))): ids.append(gid) else: for image_file in os.listdir(config.image_dir): (iid, ext) = os.path.splitext(image_file) if (ext in ['.jpg', '.png', '.tif'] and os.path.isfile(os.path.join(config.image_dir, image_file))): ids.append(iid) return ids
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 code config.image_dir - directory for images Returns: ids - a list of ids
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L68-L98
zimeon/iiif
iiif/flask_utils.py
prefix_index_page
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: config.client_prefix - URI path prefix seen by client config.host - URI host seen by client config.api_version - string for api_version config.manipulator - string manipulator type config.auth_type - string for auth type config.include_osd - whether OSD is included """ 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_type = %s\n</p>\n' % (config.auth_type) # table of identifiers and example requests ids = identifiers(config) api_version = config.api_version default = 'native' if api_version < '2.0' else 'default' body += '<table border="1">\n<tr><th align="left">Image identifier</th>' body += '<th> </th><th>full</th>' if (config.klass_name != 'dummy'): body += '<th>256,256</th>' body += '<th>30deg</th>' if (config.include_osd): body += '<th> </th>' body += "</tr>\n" for identifier in sorted(ids): base = urljoin('/', config.client_prefix + '/' + identifier) body += '<tr><th align="left">%s</th>' % (identifier) info = base + "/info.json" body += '<td><a href="%s">%s</a></td>' % (info, 'info') suffix = "full/full/0/%s" % (default) body += '<td><a href="%s">%s</a></td>' % (base + '/' + suffix, suffix) if (config.klass_name != 'dummy'): suffix = "full/256,256/0/%s" % (default) body += '<td><a href="%s">%s</a></td>' % (base + '/' + suffix, suffix) suffix = "full/100,/30/%s" % (default) body += '<td><a href="%s">%s</a></td>' % (base + '/' + suffix, suffix) if (config.include_osd): body += '<td><a href="%s/osd.html">OSD</a></td>' % (base) body += "</tr>\n" body += "</table<\n" return html_page(title, body)
python
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: config.client_prefix - URI path prefix seen by client config.host - URI host seen by client config.api_version - string for api_version config.manipulator - string manipulator type config.auth_type - string for auth type config.include_osd - whether OSD is included """ 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_type = %s\n</p>\n' % (config.auth_type) # table of identifiers and example requests ids = identifiers(config) api_version = config.api_version default = 'native' if api_version < '2.0' else 'default' body += '<table border="1">\n<tr><th align="left">Image identifier</th>' body += '<th> </th><th>full</th>' if (config.klass_name != 'dummy'): body += '<th>256,256</th>' body += '<th>30deg</th>' if (config.include_osd): body += '<th> </th>' body += "</tr>\n" for identifier in sorted(ids): base = urljoin('/', config.client_prefix + '/' + identifier) body += '<tr><th align="left">%s</th>' % (identifier) info = base + "/info.json" body += '<td><a href="%s">%s</a></td>' % (info, 'info') suffix = "full/full/0/%s" % (default) body += '<td><a href="%s">%s</a></td>' % (base + '/' + suffix, suffix) if (config.klass_name != 'dummy'): suffix = "full/256,256/0/%s" % (default) body += '<td><a href="%s">%s</a></td>' % (base + '/' + suffix, suffix) suffix = "full/100,/30/%s" % (default) body += '<td><a href="%s">%s</a></td>' % (base + '/' + suffix, suffix) if (config.include_osd): body += '<td><a href="%s/osd.html">OSD</a></td>' % (base) body += "</tr>\n" body += "</table<\n" return html_page(title, body)
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: config.client_prefix - URI path prefix seen by client config.host - URI host seen by client config.api_version - string for api_version config.manipulator - string manipulator type config.auth_type - string for auth type config.include_osd - whether OSD is included
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L101-L152
zimeon/iiif
iiif/flask_utils.py
host_port_prefix
def host_port_prefix(host, port, prefix): """Return URI composed of scheme, server, port, and prefix.""" uri = "http://" + host if (port != 80): uri += ':' + str(port) if (prefix): uri += '/' + prefix return uri
python
def host_port_prefix(host, port, prefix): """Return URI composed of scheme, server, port, and prefix.""" uri = "http://" + host if (port != 80): uri += ':' + str(port) if (prefix): uri += '/' + prefix return uri
Return URI composed of scheme, server, port, and prefix.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L155-L162
zimeon/iiif
iiif/flask_utils.py
osd_page_handler
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 """ 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.0', osd_uri='/openseadragon200/openseadragon.min.js', osd_images_prefix='/openseadragon200/images', osd_height=500, osd_width=500, info_json_uri='info.json') return make_response(Template(template).safe_substitute(d))
python
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 """ 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.0', osd_uri='/openseadragon200/openseadragon.min.js', osd_images_prefix='/openseadragon200/images', osd_height=500, osd_width=500, info_json_uri='info.json') return make_response(Template(template).safe_substitute(d))
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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L168-L189
zimeon/iiif
iiif/flask_utils.py
iiif_info_handler
def iiif_info_handler(prefix=None, identifier=None, config=None, klass=None, auth=None, **args): """Handler for IIIF Image Information requests.""" 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_response() except IIIFError as e: return i.error_response(e) elif (auth.info_authn()): # authn but not authz -> 401 abort(401) else: # redirect to degraded response = redirect(host_port_prefix( config.host, config.port, prefix) + '/' + identifier + '-deg/info.json') response.headers['Access-control-allow-origin'] = '*' return response
python
def iiif_info_handler(prefix=None, identifier=None, config=None, klass=None, auth=None, **args): """Handler for IIIF Image Information requests.""" 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_response() except IIIFError as e: return i.error_response(e) elif (auth.info_authn()): # authn but not authz -> 401 abort(401) else: # redirect to degraded response = redirect(host_port_prefix( config.host, config.port, prefix) + '/' + identifier + '-deg/info.json') response.headers['Access-control-allow-origin'] = '*' return response
Handler for IIIF Image Information requests.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L384-L404
zimeon/iiif
iiif/flask_utils.py
iiif_image_handler
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. """ 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) except IIIFError as e: return i.error_response(e) else: # redirect to degraded (for not authz and for authn but not authz too) degraded_uri = host_port_prefix( config.host, config.port, prefix) + '/' + identifier + '-deg/' + path logging.info("Redirection to degraded: %s" % degraded_uri) response = redirect(degraded_uri) response.headers['Access-control-allow-origin'] = '*' return response
python
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. """ 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) except IIIFError as e: return i.error_response(e) else: # redirect to degraded (for not authz and for authn but not authz too) degraded_uri = host_port_prefix( config.host, config.port, prefix) + '/' + identifier + '-deg/' + path logging.info("Redirection to degraded: %s" % degraded_uri) response = redirect(degraded_uri) response.headers['Access-control-allow-origin'] = '*' return response
Handler for IIIF Image Requests. Behaviour for case of a non-authn or non-authz case is to return 403.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L408-L431
zimeon/iiif
iiif/flask_utils.py
parse_accept_header
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/> """ 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(value) else: media_params.append((key, value)) result.append((media_type, tuple(media_params), q)) result.sort(key=lambda x: -x[2]) return result
python
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/> """ 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(value) else: media_params.append((key, value)) result.append((media_type, tuple(media_params), q)) result.sort(key=lambda x: -x[2]) return result
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/>
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L450-L472
zimeon/iiif
iiif/flask_utils.py
parse_authorization_header
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> <http://bugs.python.org/file34041/0001-Add-an-authorization-header-to-the-initial-request.patch> """ 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 (username, password) = decoded.split(':', 1) except (ValueError, TypeError): # py3, py2 return return {'type': 'basic', 'username': username, 'password': password} elif (auth_type == 'digest'): try: auth_map = parse_keqv_list(parse_http_list(auth_info)) except ValueError: return logging.debug(auth_map) for key in 'username', 'realm', 'nonce', 'uri', 'response': if key not in auth_map: return if 'qop' in auth_map and ('nc' not in auth_map or 'cnonce' not in auth_map): return auth_map['type'] = 'digest' return auth_map else: # unknown auth type return
python
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> <http://bugs.python.org/file34041/0001-Add-an-authorization-header-to-the-initial-request.patch> """ 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 (username, password) = decoded.split(':', 1) except (ValueError, TypeError): # py3, py2 return return {'type': 'basic', 'username': username, 'password': password} elif (auth_type == 'digest'): try: auth_map = parse_keqv_list(parse_http_list(auth_info)) except ValueError: return logging.debug(auth_map) for key in 'username', 'realm', 'nonce', 'uri', 'response': if key not in auth_map: return if 'qop' in auth_map and ('nc' not in auth_map or 'cnonce' not in auth_map): return auth_map['type'] = 'digest' return auth_map else: # unknown auth type return
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> <http://bugs.python.org/file34041/0001-Add-an-authorization-header-to-the-initial-request.patch>
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L475-L513
zimeon/iiif
iiif/flask_utils.py
do_conneg
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 """ for result in parse_accept_header(accept): mime_type = result[0] if (mime_type in supported): return mime_type return None
python
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 """ for result in parse_accept_header(accept): mime_type = result[0] if (mime_type in supported): return mime_type return None
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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L516-L532
zimeon/iiif
iiif/flask_utils.py
setup_auth_paths
def setup_auth_paths(app, auth, prefix, params): """Add URL rules for auth paths.""" 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 (auth.client_id_handler): app.add_url_rule(base + 'client', prefix + 'client_id_handler', auth.client_id_handler, defaults=params) app.add_url_rule(base + 'token', prefix + 'access_token_handler', auth.access_token_handler, defaults=params) if (auth.home_handler): app.add_url_rule(base + 'home', prefix + 'home_handler', auth.home_handler, defaults=params)
python
def setup_auth_paths(app, auth, prefix, params): """Add URL rules for auth paths.""" 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 (auth.client_id_handler): app.add_url_rule(base + 'client', prefix + 'client_id_handler', auth.client_id_handler, defaults=params) app.add_url_rule(base + 'token', prefix + 'access_token_handler', auth.access_token_handler, defaults=params) if (auth.home_handler): app.add_url_rule(base + 'home', prefix + 'home_handler', auth.home_handler, defaults=params)
Add URL rules for auth paths.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L537-L551
zimeon/iiif
iiif/flask_utils.py
make_prefix
def make_prefix(api_version, manipulator, auth_type): """Make prefix string based on configuration parameters.""" prefix = "%s_%s" % (api_version, manipulator) if (auth_type and auth_type != 'none'): prefix += '_' + auth_type return prefix
python
def make_prefix(api_version, manipulator, auth_type): """Make prefix string based on configuration parameters.""" prefix = "%s_%s" % (api_version, manipulator) if (auth_type and auth_type != 'none'): prefix += '_' + auth_type return prefix
Make prefix string based on configuration parameters.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L554-L559
zimeon/iiif
iiif/flask_utils.py
split_comma_argument
def split_comma_argument(comma_sep_str): """Split a comma separated option into a list.""" terms = [] for term in comma_sep_str.split(','): if term: terms.append(term) return terms
python
def split_comma_argument(comma_sep_str): """Split a comma separated option into a list.""" terms = [] for term in comma_sep_str.split(','): if term: terms.append(term) return terms
Split a comma separated option into a list.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L562-L568
zimeon/iiif
iiif/flask_utils.py
add_shared_configs
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. """ 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 also specify --app-port)") p.add('--app-port', type=int, default=None, help="Local application port for reverse proxy deployment, " "as opposed to service --port (must also specify --app-host)") p.add('--image-dir', '-d', default=os.path.join(base_dir, 'testimages'), help="Image file directory") p.add('--generator-dir', default=os.path.join(base_dir, 'iiif/generators'), help="Generator directory for manipulator='gen'") p.add('--tile-height', type=int, default=512, help="Tile height") p.add('--tile-width', type=int, default=512, help="Tile width") p.add('--gauth-client-secret', default=os.path.join(base_dir, 'client_secret.json'), help="Name of file with Google auth client secret") p.add('--include-osd', action='store_true', help="Include a page with OpenSeadragon for each source") p.add('--access-cookie-lifetime', type=int, default=3600, help="Set access cookie lifetime for authenticated access in seconds") p.add('--access-token-lifetime', type=int, default=10, help="Set access token lifetime for authenticated access in seconds") p.add('--config', is_config_file=True, default=None, help='Read config from given file path') p.add('--debug', action='store_true', help="Set debug mode for web application. INSECURE!") p.add('--verbose', '-v', action='store_true', help="Be verbose") p.add('--quiet', '-q', action='store_true', help="Minimal output only")
python
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. """ 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 also specify --app-port)") p.add('--app-port', type=int, default=None, help="Local application port for reverse proxy deployment, " "as opposed to service --port (must also specify --app-host)") p.add('--image-dir', '-d', default=os.path.join(base_dir, 'testimages'), help="Image file directory") p.add('--generator-dir', default=os.path.join(base_dir, 'iiif/generators'), help="Generator directory for manipulator='gen'") p.add('--tile-height', type=int, default=512, help="Tile height") p.add('--tile-width', type=int, default=512, help="Tile width") p.add('--gauth-client-secret', default=os.path.join(base_dir, 'client_secret.json'), help="Name of file with Google auth client secret") p.add('--include-osd', action='store_true', help="Include a page with OpenSeadragon for each source") p.add('--access-cookie-lifetime', type=int, default=3600, help="Set access cookie lifetime for authenticated access in seconds") p.add('--access-token-lifetime', type=int, default=10, help="Set access token lifetime for authenticated access in seconds") p.add('--config', is_config_file=True, default=None, help='Read config from given file path') p.add('--debug', action='store_true', help="Set debug mode for web application. INSECURE!") p.add('--verbose', '-v', action='store_true', help="Be verbose") p.add('--quiet', '-q', action='store_true', help="Minimal output only")
Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L571-L611
zimeon/iiif
iiif/flask_utils.py
add_handler
def add_handler(app, config): """Add a single handler to the app. Adds one IIIF Image API handler to app, with config from config. Arguments: app - Flask app config - Configuration object in which: config.prefix - String path prefix for this handler config.client_prefix - String path prefix seen by client (which may be different because of reverse proxy or such config.klass_name - Manipulator class, e.g. 'pil' config.api_version - e.g. '2.1' config.include_osd - True or False to include OSD config.gauth_client_secret_file - filename if auth_type='gauth' config.access_cookie_lifetime - number of seconds config.access_token_lifetime - number of seconds config.auth_type - Auth type string or 'none' Returns True on success, nothing otherwise. """ auth = None if (config.auth_type is None or config.auth_type == 'none'): pass elif (config.auth_type == 'gauth'): from iiif.auth_google import IIIFAuthGoogle auth = IIIFAuthGoogle(client_secret_file=config.gauth_client_secret_file) elif (config.auth_type == 'basic'): from iiif.auth_basic import IIIFAuthBasic auth = IIIFAuthBasic() elif (config.auth_type == 'clickthrough'): from iiif.auth_clickthrough import IIIFAuthClickthrough auth = IIIFAuthClickthrough() elif (config.auth_type == 'kiosk'): from iiif.auth_kiosk import IIIFAuthKiosk auth = IIIFAuthKiosk() elif (config.auth_type == 'external'): from iiif.auth_external import IIIFAuthExternal auth = IIIFAuthExternal() else: logging.error("Unknown auth type %s, ignoring" % (config.auth_type)) return if (auth is not None): auth.access_cookie_lifetime = config.access_cookie_lifetime auth.access_token_lifetime = config.access_token_lifetime klass = None if (config.klass_name == 'pil'): from iiif.manipulator_pil import IIIFManipulatorPIL klass = IIIFManipulatorPIL elif (config.klass_name == 'netpbm'): from iiif.manipulator_netpbm import IIIFManipulatorNetpbm klass = IIIFManipulatorNetpbm elif (config.klass_name == 'dummy'): from iiif.manipulator import IIIFManipulator klass = IIIFManipulator elif (config.klass_name == 'gen'): from iiif.manipulator_gen import IIIFManipulatorGen klass = IIIFManipulatorGen else: logging.error("Unknown manipulator type %s, ignoring" % (config.klass_name)) return base = urljoin('/', config.prefix + '/') # ensure has trailing slash client_base = urljoin('/', config.client_prefix + '/') # ensure has trailing slash logging.warning("Installing %s IIIFManipulator at %s v%s %s" % (config.klass_name, base, config.api_version, config.auth_type)) params = dict(config=config, klass=klass, auth=auth, prefix=config.client_prefix) app.add_url_rule(base.rstrip('/'), 'prefix_index_page', prefix_index_page, defaults={'config': config}) app.add_url_rule(base, 'prefix_index_page', prefix_index_page, defaults={'config': config}) app.add_url_rule(base + '<string(minlength=1):identifier>/info.json', 'options_handler', options_handler, methods=['OPTIONS']) app.add_url_rule(base + '<string(minlength=1):identifier>/info.json', 'iiif_info_handler', iiif_info_handler, methods=['GET'], defaults=params) if (config.include_osd): app.add_url_rule(base + '<string(minlength=1):identifier>/osd.html', 'osd_page_handler', osd_page_handler, methods=['GET'], defaults=params) app.add_url_rule(base + '<string(minlength=1):identifier>/<path:path>', 'iiif_image_handler', iiif_image_handler, methods=['GET'], defaults=params) if (auth): setup_auth_paths(app, auth, config.client_prefix, params) # redirects to info.json must come after auth app.add_url_rule(base + '<string(minlength=1):identifier>', 'iiif_info_handler', redirect_to=client_base + '<identifier>/info.json') app.add_url_rule(base + '<string(minlength=1):identifier>/', 'iiif_info_handler', redirect_to=client_base + '<identifier>/info.json') return True
python
def add_handler(app, config): """Add a single handler to the app. Adds one IIIF Image API handler to app, with config from config. Arguments: app - Flask app config - Configuration object in which: config.prefix - String path prefix for this handler config.client_prefix - String path prefix seen by client (which may be different because of reverse proxy or such config.klass_name - Manipulator class, e.g. 'pil' config.api_version - e.g. '2.1' config.include_osd - True or False to include OSD config.gauth_client_secret_file - filename if auth_type='gauth' config.access_cookie_lifetime - number of seconds config.access_token_lifetime - number of seconds config.auth_type - Auth type string or 'none' Returns True on success, nothing otherwise. """ auth = None if (config.auth_type is None or config.auth_type == 'none'): pass elif (config.auth_type == 'gauth'): from iiif.auth_google import IIIFAuthGoogle auth = IIIFAuthGoogle(client_secret_file=config.gauth_client_secret_file) elif (config.auth_type == 'basic'): from iiif.auth_basic import IIIFAuthBasic auth = IIIFAuthBasic() elif (config.auth_type == 'clickthrough'): from iiif.auth_clickthrough import IIIFAuthClickthrough auth = IIIFAuthClickthrough() elif (config.auth_type == 'kiosk'): from iiif.auth_kiosk import IIIFAuthKiosk auth = IIIFAuthKiosk() elif (config.auth_type == 'external'): from iiif.auth_external import IIIFAuthExternal auth = IIIFAuthExternal() else: logging.error("Unknown auth type %s, ignoring" % (config.auth_type)) return if (auth is not None): auth.access_cookie_lifetime = config.access_cookie_lifetime auth.access_token_lifetime = config.access_token_lifetime klass = None if (config.klass_name == 'pil'): from iiif.manipulator_pil import IIIFManipulatorPIL klass = IIIFManipulatorPIL elif (config.klass_name == 'netpbm'): from iiif.manipulator_netpbm import IIIFManipulatorNetpbm klass = IIIFManipulatorNetpbm elif (config.klass_name == 'dummy'): from iiif.manipulator import IIIFManipulator klass = IIIFManipulator elif (config.klass_name == 'gen'): from iiif.manipulator_gen import IIIFManipulatorGen klass = IIIFManipulatorGen else: logging.error("Unknown manipulator type %s, ignoring" % (config.klass_name)) return base = urljoin('/', config.prefix + '/') # ensure has trailing slash client_base = urljoin('/', config.client_prefix + '/') # ensure has trailing slash logging.warning("Installing %s IIIFManipulator at %s v%s %s" % (config.klass_name, base, config.api_version, config.auth_type)) params = dict(config=config, klass=klass, auth=auth, prefix=config.client_prefix) app.add_url_rule(base.rstrip('/'), 'prefix_index_page', prefix_index_page, defaults={'config': config}) app.add_url_rule(base, 'prefix_index_page', prefix_index_page, defaults={'config': config}) app.add_url_rule(base + '<string(minlength=1):identifier>/info.json', 'options_handler', options_handler, methods=['OPTIONS']) app.add_url_rule(base + '<string(minlength=1):identifier>/info.json', 'iiif_info_handler', iiif_info_handler, methods=['GET'], defaults=params) if (config.include_osd): app.add_url_rule(base + '<string(minlength=1):identifier>/osd.html', 'osd_page_handler', osd_page_handler, methods=['GET'], defaults=params) app.add_url_rule(base + '<string(minlength=1):identifier>/<path:path>', 'iiif_image_handler', iiif_image_handler, methods=['GET'], defaults=params) if (auth): setup_auth_paths(app, auth, config.client_prefix, params) # redirects to info.json must come after auth app.add_url_rule(base + '<string(minlength=1):identifier>', 'iiif_info_handler', redirect_to=client_base + '<identifier>/info.json') app.add_url_rule(base + '<string(minlength=1):identifier>/', 'iiif_info_handler', redirect_to=client_base + '<identifier>/info.json') return True
Add a single handler to the app. Adds one IIIF Image API handler to app, with config from config. Arguments: app - Flask app config - Configuration object in which: config.prefix - String path prefix for this handler config.client_prefix - String path prefix seen by client (which may be different because of reverse proxy or such config.klass_name - Manipulator class, e.g. 'pil' config.api_version - e.g. '2.1' config.include_osd - True or False to include OSD config.gauth_client_secret_file - filename if auth_type='gauth' config.access_cookie_lifetime - number of seconds config.access_token_lifetime - number of seconds config.auth_type - Auth type string or 'none' Returns True on success, nothing otherwise.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L614-L702
zimeon/iiif
iiif/flask_utils.py
serve_static
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. """ if not basedir: basedir = os.path.join(os.path.dirname(__file__), 'third_party') return send_from_directory(os.path.join(basedir, prefix), filename)
python
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. """ if not basedir: basedir = os.path.join(os.path.dirname(__file__), 'third_party') return send_from_directory(os.path.join(basedir, prefix), filename)
Handler for static files: server filename in basedir/prefix. If not specified then basedir defaults to the local third_party directory.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L705-L713
zimeon/iiif
iiif/flask_utils.py
write_pid_file
def write_pid_file(): """Write a file with the PID of this server instance. Call when setting up a command line testserver. """ 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()
python
def write_pid_file(): """Write a file with the PID of this server instance. Call when setting up a command line testserver. """ 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()
Write a file with the PID of this server instance. Call when setting up a command line testserver.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L739-L747
zimeon/iiif
iiif/flask_utils.py
setup_app
def setup_app(app, cfg): """Setup Flask app and handle reverse proxy setup if configured. Arguments: app - Flask application cfg - configuration data """ # 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 = ReverseProxied(app.wsgi_app, cfg.host) elif (cfg.app_host or cfg.app_port): logging.critical("Must specify both app-host and app-port for reverse proxy configuration, aborting") sys.exit(1) else: cfg.app_host = cfg.host cfg.app_port = cfg.port logging.warning("Setup server on http://%s:%d/ ..." % (cfg.app_host, cfg.app_port)) return(app)
python
def setup_app(app, cfg): """Setup Flask app and handle reverse proxy setup if configured. Arguments: app - Flask application cfg - configuration data """ # 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 = ReverseProxied(app.wsgi_app, cfg.host) elif (cfg.app_host or cfg.app_port): logging.critical("Must specify both app-host and app-port for reverse proxy configuration, aborting") sys.exit(1) else: cfg.app_host = cfg.host cfg.app_port = cfg.port logging.warning("Setup server on http://%s:%d/ ..." % (cfg.app_host, cfg.app_port)) return(app)
Setup Flask app and handle reverse proxy setup if configured. Arguments: app - Flask application cfg - configuration data
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L750-L770
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.server_and_prefix
def server_and_prefix(self): """Server and prefix from config.""" return(host_port_prefix(self.config.host, self.config.port, self.prefix))
python
def server_and_prefix(self): """Server and prefix from config.""" return(host_port_prefix(self.config.host, self.config.port, self.prefix))
Server and prefix from config.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L231-L233
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.json_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 """ 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
python
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 """ 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
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
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L236-L247
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.file
def file(self): """Filename property for the source image for the current identifier.""" 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 ext in ['.jpg', '.png', '.tif']: file = os.path.join(self.config.image_dir, self.identifier + ext) if (os.path.isfile(file)): return file # failed, show list of available identifiers as error available = "\n ".join(identifiers(self.config)) raise IIIFError(code=404, parameter="identifier", text="Image resource '" + self.identifier + "' not found. Local resources available:" + available + "\n")
python
def file(self): """Filename property for the source image for the current identifier.""" 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 ext in ['.jpg', '.png', '.tif']: file = os.path.join(self.config.image_dir, self.identifier + ext) if (os.path.isfile(file)): return file # failed, show list of available identifiers as error available = "\n ".join(identifiers(self.config)) raise IIIFError(code=404, parameter="identifier", text="Image resource '" + self.identifier + "' not found. Local resources available:" + available + "\n")
Filename property for the source image for the current identifier.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L250-L268
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.add_compliance_header
def add_compliance_header(self): """Add IIIF Compliance level header to response.""" if (self.manipulator.compliance_uri is not None): self.headers['Link'] = '<' + \ self.manipulator.compliance_uri + '>;rel="profile"'
python
def add_compliance_header(self): """Add IIIF Compliance level header to response.""" if (self.manipulator.compliance_uri is not None): self.headers['Link'] = '<' + \ self.manipulator.compliance_uri + '>;rel="profile"'
Add IIIF Compliance level header to response.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L270-L274
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.make_response
def make_response(self, content, code=200, headers=None): """Wrapper around Flask.make_response which also adds any local headers.""" if headers: for header in headers: self.headers[header] = headers[header] return make_response(content, code, self.headers)
python
def make_response(self, content, code=200, headers=None): """Wrapper around Flask.make_response which also adds any local headers.""" if headers: for header in headers: self.headers[header] = headers[header] return make_response(content, code, self.headers)
Wrapper around Flask.make_response which also adds any local headers.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L276-L281
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.image_information_response
def image_information_response(self): """Parse image information request and create response.""" 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("image_information: %s" % (self.identifier)) # get size self.manipulator.srcfile = self.file self.manipulator.do_first() # most of info.json comes from config, a few things specific to image info = {'tile_height': self.config.tile_height, 'tile_width': self.config.tile_width, 'scale_factors': self.config.scale_factors } # calculate scale factors if not hard-coded if ('auto' in self.config.scale_factors): info['scale_factors'] = self.manipulator.scale_factors( self.config.tile_width, self.config.tile_height) i = IIIFInfo(conf=info, api_version=self.api_version) i.server_and_prefix = self.server_and_prefix i.identifier = self.iiif.identifier i.width = self.manipulator.width i.height = self.manipulator.height if (self.api_version >= '2.0'): # FIXME - should come from manipulator i.qualities = ["default", "color", "gray"] else: # FIXME - should come from manipulator i.qualities = ["native", "color", "gray"] i.formats = ["jpg", "png"] # FIXME - should come from manipulator if (self.auth): self.auth.add_services(i) return self.make_response(i.as_json(), headers={"Content-Type": self.json_mime_type})
python
def image_information_response(self): """Parse image information request and create response.""" 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("image_information: %s" % (self.identifier)) # get size self.manipulator.srcfile = self.file self.manipulator.do_first() # most of info.json comes from config, a few things specific to image info = {'tile_height': self.config.tile_height, 'tile_width': self.config.tile_width, 'scale_factors': self.config.scale_factors } # calculate scale factors if not hard-coded if ('auto' in self.config.scale_factors): info['scale_factors'] = self.manipulator.scale_factors( self.config.tile_width, self.config.tile_height) i = IIIFInfo(conf=info, api_version=self.api_version) i.server_and_prefix = self.server_and_prefix i.identifier = self.iiif.identifier i.width = self.manipulator.width i.height = self.manipulator.height if (self.api_version >= '2.0'): # FIXME - should come from manipulator i.qualities = ["default", "color", "gray"] else: # FIXME - should come from manipulator i.qualities = ["native", "color", "gray"] i.formats = ["jpg", "png"] # FIXME - should come from manipulator if (self.auth): self.auth.add_services(i) return self.make_response(i.as_json(), headers={"Content-Type": self.json_mime_type})
Parse image information request and create response.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L283-L320
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.image_request_response
def image_request_response(self, path): """Parse image request and create response.""" # 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 IIIFRequestPathError as e: # Reraise as IIIFError with code=404 because we can't tell # whether there was an encoded slash in the identifier or # whether there was a bad number of path segments. raise IIIFError(code=404, text=e.text) except IIIFError as e: # Pass through raise e except Exception as e: # Something completely unexpected => 500 raise IIIFError(code=500, text="Internal Server Error: unexpected exception parsing request (" + str(e) + ")") dr = degraded_request(self.identifier) if (dr): self.logger.info("image_request: degraded %s -> %s" % (self.identifier, dr)) self.degraded = self.identifier self.identifier = dr self.iiif.quality = 'gray' else: # Parsed request OK, attempt to fulfill self.logger.info("image_request: %s" % (self.identifier)) file = self.file self.manipulator.srcfile = file self.manipulator.do_first() if (self.api_version < '2.0' and self.iiif.format is None and 'Accept' in request.headers): # In 1.0 and 1.1 conneg was specified as an alternative to format, see: # http://iiif.io/api/image/1.0/#format # http://iiif.io/api/image/1.1/#parameters-format formats = {'image/jpeg': 'jpg', 'image/tiff': 'tif', 'image/png': 'png', 'image/gif': 'gif', 'image/jp2': 'jps', 'application/pdf': 'pdf'} accept = do_conneg(request.headers['Accept'], list(formats.keys())) # Ignore Accept header if not recognized, should this be an error # instead? if (accept in formats): self.iiif.format = formats[accept] (outfile, mime_type) = self.manipulator.derive(file, self.iiif) # FIXME - find efficient way to serve file with headers self.add_compliance_header() return send_file(outfile, mimetype=mime_type)
python
def image_request_response(self, path): """Parse image request and create response.""" # 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 IIIFRequestPathError as e: # Reraise as IIIFError with code=404 because we can't tell # whether there was an encoded slash in the identifier or # whether there was a bad number of path segments. raise IIIFError(code=404, text=e.text) except IIIFError as e: # Pass through raise e except Exception as e: # Something completely unexpected => 500 raise IIIFError(code=500, text="Internal Server Error: unexpected exception parsing request (" + str(e) + ")") dr = degraded_request(self.identifier) if (dr): self.logger.info("image_request: degraded %s -> %s" % (self.identifier, dr)) self.degraded = self.identifier self.identifier = dr self.iiif.quality = 'gray' else: # Parsed request OK, attempt to fulfill self.logger.info("image_request: %s" % (self.identifier)) file = self.file self.manipulator.srcfile = file self.manipulator.do_first() if (self.api_version < '2.0' and self.iiif.format is None and 'Accept' in request.headers): # In 1.0 and 1.1 conneg was specified as an alternative to format, see: # http://iiif.io/api/image/1.0/#format # http://iiif.io/api/image/1.1/#parameters-format formats = {'image/jpeg': 'jpg', 'image/tiff': 'tif', 'image/png': 'png', 'image/gif': 'gif', 'image/jp2': 'jps', 'application/pdf': 'pdf'} accept = do_conneg(request.headers['Accept'], list(formats.keys())) # Ignore Accept header if not recognized, should this be an error # instead? if (accept in formats): self.iiif.format = formats[accept] (outfile, mime_type) = self.manipulator.derive(file, self.iiif) # FIXME - find efficient way to serve file with headers self.add_compliance_header() return send_file(outfile, mimetype=mime_type)
Parse image request and create response.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L322-L373
zimeon/iiif
iiif/flask_utils.py
IIIFHandler.error_response
def error_response(self, e): """Make response for an IIIFError e. Also add compliance header. """ self.add_compliance_header() return self.make_response(*e.image_server_response(self.api_version))
python
def error_response(self, e): """Make response for an IIIFError e. Also add compliance header. """ self.add_compliance_header() return self.make_response(*e.image_server_response(self.api_version))
Make response for an IIIFError e. Also add compliance header.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L375-L381
zimeon/iiif
iiif_cgi.py
IIIFRequestHandler.error_response
def error_response(self, code, content=''): """Construct and send error response.""" self.send_response(code) self.send_header('Content-Type', 'text/xml') self.add_compliance_header() self.end_headers() self.wfile.write(content)
python
def error_response(self, code, content=''): """Construct and send error response.""" self.send_response(code) self.send_header('Content-Type', 'text/xml') self.add_compliance_header() self.end_headers() self.wfile.write(content)
Construct and send error response.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif_cgi.py#L64-L70
zimeon/iiif
iiif_cgi.py
IIIFRequestHandler.do_GET
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). """ 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 is not None): self.send_header('Content-Type', mime_type) self.add_compliance_header() self.end_headers() while (1): buffer = of.read(8192) if (not buffer): break self.wfile.write(buffer) # Now cleanup self.manipulator.cleanup() except IIIFError as e: if (self.debug): e.text += "\nRequest parameters:\n" + str(self.iiif) self.error_response(e.code, str(e)) except Exception as ue: # Anything else becomes a 500 Internal Server Error e = IIIFError(code=500, text="Something went wrong... %s ---- %s.\n" % (str(ue), traceback.format_exc())) if (self.debug): e.text += "\nRequest parameters:\n" + str(self.iiif) self.error_response(e.code, str(e))
python
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). """ 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 is not None): self.send_header('Content-Type', mime_type) self.add_compliance_header() self.end_headers() while (1): buffer = of.read(8192) if (not buffer): break self.wfile.write(buffer) # Now cleanup self.manipulator.cleanup() except IIIFError as e: if (self.debug): e.text += "\nRequest parameters:\n" + str(self.iiif) self.error_response(e.code, str(e)) except Exception as ue: # Anything else becomes a 500 Internal Server Error e = IIIFError(code=500, text="Something went wrong... %s ---- %s.\n" % (str(ue), traceback.format_exc())) if (self.debug): e.text += "\nRequest parameters:\n" + str(self.iiif) self.error_response(e.code, str(e))
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).
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif_cgi.py#L78-L113
zimeon/iiif
iiif_cgi.py
IIIFRequestHandler.do_GET_body
def do_GET_body(self): """Create body of GET.""" 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('/') sys.stderr.write("path = %s" % (self.path)) iiif.parse_url(self.path) except Exception as e: # Something completely unexpected => 500 raise IIIFError(code=500, text="Internal Server Error: unexpected exception parsing request (" + str(e) + ")") # Now we have a full iiif request if (re.match('[\w\.\-]+$', iiif.identifier)): file = os.path.join(TESTIMAGE_DIR, iiif.identifier) if (not os.path.isfile(file)): images_available = "" for image_file in os.listdir(TESTIMAGE_DIR): if (os.path.isfile(os.path.join(TESTIMAGE_DIR, image_file))): images_available += " " + image_file + "\n" raise IIIFError(code=404, parameter="identifier", text="Image resource '" + iiif.identifier + "' not found. Local image files available:\n" + images_available) else: raise IIIFError(code=404, parameter="identifier", text="Image resource '" + iiif.identifier + "' not found. Only local test images and http: URIs for images are supported.\n") # Now know image is OK manipulator = IIIFRequestHandler.manipulator_class() # Stash manipulator object so we can cleanup after reading file self.manipulator = manipulator self.compliance_uri = manipulator.compliance_uri if (iiif.info): # get size manipulator.srcfile = file manipulator.do_first() # most of info.json comes from config, a few things # specific to image i = IIIFInfo() i.identifier = self.iiif.identifier i.width = manipulator.width i.height = manipulator.height import io return(io.StringIO(i.as_json()), "application/json") else: (outfile, mime_type) = manipulator.derive(file, iiif) return(open(outfile, 'r'), mime_type)
python
def do_GET_body(self): """Create body of GET.""" 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('/') sys.stderr.write("path = %s" % (self.path)) iiif.parse_url(self.path) except Exception as e: # Something completely unexpected => 500 raise IIIFError(code=500, text="Internal Server Error: unexpected exception parsing request (" + str(e) + ")") # Now we have a full iiif request if (re.match('[\w\.\-]+$', iiif.identifier)): file = os.path.join(TESTIMAGE_DIR, iiif.identifier) if (not os.path.isfile(file)): images_available = "" for image_file in os.listdir(TESTIMAGE_DIR): if (os.path.isfile(os.path.join(TESTIMAGE_DIR, image_file))): images_available += " " + image_file + "\n" raise IIIFError(code=404, parameter="identifier", text="Image resource '" + iiif.identifier + "' not found. Local image files available:\n" + images_available) else: raise IIIFError(code=404, parameter="identifier", text="Image resource '" + iiif.identifier + "' not found. Only local test images and http: URIs for images are supported.\n") # Now know image is OK manipulator = IIIFRequestHandler.manipulator_class() # Stash manipulator object so we can cleanup after reading file self.manipulator = manipulator self.compliance_uri = manipulator.compliance_uri if (iiif.info): # get size manipulator.srcfile = file manipulator.do_first() # most of info.json comes from config, a few things # specific to image i = IIIFInfo() i.identifier = self.iiif.identifier i.width = manipulator.width i.height = manipulator.height import io return(io.StringIO(i.as_json()), "application/json") else: (outfile, mime_type) = manipulator.derive(file, iiif) return(open(outfile, 'r'), mime_type)
Create body of GET.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif_cgi.py#L115-L162
zimeon/iiif
iiif/auth.py
IIIFAuth.set_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. """ if (cookie_prefix is None): self.cookie_prefix = "%06d_" % int(random.random() * 1000000) else: self.cookie_prefix = cookie_prefix
python
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. """ if (cookie_prefix is None): self.cookie_prefix = "%06d_" % int(random.random() * 1000000) else: self.cookie_prefix = cookie_prefix
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L41-L52
zimeon/iiif
iiif/auth.py
IIIFAuth.add_services
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 in the authorized and unauthorized cases (although in the data could be different). """ 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()) if (self.access_token_uri): svcs.append(self.access_token_service_description()) # Add one as direct child of service property, else array for >1 if (len(svcs) == 1): svc['service'] = svcs[0] elif (len(svcs) > 1): svc['service'] = svcs info.add_service(svc)
python
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 in the authorized and unauthorized cases (although in the data could be different). """ 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()) if (self.access_token_uri): svcs.append(self.access_token_service_description()) # Add one as direct child of service property, else array for >1 if (len(svcs) == 1): svc['service'] = svcs[0] elif (len(svcs) > 1): svc['service'] = svcs info.add_service(svc)
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 in the authorized and unauthorized cases (although in the data could be different).
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L54-L80
zimeon/iiif
iiif/auth.py
IIIFAuth.login_service_description
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. """ 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['header'] = self.header if (self.description): desc['description'] = self.description return desc
python
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. """ 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['header'] = self.header if (self.description): desc['description'] = self.description return desc
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L82-L99
zimeon/iiif
iiif/auth.py
IIIFAuth.logout_service_description
def logout_service_description(self): """Logout service description.""" 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})
python
def logout_service_description(self): """Logout service description.""" 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})
Logout service description.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L101-L108
zimeon/iiif
iiif/auth.py
IIIFAuth.access_token_response
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. """ if (token): data = {"accessToken": token, "expiresIn": self.access_token_lifetime} if (message_id): data['messageId'] = message_id else: data = {"error": "client_unauthorized", "description": "No authorization details received"} return data
python
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. """ if (token): data = {"accessToken": token, "expiresIn": self.access_token_lifetime} if (message_id): data['messageId'] = message_id else: data = {"error": "client_unauthorized", "description": "No authorization details received"} return data
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.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L123-L138
zimeon/iiif
iiif/auth.py
IIIFAuth.scheme_host_port_prefix
def scheme_host_port_prefix(self, scheme='http', host='host', port=None, prefix=None): """Return URI composed of scheme, server, port, and prefix.""" 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
python
def scheme_host_port_prefix(self, scheme='http', host='host', port=None, prefix=None): """Return URI composed of scheme, server, port, and prefix.""" 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
Return URI composed of scheme, server, port, and prefix.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L178-L187
zimeon/iiif
iiif/auth.py
IIIFAuth._generate_random_string
def _generate_random_string(self, container, length=20): """Generate a random cookie or token string not in container. The cookie or token should be secure in the sense that it should not be likely to be able guess a value. Because it is not derived from anything else, there is no vulnerability of the token from computation, or possible leakage of information from the token. """ while True: s = ''.join([random.SystemRandom().choice(string.digits + string.ascii_letters) for n in range(length)]) if (s not in container): break return s
python
def _generate_random_string(self, container, length=20): """Generate a random cookie or token string not in container. The cookie or token should be secure in the sense that it should not be likely to be able guess a value. Because it is not derived from anything else, there is no vulnerability of the token from computation, or possible leakage of information from the token. """ while True: s = ''.join([random.SystemRandom().choice(string.digits + string.ascii_letters) for n in range(length)]) if (s not in container): break return s
Generate a random cookie or token string not in container. The cookie or token should be secure in the sense that it should not be likely to be able guess a value. Because it is not derived from anything else, there is no vulnerability of the token from computation, or possible leakage of information from the token.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L189-L202
zimeon/iiif
iiif/auth.py
IIIFAuth.access_cookie
def access_cookie(self, account): """Make and store access cookie for a given account. If account is allowed then make a cookie and add it to the dict of accepted access cookies with current timestamp as the value. Return the access cookie. Otherwise return None. """ if (self.account_allowed(account)): cookie = self._generate_random_string(self.access_cookies) self.access_cookies[cookie] = int(time.time()) return cookie else: return None
python
def access_cookie(self, account): """Make and store access cookie for a given account. If account is allowed then make a cookie and add it to the dict of accepted access cookies with current timestamp as the value. Return the access cookie. Otherwise return None. """ if (self.account_allowed(account)): cookie = self._generate_random_string(self.access_cookies) self.access_cookies[cookie] = int(time.time()) return cookie else: return None
Make and store access cookie for a given account. If account is allowed then make a cookie and add it to the dict of accepted access cookies with current timestamp as the value. Return the access cookie. Otherwise return None.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L213-L227
zimeon/iiif
iiif/auth.py
IIIFAuth.access_cookie_valid
def access_cookie_valid(self, cookie, log_msg): """Check access cookie validity. Returns true if the access cookie is valid. The set of allowed access cookies is stored in self.access_cookies. Uses log_msg as prefix to info level log message of accetance or rejection. """ if (cookie in self.access_cookies): age = int(time.time()) - self.access_cookies[cookie] if (age <= (self.access_cookie_lifetime + 1)): self.logger.info(log_msg + " " + cookie + " ACCEPTED COOKIE (%ds old)" % age) return True # Expired... self.logger.info(log_msg + " " + cookie + " EXPIRED COOKIE (%ds old > %ds)" % (age, self.access_cookie_lifetime)) # Keep cookie for 2x lifetim in order to generate # helpful expired message if (age > (self.access_cookie_lifetime * 2)): del self.access_cookies[cookie] return False else: self.logger.info(log_msg + " " + cookie + " REJECTED COOKIE") return False
python
def access_cookie_valid(self, cookie, log_msg): """Check access cookie validity. Returns true if the access cookie is valid. The set of allowed access cookies is stored in self.access_cookies. Uses log_msg as prefix to info level log message of accetance or rejection. """ if (cookie in self.access_cookies): age = int(time.time()) - self.access_cookies[cookie] if (age <= (self.access_cookie_lifetime + 1)): self.logger.info(log_msg + " " + cookie + " ACCEPTED COOKIE (%ds old)" % age) return True # Expired... self.logger.info(log_msg + " " + cookie + " EXPIRED COOKIE (%ds old > %ds)" % (age, self.access_cookie_lifetime)) # Keep cookie for 2x lifetim in order to generate # helpful expired message if (age > (self.access_cookie_lifetime * 2)): del self.access_cookies[cookie] return False else: self.logger.info(log_msg + " " + cookie + " REJECTED COOKIE") return False
Check access cookie validity. Returns true if the access cookie is valid. The set of allowed access cookies is stored in self.access_cookies. Uses log_msg as prefix to info level log message of accetance or rejection.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L229-L255
zimeon/iiif
iiif/auth.py
IIIFAuth.access_token
def access_token(self, cookie): """Make and store access token as proxy for the access cookie. Create an access token to act as a proxy for access cookie, add it to the dict of accepted access tokens with (cookie, current timestamp) as the value. Return the access token. Return None if cookie is not set. """ if (cookie): token = self._generate_random_string(self.access_tokens) self.access_tokens[token] = (cookie, int(time.time())) return token else: return None
python
def access_token(self, cookie): """Make and store access token as proxy for the access cookie. Create an access token to act as a proxy for access cookie, add it to the dict of accepted access tokens with (cookie, current timestamp) as the value. Return the access token. Return None if cookie is not set. """ if (cookie): token = self._generate_random_string(self.access_tokens) self.access_tokens[token] = (cookie, int(time.time())) return token else: return None
Make and store access token as proxy for the access cookie. Create an access token to act as a proxy for access cookie, add it to the dict of accepted access tokens with (cookie, current timestamp) as the value. Return the access token. Return None if cookie is not set.
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L257-L269