id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
233,800 | ContextLab/hypertools | hypertools/_externals/srm.py | DetSRM._objective_function | def _objective_function(self, data, w, s):
"""Calculate the objective function
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
w : list of 2D arrays, element i has shape=[voxels_i, features]
The orthogonal transforms (mappings) :math:`W_i` for each subject.
s : array, shape=[features, samples]
The shared response
Returns
-------
objective : float
The objective function value.
"""
subjects = len(data)
objective = 0.0
for m in range(subjects):
objective += \
np.linalg.norm(data[m] - w[m].dot(s), 'fro')**2
return objective * 0.5 / data[0].shape[1] | python | def _objective_function(self, data, w, s):
subjects = len(data)
objective = 0.0
for m in range(subjects):
objective += \
np.linalg.norm(data[m] - w[m].dot(s), 'fro')**2
return objective * 0.5 / data[0].shape[1] | [
"def",
"_objective_function",
"(",
"self",
",",
"data",
",",
"w",
",",
"s",
")",
":",
"subjects",
"=",
"len",
"(",
"data",
")",
"objective",
"=",
"0.0",
"for",
"m",
"in",
"range",
"(",
"subjects",
")",
":",
"objective",
"+=",
"np",
".",
"linalg",
"... | Calculate the objective function
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
w : list of 2D arrays, element i has shape=[voxels_i, features]
The orthogonal transforms (mappings) :math:`W_i` for each subject.
s : array, shape=[features, samples]
The shared response
Returns
-------
objective : float
The objective function value. | [
"Calculate",
"the",
"objective",
"function"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L557-L584 |
233,801 | ContextLab/hypertools | hypertools/tools/text2mat.py | text2mat | def text2mat(data, vectorizer='CountVectorizer',
semantic='LatentDirichletAllocation', corpus='wiki'):
"""
Turns a list of text samples into a matrix using a vectorizer and a text model
Parameters
----------
data : list (or list of lists) of text samples
The text data to transform
vectorizer : str, dict, class or class instance
The vectorizer to use. Built-in options are 'CountVectorizer' or
'TfidfVectorizer'. To change default parameters, set to a dictionary
e.g. {'model' : 'CountVectorizer', 'params' : {'max_features' : 10}}. See
http://scikit-learn.org/stable/modules/classes.html#module-sklearn.feature_extraction.text
for details. You can also specify your own vectorizer model as a class,
or class instance. With either option, the class must have a
fit_transform method (see here: http://scikit-learn.org/stable/data_transforms.html).
If a class, pass any parameters as a dictionary to vectorizer_params. If
a class instance, no parameters can be passed.
semantic : str, dict, class or class instance
Text model to use to transform text data. Built-in options are
'LatentDirichletAllocation' or 'NMF' (default: LDA). To change default
parameters, set to a dictionary e.g. {'model' : 'NMF', 'params' :
{'n_components' : 10}}. See
http://scikit-learn.org/stable/modules/classes.html#module-sklearn.decomposition
for details on the two model options. You can also specify your own
text model as a class, or class instance. With either option, the class
must have a fit_transform method (see here:
http://scikit-learn.org/stable/data_transforms.html).
If a class, pass any parameters as a dictionary to text_params. If
a class instance, no parameters can be passed.
corpus : list (or list of lists) of text samples or 'wiki', 'nips', 'sotus'.
Text to use to fit the semantic model (optional). If set to 'wiki', 'nips'
or 'sotus' and the default semantic and vectorizer models are used, a
pretrained model will be loaded which can save a lot of time.
Returns
----------
transformed data : list of numpy arrays
The transformed text data
"""
if semantic is None:
semantic = 'LatentDirichletAllocation'
if vectorizer is None:
vectorizer = 'CountVectorizer'
model_is_fit=False
if corpus is not None:
if corpus in ('wiki', 'nips', 'sotus',):
if semantic == 'LatentDirichletAllocation' and vectorizer == 'CountVectorizer':
semantic = load(corpus + '_model')
vectorizer = None
model_is_fit = True
else:
corpus = np.array(load(corpus).get_data())
else:
corpus = np.array([corpus])
vtype = _check_mtype(vectorizer)
if vtype == 'str':
vectorizer_params = default_params(vectorizer)
elif vtype == 'dict':
vectorizer_params = default_params(vectorizer['model'], vectorizer['params'])
vectorizer = vectorizer['model']
elif vtype in ('class', 'class_instance'):
if hasattr(vectorizer, 'fit_transform'):
vectorizer_models.update({'user_model' : vectorizer})
vectorizer = 'user_model'
else:
raise RuntimeError('Error: Vectorizer model must have fit_transform '
'method following the scikit-learn API. See here '
'for more details: '
'http://scikit-learn.org/stable/data_transforms.html')
ttype = _check_mtype(semantic)
if ttype == 'str':
text_params = default_params(semantic)
elif ttype == 'dict':
text_params = default_params(semantic['model'], semantic['params'])
semantic = semantic['model']
elif ttype in ('class', 'class_instance'):
if hasattr(semantic, 'fit_transform'):
texts.update({'user_model' : semantic})
semantic = 'user_model'
else:
raise RuntimeError('Text model must have fit_transform '
'method following the scikit-learn API. See here '
'for more details: '
'http://scikit-learn.org/stable/data_transforms.html')
if vectorizer:
if vtype in ('str', 'dict'):
vmodel = vectorizer_models[vectorizer](**vectorizer_params)
elif vtype == 'class':
vmodel = vectorizer_models[vectorizer]()
elif vtype == 'class_instance':
vmodel = vectorizer_models[vectorizer]
else:
vmodel = None
if semantic:
if ttype in ('str', 'dict'):
tmodel = texts[semantic](**text_params)
elif ttype == 'class':
tmodel = texts[semantic]()
elif ttype == 'class_instance':
tmodel = texts[semantic]
else:
tmodel = None
if not isinstance(data, list):
data = [data]
if corpus is None:
_fit_models(vmodel, tmodel, data, model_is_fit)
else:
_fit_models(vmodel, tmodel, corpus, model_is_fit)
return _transform(vmodel, tmodel, data) | python | def text2mat(data, vectorizer='CountVectorizer',
semantic='LatentDirichletAllocation', corpus='wiki'):
if semantic is None:
semantic = 'LatentDirichletAllocation'
if vectorizer is None:
vectorizer = 'CountVectorizer'
model_is_fit=False
if corpus is not None:
if corpus in ('wiki', 'nips', 'sotus',):
if semantic == 'LatentDirichletAllocation' and vectorizer == 'CountVectorizer':
semantic = load(corpus + '_model')
vectorizer = None
model_is_fit = True
else:
corpus = np.array(load(corpus).get_data())
else:
corpus = np.array([corpus])
vtype = _check_mtype(vectorizer)
if vtype == 'str':
vectorizer_params = default_params(vectorizer)
elif vtype == 'dict':
vectorizer_params = default_params(vectorizer['model'], vectorizer['params'])
vectorizer = vectorizer['model']
elif vtype in ('class', 'class_instance'):
if hasattr(vectorizer, 'fit_transform'):
vectorizer_models.update({'user_model' : vectorizer})
vectorizer = 'user_model'
else:
raise RuntimeError('Error: Vectorizer model must have fit_transform '
'method following the scikit-learn API. See here '
'for more details: '
'http://scikit-learn.org/stable/data_transforms.html')
ttype = _check_mtype(semantic)
if ttype == 'str':
text_params = default_params(semantic)
elif ttype == 'dict':
text_params = default_params(semantic['model'], semantic['params'])
semantic = semantic['model']
elif ttype in ('class', 'class_instance'):
if hasattr(semantic, 'fit_transform'):
texts.update({'user_model' : semantic})
semantic = 'user_model'
else:
raise RuntimeError('Text model must have fit_transform '
'method following the scikit-learn API. See here '
'for more details: '
'http://scikit-learn.org/stable/data_transforms.html')
if vectorizer:
if vtype in ('str', 'dict'):
vmodel = vectorizer_models[vectorizer](**vectorizer_params)
elif vtype == 'class':
vmodel = vectorizer_models[vectorizer]()
elif vtype == 'class_instance':
vmodel = vectorizer_models[vectorizer]
else:
vmodel = None
if semantic:
if ttype in ('str', 'dict'):
tmodel = texts[semantic](**text_params)
elif ttype == 'class':
tmodel = texts[semantic]()
elif ttype == 'class_instance':
tmodel = texts[semantic]
else:
tmodel = None
if not isinstance(data, list):
data = [data]
if corpus is None:
_fit_models(vmodel, tmodel, data, model_is_fit)
else:
_fit_models(vmodel, tmodel, corpus, model_is_fit)
return _transform(vmodel, tmodel, data) | [
"def",
"text2mat",
"(",
"data",
",",
"vectorizer",
"=",
"'CountVectorizer'",
",",
"semantic",
"=",
"'LatentDirichletAllocation'",
",",
"corpus",
"=",
"'wiki'",
")",
":",
"if",
"semantic",
"is",
"None",
":",
"semantic",
"=",
"'LatentDirichletAllocation'",
"if",
"... | Turns a list of text samples into a matrix using a vectorizer and a text model
Parameters
----------
data : list (or list of lists) of text samples
The text data to transform
vectorizer : str, dict, class or class instance
The vectorizer to use. Built-in options are 'CountVectorizer' or
'TfidfVectorizer'. To change default parameters, set to a dictionary
e.g. {'model' : 'CountVectorizer', 'params' : {'max_features' : 10}}. See
http://scikit-learn.org/stable/modules/classes.html#module-sklearn.feature_extraction.text
for details. You can also specify your own vectorizer model as a class,
or class instance. With either option, the class must have a
fit_transform method (see here: http://scikit-learn.org/stable/data_transforms.html).
If a class, pass any parameters as a dictionary to vectorizer_params. If
a class instance, no parameters can be passed.
semantic : str, dict, class or class instance
Text model to use to transform text data. Built-in options are
'LatentDirichletAllocation' or 'NMF' (default: LDA). To change default
parameters, set to a dictionary e.g. {'model' : 'NMF', 'params' :
{'n_components' : 10}}. See
http://scikit-learn.org/stable/modules/classes.html#module-sklearn.decomposition
for details on the two model options. You can also specify your own
text model as a class, or class instance. With either option, the class
must have a fit_transform method (see here:
http://scikit-learn.org/stable/data_transforms.html).
If a class, pass any parameters as a dictionary to text_params. If
a class instance, no parameters can be passed.
corpus : list (or list of lists) of text samples or 'wiki', 'nips', 'sotus'.
Text to use to fit the semantic model (optional). If set to 'wiki', 'nips'
or 'sotus' and the default semantic and vectorizer models are used, a
pretrained model will be loaded which can save a lot of time.
Returns
----------
transformed data : list of numpy arrays
The transformed text data | [
"Turns",
"a",
"list",
"of",
"text",
"samples",
"into",
"a",
"matrix",
"using",
"a",
"vectorizer",
"and",
"a",
"text",
"model"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/text2mat.py#L28-L148 |
233,802 | ContextLab/hypertools | hypertools/_shared/helpers.py | patch_lines | def patch_lines(x):
"""
Draw lines between groups
"""
for idx in range(len(x)-1):
x[idx] = np.vstack([x[idx], x[idx+1][0,:]])
return x | python | def patch_lines(x):
for idx in range(len(x)-1):
x[idx] = np.vstack([x[idx], x[idx+1][0,:]])
return x | [
"def",
"patch_lines",
"(",
"x",
")",
":",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"x",
")",
"-",
"1",
")",
":",
"x",
"[",
"idx",
"]",
"=",
"np",
".",
"vstack",
"(",
"[",
"x",
"[",
"idx",
"]",
",",
"x",
"[",
"idx",
"+",
"1",
"]",
"... | Draw lines between groups | [
"Draw",
"lines",
"between",
"groups"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_shared/helpers.py#L161-L167 |
233,803 | ContextLab/hypertools | hypertools/_shared/helpers.py | check_geo | def check_geo(geo):
""" Checks a geo and makes sure the text fields are not binary """
geo = copy.copy(geo)
def fix_item(item):
if isinstance(item, six.binary_type):
return item.decode()
return item
def fix_list(lst):
return [fix_item(i) for i in lst]
if isinstance(geo.reduce, six.binary_type):
geo.reduce = geo.reduce.decode()
for key in geo.kwargs.keys():
if geo.kwargs[key] is not None:
if isinstance(geo.kwargs[key], (list, np.ndarray)):
geo.kwargs[key] = fix_list(geo.kwargs[key])
elif isinstance(geo.kwargs[key], six.binary_type):
geo.kwargs[key] = fix_item(geo.kwargs[key])
return geo | python | def check_geo(geo):
geo = copy.copy(geo)
def fix_item(item):
if isinstance(item, six.binary_type):
return item.decode()
return item
def fix_list(lst):
return [fix_item(i) for i in lst]
if isinstance(geo.reduce, six.binary_type):
geo.reduce = geo.reduce.decode()
for key in geo.kwargs.keys():
if geo.kwargs[key] is not None:
if isinstance(geo.kwargs[key], (list, np.ndarray)):
geo.kwargs[key] = fix_list(geo.kwargs[key])
elif isinstance(geo.kwargs[key], six.binary_type):
geo.kwargs[key] = fix_item(geo.kwargs[key])
return geo | [
"def",
"check_geo",
"(",
"geo",
")",
":",
"geo",
"=",
"copy",
".",
"copy",
"(",
"geo",
")",
"def",
"fix_item",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"item",
".",
"decode",
"(",
... | Checks a geo and makes sure the text fields are not binary | [
"Checks",
"a",
"geo",
"and",
"makes",
"sure",
"the",
"text",
"fields",
"are",
"not",
"binary"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_shared/helpers.py#L232-L251 |
233,804 | ContextLab/hypertools | hypertools/tools/df2mat.py | df2mat | def df2mat(data, return_labels=False):
"""
Transforms a Pandas DataFrame into a Numpy array with binarized text columns
This function transforms single-level df to an array so it can be plotted
with HyperTools. Additionally, it uses the Pandas.Dataframe.get_dummies
function to transform text columns into binary vectors, or
'dummy variables'.
Parameters
----------
data : A single-level Pandas DataFrame
The df that you want to convert. Note that this currently only works
with single-level (not Multi-level indices).
Returns
----------
plot_data : Numpy array
A Numpy array where text columns are turned into binary vectors.
labels : list (optional)
A list of column labels for the numpy array. To return this, set
return_labels=True.
"""
df_str = data.select_dtypes(include=['object'])
df_num = data.select_dtypes(exclude=['object'])
for colname in df_str.columns:
df_num = df_num.join(pd.get_dummies(data[colname], prefix=colname))
plot_data = df_num.as_matrix()
labels=list(df_num.columns.values)
if return_labels:
return plot_data,labels
else:
return plot_data | python | def df2mat(data, return_labels=False):
df_str = data.select_dtypes(include=['object'])
df_num = data.select_dtypes(exclude=['object'])
for colname in df_str.columns:
df_num = df_num.join(pd.get_dummies(data[colname], prefix=colname))
plot_data = df_num.as_matrix()
labels=list(df_num.columns.values)
if return_labels:
return plot_data,labels
else:
return plot_data | [
"def",
"df2mat",
"(",
"data",
",",
"return_labels",
"=",
"False",
")",
":",
"df_str",
"=",
"data",
".",
"select_dtypes",
"(",
"include",
"=",
"[",
"'object'",
"]",
")",
"df_num",
"=",
"data",
".",
"select_dtypes",
"(",
"exclude",
"=",
"[",
"'object'",
... | Transforms a Pandas DataFrame into a Numpy array with binarized text columns
This function transforms single-level df to an array so it can be plotted
with HyperTools. Additionally, it uses the Pandas.Dataframe.get_dummies
function to transform text columns into binary vectors, or
'dummy variables'.
Parameters
----------
data : A single-level Pandas DataFrame
The df that you want to convert. Note that this currently only works
with single-level (not Multi-level indices).
Returns
----------
plot_data : Numpy array
A Numpy array where text columns are turned into binary vectors.
labels : list (optional)
A list of column labels for the numpy array. To return this, set
return_labels=True. | [
"Transforms",
"a",
"Pandas",
"DataFrame",
"into",
"a",
"Numpy",
"array",
"with",
"binarized",
"text",
"columns"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/df2mat.py#L6-L45 |
233,805 | ContextLab/hypertools | hypertools/tools/load.py | load | def load(dataset, reduce=None, ndims=None, align=None, normalize=None):
"""
Load a .geo file or example data
Parameters
----------
dataset : string
The name of the example dataset. Can be a `.geo` file, or one of a
number of example datasets listed below.
`weights` is list of 2 numpy arrays, each containing average brain
activity (fMRI) from 18 subjects listening to the same story, fit using
Hierarchical Topographic Factor Analysis (HTFA) with 100 nodes. The rows
are fMRI measurements and the columns are parameters of the model.
`weights_sample` is a sample of 3 subjects from that dataset.
`weights_avg` is the dataset split in half and averaged into two groups.
`spiral` is numpy array containing data for a 3D spiral, used to
highlight the `procrustes` function.
`mushrooms` is a numpy array comprised of features (columns) of a
collection of 8,124 mushroomm samples (rows).
`sotus` is a collection of State of the Union speeches from 1989-2018.
`wiki` is a collection of wikipedia pages used to fit wiki-model.
`wiki-model` is a sklearn Pipeline (CountVectorizer->LatentDirichletAllocation)
trained on a sample of wikipedia articles. It can be used to transform
text to topic vectors.
normalize : str or False or None
If set to 'across', the columns of the input data will be z-scored
across lists (default). That is, the z-scores will be computed with
with respect to column n across all arrays passed in the list. If set
to 'within', the columns will be z-scored within each list that is
passed. If set to 'row', each row of the input data will be z-scored.
If set to False, the input data will be returned with no z-scoring.
reduce : str or dict
Decomposition/manifold learning model to use. Models supported: PCA,
IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA,
FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning,
TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be
passed as a string, but for finer control of the model parameters, pass
as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}.
See scikit-learn specific model docs for details on parameters supported
for each model.
ndims : int
Number of dimensions to reduce
align : str or dict
If str, either 'hyper' or 'SRM'. If 'hyper', alignment algorithm will be
hyperalignment. If 'SRM', alignment algorithm will be shared response
model. You can also pass a dictionary for finer control, where the 'model'
key is a string that specifies the model and the params key is a dictionary
of parameter values (default : 'hyper').
Returns
----------
data : Numpy Array
Example data
"""
if dataset[-4:] == '.geo':
geo = dd.io.load(dataset)
if 'dtype' in geo:
if 'list' in geo['dtype']:
geo['data'] = list(geo['data'])
elif 'df' in geo['dtype']:
geo['data'] = pd.DataFrame(geo['data'])
geo['xform_data'] = list(geo['xform_data'])
data = DataGeometry(**geo)
elif dataset in datadict.keys():
data = _load_data(dataset, datadict[dataset])
else:
raise RuntimeError('No data loaded. Please specify a .geo file or '
'one of the following sample files: weights, '
'weights_avg, weights_sample, spiral, mushrooms, '
'wiki, nips or sotus.')
if data is not None:
if dataset in ('wiki_model', 'nips_model', 'sotus_model'):
return data
if isinstance(data, DataGeometry):
if any([reduce, ndims, align, normalize]):
from ..plot.plot import plot
if ndims:
if reduce is None:
reduce='IncrementalPCA'
d = analyze(data.get_data(), reduce=reduce, ndims=ndims, align=align, normalize=normalize)
return plot(d, show=False)
else:
return data
else:
return analyze(data, reduce=reduce, ndims=ndims, align=align, normalize=normalize) | python | def load(dataset, reduce=None, ndims=None, align=None, normalize=None):
if dataset[-4:] == '.geo':
geo = dd.io.load(dataset)
if 'dtype' in geo:
if 'list' in geo['dtype']:
geo['data'] = list(geo['data'])
elif 'df' in geo['dtype']:
geo['data'] = pd.DataFrame(geo['data'])
geo['xform_data'] = list(geo['xform_data'])
data = DataGeometry(**geo)
elif dataset in datadict.keys():
data = _load_data(dataset, datadict[dataset])
else:
raise RuntimeError('No data loaded. Please specify a .geo file or '
'one of the following sample files: weights, '
'weights_avg, weights_sample, spiral, mushrooms, '
'wiki, nips or sotus.')
if data is not None:
if dataset in ('wiki_model', 'nips_model', 'sotus_model'):
return data
if isinstance(data, DataGeometry):
if any([reduce, ndims, align, normalize]):
from ..plot.plot import plot
if ndims:
if reduce is None:
reduce='IncrementalPCA'
d = analyze(data.get_data(), reduce=reduce, ndims=ndims, align=align, normalize=normalize)
return plot(d, show=False)
else:
return data
else:
return analyze(data, reduce=reduce, ndims=ndims, align=align, normalize=normalize) | [
"def",
"load",
"(",
"dataset",
",",
"reduce",
"=",
"None",
",",
"ndims",
"=",
"None",
",",
"align",
"=",
"None",
",",
"normalize",
"=",
"None",
")",
":",
"if",
"dataset",
"[",
"-",
"4",
":",
"]",
"==",
"'.geo'",
":",
"geo",
"=",
"dd",
".",
"io"... | Load a .geo file or example data
Parameters
----------
dataset : string
The name of the example dataset. Can be a `.geo` file, or one of a
number of example datasets listed below.
`weights` is list of 2 numpy arrays, each containing average brain
activity (fMRI) from 18 subjects listening to the same story, fit using
Hierarchical Topographic Factor Analysis (HTFA) with 100 nodes. The rows
are fMRI measurements and the columns are parameters of the model.
`weights_sample` is a sample of 3 subjects from that dataset.
`weights_avg` is the dataset split in half and averaged into two groups.
`spiral` is numpy array containing data for a 3D spiral, used to
highlight the `procrustes` function.
`mushrooms` is a numpy array comprised of features (columns) of a
collection of 8,124 mushroomm samples (rows).
`sotus` is a collection of State of the Union speeches from 1989-2018.
`wiki` is a collection of wikipedia pages used to fit wiki-model.
`wiki-model` is a sklearn Pipeline (CountVectorizer->LatentDirichletAllocation)
trained on a sample of wikipedia articles. It can be used to transform
text to topic vectors.
normalize : str or False or None
If set to 'across', the columns of the input data will be z-scored
across lists (default). That is, the z-scores will be computed with
with respect to column n across all arrays passed in the list. If set
to 'within', the columns will be z-scored within each list that is
passed. If set to 'row', each row of the input data will be z-scored.
If set to False, the input data will be returned with no z-scoring.
reduce : str or dict
Decomposition/manifold learning model to use. Models supported: PCA,
IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA,
FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning,
TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be
passed as a string, but for finer control of the model parameters, pass
as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}.
See scikit-learn specific model docs for details on parameters supported
for each model.
ndims : int
Number of dimensions to reduce
align : str or dict
If str, either 'hyper' or 'SRM'. If 'hyper', alignment algorithm will be
hyperalignment. If 'SRM', alignment algorithm will be shared response
model. You can also pass a dictionary for finer control, where the 'model'
key is a string that specifies the model and the params key is a dictionary
of parameter values (default : 'hyper').
Returns
----------
data : Numpy Array
Example data | [
"Load",
"a",
".",
"geo",
"file",
"or",
"example",
"data"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/load.py#L30-L129 |
233,806 | ContextLab/hypertools | hypertools/datageometry.py | DataGeometry.transform | def transform(self, data=None):
"""
Return transformed data, or transform new data using the same model
parameters
Parameters
----------
data : numpy array, pandas dataframe or list of arrays/dfs
The data to transform. If no data is passed, the xform_data from
the DataGeometry object will be returned.
Returns
----------
xformed_data : list of numpy arrays
The transformed data
"""
# if no new data passed,
if data is None:
return self.xform_data
else:
formatted = format_data(
data,
semantic=self.semantic,
vectorizer=self.vectorizer,
corpus=self.corpus,
ppca=True)
norm = normalizer(formatted, normalize=self.normalize)
reduction = reducer(
norm,
reduce=self.reduce,
ndims=self.reduce['params']['n_components'])
return aligner(reduction, align=self.align) | python | def transform(self, data=None):
# if no new data passed,
if data is None:
return self.xform_data
else:
formatted = format_data(
data,
semantic=self.semantic,
vectorizer=self.vectorizer,
corpus=self.corpus,
ppca=True)
norm = normalizer(formatted, normalize=self.normalize)
reduction = reducer(
norm,
reduce=self.reduce,
ndims=self.reduce['params']['n_components'])
return aligner(reduction, align=self.align) | [
"def",
"transform",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"# if no new data passed,",
"if",
"data",
"is",
"None",
":",
"return",
"self",
".",
"xform_data",
"else",
":",
"formatted",
"=",
"format_data",
"(",
"data",
",",
"semantic",
"=",
"self",
... | Return transformed data, or transform new data using the same model
parameters
Parameters
----------
data : numpy array, pandas dataframe or list of arrays/dfs
The data to transform. If no data is passed, the xform_data from
the DataGeometry object will be returned.
Returns
----------
xformed_data : list of numpy arrays
The transformed data | [
"Return",
"transformed",
"data",
"or",
"transform",
"new",
"data",
"using",
"the",
"same",
"model",
"parameters"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/datageometry.py#L110-L142 |
233,807 | ContextLab/hypertools | hypertools/datageometry.py | DataGeometry.save | def save(self, fname, compression='blosc'):
"""
Save method for the data geometry object
The data will be saved as a 'geo' file, which is a dictionary containing
the elements of a data geometry object saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
A name for the file. If the file extension (.geo) is not specified,
it will be appended.
compression : str
The kind of compression to use. See the deepdish documentation for
options: http://deepdish.readthedocs.io/en/latest/api_io.html#deepdish.io.save
"""
if hasattr(self, 'dtype'):
if 'list' in self.dtype:
data = np.array(self.data)
elif 'df' in self.dtype:
data = {k: np.array(v).astype('str') for k, v in self.data.to_dict('list').items()}
else:
data = self.data
# put geo vars into a dict
geo = {
'data' : data,
'xform_data' : np.array(self.xform_data),
'reduce' : self.reduce,
'align' : self.align,
'normalize' : self.normalize,
'semantic' : self.semantic,
'corpus' : np.array(self.corpus) if isinstance(self.corpus, list) else self.corpus,
'kwargs' : self.kwargs,
'version' : self.version,
'dtype' : self.dtype
}
# if extension wasn't included, add it
if fname[-4:]!='.geo':
fname+='.geo'
# save
dd.io.save(fname, geo, compression=compression) | python | def save(self, fname, compression='blosc'):
if hasattr(self, 'dtype'):
if 'list' in self.dtype:
data = np.array(self.data)
elif 'df' in self.dtype:
data = {k: np.array(v).astype('str') for k, v in self.data.to_dict('list').items()}
else:
data = self.data
# put geo vars into a dict
geo = {
'data' : data,
'xform_data' : np.array(self.xform_data),
'reduce' : self.reduce,
'align' : self.align,
'normalize' : self.normalize,
'semantic' : self.semantic,
'corpus' : np.array(self.corpus) if isinstance(self.corpus, list) else self.corpus,
'kwargs' : self.kwargs,
'version' : self.version,
'dtype' : self.dtype
}
# if extension wasn't included, add it
if fname[-4:]!='.geo':
fname+='.geo'
# save
dd.io.save(fname, geo, compression=compression) | [
"def",
"save",
"(",
"self",
",",
"fname",
",",
"compression",
"=",
"'blosc'",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'dtype'",
")",
":",
"if",
"'list'",
"in",
"self",
".",
"dtype",
":",
"data",
"=",
"np",
".",
"array",
"(",
"self",
".",
"d... | Save method for the data geometry object
The data will be saved as a 'geo' file, which is a dictionary containing
the elements of a data geometry object saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
A name for the file. If the file extension (.geo) is not specified,
it will be appended.
compression : str
The kind of compression to use. See the deepdish documentation for
options: http://deepdish.readthedocs.io/en/latest/api_io.html#deepdish.io.save | [
"Save",
"method",
"for",
"the",
"data",
"geometry",
"object"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/datageometry.py#L191-L238 |
233,808 | ContextLab/hypertools | hypertools/tools/analyze.py | analyze | def analyze(data, normalize=None, reduce=None, ndims=None, align=None, internal=False):
"""
Wrapper function for normalize -> reduce -> align transformations.
Parameters
----------
data : numpy array, pandas df, or list of arrays/dfs
The data to analyze
normalize : str or False or None
If set to 'across', the columns of the input data will be z-scored
across lists (default). That is, the z-scores will be computed with
with respect to column n across all arrays passed in the list. If set
to 'within', the columns will be z-scored within each list that is
passed. If set to 'row', each row of the input data will be z-scored.
If set to False, the input data will be returned with no z-scoring.
reduce : str or dict
Decomposition/manifold learning model to use. Models supported: PCA,
IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA,
FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning,
TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be
passed as a string, but for finer control of the model parameters, pass
as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}.
See scikit-learn specific model docs for details on parameters supported
for each model.
ndims : int
Number of dimensions to reduce
align : str or dict
If str, either 'hyper' or 'SRM'. If 'hyper', alignment algorithm will be
hyperalignment. If 'SRM', alignment algorithm will be shared response
model. You can also pass a dictionary for finer control, where the 'model'
key is a string that specifies the model and the params key is a dictionary
of parameter values (default : 'hyper').
Returns
----------
analyzed_data : list of numpy arrays
The processed data
"""
# return processed data
return aligner(reducer(normalizer(data, normalize=normalize, internal=internal),
reduce=reduce, ndims=ndims, internal=internal), align=align) | python | def analyze(data, normalize=None, reduce=None, ndims=None, align=None, internal=False):
# return processed data
return aligner(reducer(normalizer(data, normalize=normalize, internal=internal),
reduce=reduce, ndims=ndims, internal=internal), align=align) | [
"def",
"analyze",
"(",
"data",
",",
"normalize",
"=",
"None",
",",
"reduce",
"=",
"None",
",",
"ndims",
"=",
"None",
",",
"align",
"=",
"None",
",",
"internal",
"=",
"False",
")",
":",
"# return processed data",
"return",
"aligner",
"(",
"reducer",
"(",
... | Wrapper function for normalize -> reduce -> align transformations.
Parameters
----------
data : numpy array, pandas df, or list of arrays/dfs
The data to analyze
normalize : str or False or None
If set to 'across', the columns of the input data will be z-scored
across lists (default). That is, the z-scores will be computed with
with respect to column n across all arrays passed in the list. If set
to 'within', the columns will be z-scored within each list that is
passed. If set to 'row', each row of the input data will be z-scored.
If set to False, the input data will be returned with no z-scoring.
reduce : str or dict
Decomposition/manifold learning model to use. Models supported: PCA,
IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA,
FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning,
TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, and MDS. Can be
passed as a string, but for finer control of the model parameters, pass
as a dictionary, e.g. reduce={'model' : 'PCA', 'params' : {'whiten' : True}}.
See scikit-learn specific model docs for details on parameters supported
for each model.
ndims : int
Number of dimensions to reduce
align : str or dict
If str, either 'hyper' or 'SRM'. If 'hyper', alignment algorithm will be
hyperalignment. If 'SRM', alignment algorithm will be shared response
model. You can also pass a dictionary for finer control, where the 'model'
key is a string that specifies the model and the params key is a dictionary
of parameter values (default : 'hyper').
Returns
----------
analyzed_data : list of numpy arrays
The processed data | [
"Wrapper",
"function",
"for",
"normalize",
"-",
">",
"reduce",
"-",
">",
"align",
"transformations",
"."
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/analyze.py#L8-L54 |
233,809 | ContextLab/hypertools | hypertools/tools/reduce.py | reduce | def reduce(x, reduce='IncrementalPCA', ndims=None, normalize=None, align=None,
model=None, model_params=None, internal=False, format_data=True):
"""
Reduces dimensionality of an array, or list of arrays
Parameters
----------
x : Numpy array or list of arrays
Dimensionality reduction using PCA is performed on this array.
reduce : str or dict
Decomposition/manifold learning model to use. Models supported: PCA,
IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA,
FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning,
TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, MDS and UMAP.
Can be passed as a string, but for finer control of the model
parameters, pass as a dictionary, e.g. reduce={'model' : 'PCA',
'params' : {'whiten' : True}}. See scikit-learn specific model docs
for details on parameters supported for each model.
ndims : int
Number of dimensions to reduce
format_data : bool
Whether or not to first call the format_data function (default: True).
model : None
Deprecated argument. Please use reduce.
model_params : None
Deprecated argument. Please use reduce.
align : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
normalize : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
Returns
----------
x_reduced : Numpy array or list of arrays
The reduced data with ndims dimensionality is returned. If the input
is a list, a list is returned.
"""
# deprecated warning
if (model is not None) or (model_params is not None):
warnings.warn('Model and model params will be deprecated. Please use the \
reduce keyword. See API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.tools.reduce.html#hypertools.tools.reduce')
reduce = {}
reduce['model'] = model
reduce['params'] = model_params
# if model is None, just return data
if reduce is None:
return x
else:
# common format
if format_data:
x = formatter(x, ppca=True)
if np.vstack([i for i in x]).shape[0]==1:
warnings.warn('Cannot reduce the dimensionality of a single row of'
' data. Return zeros length of ndims')
return [np.zeros((1, ndims))]
if ndims:
if np.vstack([i for i in x]).shape[0]<ndims:
warnings.warn('The number of rows in your data is less than ndims.'
' The data will be reduced to the number of rows.')
# deprecation warnings
if normalize is not None:
warnings.warn('The normalize argument will be deprecated for this function. Please use the \
analyze function to perform combinations of these transformations. See API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.analyze.html#hypertools.analyze')
x = normalizer(x, normalize=normalize)
if align is not None:
warnings.warn('The align argument will be deprecated for this function. Please use the \
analyze function to perform combinations of these transformations. See API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.analyze.html#hypertools.analyze')
x = aligner(x, align=align)
# if the shape of the data is already less than ndims, just return it
if ndims is None:
return x
elif all([i.shape[1]<=ndims for i in x]):
return x
# if reduce is a string, find the corresponding model
if type(reduce) in [str, np.string_]:
model = models[reduce]
model_params = {
'n_components' : ndims
}
# if its a dict, use custom params
elif type(reduce) is dict:
if isinstance((reduce['model']), six.string_types):
model = models[reduce['model']]
if reduce['params'] is None:
model_params = {
'n_components' : ndims
}
else:
model_params = reduce['params']
if ndims:
model_params = {
'n_components' : ndims
}
# initialize model
model = model(**model_params)
# reduce data
x_reduced = reduce_list(x, model)
# return data
if internal or len(x_reduced)>1:
return x_reduced
else:
return x_reduced[0] | python | def reduce(x, reduce='IncrementalPCA', ndims=None, normalize=None, align=None,
model=None, model_params=None, internal=False, format_data=True):
# deprecated warning
if (model is not None) or (model_params is not None):
warnings.warn('Model and model params will be deprecated. Please use the \
reduce keyword. See API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.tools.reduce.html#hypertools.tools.reduce')
reduce = {}
reduce['model'] = model
reduce['params'] = model_params
# if model is None, just return data
if reduce is None:
return x
else:
# common format
if format_data:
x = formatter(x, ppca=True)
if np.vstack([i for i in x]).shape[0]==1:
warnings.warn('Cannot reduce the dimensionality of a single row of'
' data. Return zeros length of ndims')
return [np.zeros((1, ndims))]
if ndims:
if np.vstack([i for i in x]).shape[0]<ndims:
warnings.warn('The number of rows in your data is less than ndims.'
' The data will be reduced to the number of rows.')
# deprecation warnings
if normalize is not None:
warnings.warn('The normalize argument will be deprecated for this function. Please use the \
analyze function to perform combinations of these transformations. See API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.analyze.html#hypertools.analyze')
x = normalizer(x, normalize=normalize)
if align is not None:
warnings.warn('The align argument will be deprecated for this function. Please use the \
analyze function to perform combinations of these transformations. See API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.analyze.html#hypertools.analyze')
x = aligner(x, align=align)
# if the shape of the data is already less than ndims, just return it
if ndims is None:
return x
elif all([i.shape[1]<=ndims for i in x]):
return x
# if reduce is a string, find the corresponding model
if type(reduce) in [str, np.string_]:
model = models[reduce]
model_params = {
'n_components' : ndims
}
# if its a dict, use custom params
elif type(reduce) is dict:
if isinstance((reduce['model']), six.string_types):
model = models[reduce['model']]
if reduce['params'] is None:
model_params = {
'n_components' : ndims
}
else:
model_params = reduce['params']
if ndims:
model_params = {
'n_components' : ndims
}
# initialize model
model = model(**model_params)
# reduce data
x_reduced = reduce_list(x, model)
# return data
if internal or len(x_reduced)>1:
return x_reduced
else:
return x_reduced[0] | [
"def",
"reduce",
"(",
"x",
",",
"reduce",
"=",
"'IncrementalPCA'",
",",
"ndims",
"=",
"None",
",",
"normalize",
"=",
"None",
",",
"align",
"=",
"None",
",",
"model",
"=",
"None",
",",
"model_params",
"=",
"None",
",",
"internal",
"=",
"False",
",",
"... | Reduces dimensionality of an array, or list of arrays
Parameters
----------
x : Numpy array or list of arrays
Dimensionality reduction using PCA is performed on this array.
reduce : str or dict
Decomposition/manifold learning model to use. Models supported: PCA,
IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA,
FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning,
TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, MDS and UMAP.
Can be passed as a string, but for finer control of the model
parameters, pass as a dictionary, e.g. reduce={'model' : 'PCA',
'params' : {'whiten' : True}}. See scikit-learn specific model docs
for details on parameters supported for each model.
ndims : int
Number of dimensions to reduce
format_data : bool
Whether or not to first call the format_data function (default: True).
model : None
Deprecated argument. Please use reduce.
model_params : None
Deprecated argument. Please use reduce.
align : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
normalize : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
Returns
----------
x_reduced : Numpy array or list of arrays
The reduced data with ndims dimensionality is returned. If the input
is a list, a list is returned. | [
"Reduces",
"dimensionality",
"of",
"an",
"array",
"or",
"list",
"of",
"arrays"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/reduce.py#L36-L158 |
233,810 | ContextLab/hypertools | hypertools/tools/cluster.py | cluster | def cluster(x, cluster='KMeans', n_clusters=3, ndims=None, format_data=True):
"""
Performs clustering analysis and returns a list of cluster labels
Parameters
----------
x : A Numpy array, Pandas Dataframe or list of arrays/dfs
The data to be clustered. You can pass a single array/df or a list.
If a list is passed, the arrays will be stacked and the clustering
will be performed across all lists (i.e. not within each list).
cluster : str or dict
Model to use to discover clusters. Support algorithms are: KMeans,
MiniBatchKMeans, AgglomerativeClustering, Birch, FeatureAgglomeration,
SpectralClustering and HDBSCAN (default: KMeans). Can be passed as a
string, but for finer control of the model parameters, pass as a
dictionary, e.g. reduce={'model' : 'KMeans', 'params' : {'max_iter' : 100}}.
See scikit-learn specific model docs for details on parameters supported for
each model.
n_clusters : int
Number of clusters to discover. Not required for HDBSCAN.
format_data : bool
Whether or not to first call the format_data function (default: True).
ndims : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
Returns
----------
cluster_labels : list
An list of cluster labels
"""
if cluster == None:
return x
elif (isinstance(cluster, six.string_types) and cluster=='HDBSCAN') or \
(isinstance(cluster, dict) and cluster['model']=='HDBSCAN'):
if not _has_hdbscan:
raise ImportError('HDBSCAN is not installed. Please install hdbscan>=0.8.11')
if ndims != None:
warnings.warn('The ndims argument is now deprecated. Ignoring dimensionality reduction step.')
if format_data:
x = formatter(x, ppca=True)
# if reduce is a string, find the corresponding model
if isinstance(cluster, six.string_types):
model = models[cluster]
if cluster != 'HDBSCAN':
model_params = {
'n_clusters' : n_clusters
}
else:
model_params = {}
# if its a dict, use custom params
elif type(cluster) is dict:
if isinstance(cluster['model'], six.string_types):
model = models[cluster['model']]
model_params = cluster['params']
# initialize model
model = model(**model_params)
# fit the model
model.fit(np.vstack(x))
# return the labels
return list(model.labels_) | python | def cluster(x, cluster='KMeans', n_clusters=3, ndims=None, format_data=True):
if cluster == None:
return x
elif (isinstance(cluster, six.string_types) and cluster=='HDBSCAN') or \
(isinstance(cluster, dict) and cluster['model']=='HDBSCAN'):
if not _has_hdbscan:
raise ImportError('HDBSCAN is not installed. Please install hdbscan>=0.8.11')
if ndims != None:
warnings.warn('The ndims argument is now deprecated. Ignoring dimensionality reduction step.')
if format_data:
x = formatter(x, ppca=True)
# if reduce is a string, find the corresponding model
if isinstance(cluster, six.string_types):
model = models[cluster]
if cluster != 'HDBSCAN':
model_params = {
'n_clusters' : n_clusters
}
else:
model_params = {}
# if its a dict, use custom params
elif type(cluster) is dict:
if isinstance(cluster['model'], six.string_types):
model = models[cluster['model']]
model_params = cluster['params']
# initialize model
model = model(**model_params)
# fit the model
model.fit(np.vstack(x))
# return the labels
return list(model.labels_) | [
"def",
"cluster",
"(",
"x",
",",
"cluster",
"=",
"'KMeans'",
",",
"n_clusters",
"=",
"3",
",",
"ndims",
"=",
"None",
",",
"format_data",
"=",
"True",
")",
":",
"if",
"cluster",
"==",
"None",
":",
"return",
"x",
"elif",
"(",
"isinstance",
"(",
"cluste... | Performs clustering analysis and returns a list of cluster labels
Parameters
----------
x : A Numpy array, Pandas Dataframe or list of arrays/dfs
The data to be clustered. You can pass a single array/df or a list.
If a list is passed, the arrays will be stacked and the clustering
will be performed across all lists (i.e. not within each list).
cluster : str or dict
Model to use to discover clusters. Support algorithms are: KMeans,
MiniBatchKMeans, AgglomerativeClustering, Birch, FeatureAgglomeration,
SpectralClustering and HDBSCAN (default: KMeans). Can be passed as a
string, but for finer control of the model parameters, pass as a
dictionary, e.g. reduce={'model' : 'KMeans', 'params' : {'max_iter' : 100}}.
See scikit-learn specific model docs for details on parameters supported for
each model.
n_clusters : int
Number of clusters to discover. Not required for HDBSCAN.
format_data : bool
Whether or not to first call the format_data function (default: True).
ndims : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
Returns
----------
cluster_labels : list
An list of cluster labels | [
"Performs",
"clustering",
"analysis",
"and",
"returns",
"a",
"list",
"of",
"cluster",
"labels"
] | b76c7ac8061998b560e969ff8e4f4c915088e7a0 | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/cluster.py#L28-L100 |
233,811 | lorien/grab | grab/transport/curl.py | build_grab_exception | def build_grab_exception(ex, curl):
"""
Build Grab exception from the pycurl exception
Args:
ex - the original pycurl exception
curl - the Curl instance raised the exception
"""
# CURLE_WRITE_ERROR (23)
# An error occurred when writing received data to a local file, or
# an error was returned to libcurl from a write callback.
# This exception should be ignored if grab_callback_interrupted
# flag # is enabled (this happens when nohead or nobody options
# enabled)
#
# Also this error is raised when curl receives KeyboardInterrupt
# while it is processing some callback function
# (WRITEFUNCTION, HEADERFUNCTIO, etc)
# If you think WTF then see details here:
# https://github.com/pycurl/pycurl/issues/413
if ex.args[0] == 23:
if getattr(curl, 'grab_callback_interrupted', None) is True:
# If the execution of body_process callback is
# interrupted (body_maxsize, nobody and other options)
# then the pycurl raised exception with code 23
# We should ignore it
return None
else:
return error.GrabNetworkError(ex.args[1], ex)
else:
if ex.args[0] == 28:
return error.GrabTimeoutError(ex.args[1], ex)
elif ex.args[0] == 7:
return error.GrabConnectionError(ex.args[1], ex)
elif ex.args[0] == 67:
return error.GrabAuthError(ex.args[1], ex)
elif ex.args[0] == 47:
return error.GrabTooManyRedirectsError(ex.args[1], ex)
elif ex.args[0] == 6:
return error.GrabCouldNotResolveHostError(ex.args[1], ex)
elif ex.args[0] == 3:
return error.GrabInvalidUrl(ex.args[1], ex)
else:
return error.GrabNetworkError(ex.args[1], ex) | python | def build_grab_exception(ex, curl):
# CURLE_WRITE_ERROR (23)
# An error occurred when writing received data to a local file, or
# an error was returned to libcurl from a write callback.
# This exception should be ignored if grab_callback_interrupted
# flag # is enabled (this happens when nohead or nobody options
# enabled)
#
# Also this error is raised when curl receives KeyboardInterrupt
# while it is processing some callback function
# (WRITEFUNCTION, HEADERFUNCTIO, etc)
# If you think WTF then see details here:
# https://github.com/pycurl/pycurl/issues/413
if ex.args[0] == 23:
if getattr(curl, 'grab_callback_interrupted', None) is True:
# If the execution of body_process callback is
# interrupted (body_maxsize, nobody and other options)
# then the pycurl raised exception with code 23
# We should ignore it
return None
else:
return error.GrabNetworkError(ex.args[1], ex)
else:
if ex.args[0] == 28:
return error.GrabTimeoutError(ex.args[1], ex)
elif ex.args[0] == 7:
return error.GrabConnectionError(ex.args[1], ex)
elif ex.args[0] == 67:
return error.GrabAuthError(ex.args[1], ex)
elif ex.args[0] == 47:
return error.GrabTooManyRedirectsError(ex.args[1], ex)
elif ex.args[0] == 6:
return error.GrabCouldNotResolveHostError(ex.args[1], ex)
elif ex.args[0] == 3:
return error.GrabInvalidUrl(ex.args[1], ex)
else:
return error.GrabNetworkError(ex.args[1], ex) | [
"def",
"build_grab_exception",
"(",
"ex",
",",
"curl",
")",
":",
"# CURLE_WRITE_ERROR (23)",
"# An error occurred when writing received data to a local file, or",
"# an error was returned to libcurl from a write callback.",
"# This exception should be ignored if grab_callback_interrupted",
"... | Build Grab exception from the pycurl exception
Args:
ex - the original pycurl exception
curl - the Curl instance raised the exception | [
"Build",
"Grab",
"exception",
"from",
"the",
"pycurl",
"exception"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L587-L630 |
233,812 | lorien/grab | grab/transport/curl.py | CurlTransport.body_processor | def body_processor(self, chunk):
"""
Process body of response.
"""
if self.config_nobody:
self.curl.grab_callback_interrupted = True
return 0
bytes_read = len(chunk)
self.response_body_bytes_read += bytes_read
if self.body_file:
self.body_file.write(chunk)
else:
self.response_body_chunks.append(chunk)
if self.config_body_maxsize is not None:
if self.response_body_bytes_read > self.config_body_maxsize:
logger.debug('Response body max size limit reached: %s',
self.config_body_maxsize)
self.curl.grab_callback_interrupted = True
return 0
# Returning None implies that all bytes were written
return None | python | def body_processor(self, chunk):
if self.config_nobody:
self.curl.grab_callback_interrupted = True
return 0
bytes_read = len(chunk)
self.response_body_bytes_read += bytes_read
if self.body_file:
self.body_file.write(chunk)
else:
self.response_body_chunks.append(chunk)
if self.config_body_maxsize is not None:
if self.response_body_bytes_read > self.config_body_maxsize:
logger.debug('Response body max size limit reached: %s',
self.config_body_maxsize)
self.curl.grab_callback_interrupted = True
return 0
# Returning None implies that all bytes were written
return None | [
"def",
"body_processor",
"(",
"self",
",",
"chunk",
")",
":",
"if",
"self",
".",
"config_nobody",
":",
"self",
".",
"curl",
".",
"grab_callback_interrupted",
"=",
"True",
"return",
"0",
"bytes_read",
"=",
"len",
"(",
"chunk",
")",
"self",
".",
"response_bo... | Process body of response. | [
"Process",
"body",
"of",
"response",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L134-L158 |
233,813 | lorien/grab | grab/transport/curl.py | CurlTransport.debug_processor | def debug_processor(self, _type, text):
"""
Process request details.
0: CURLINFO_TEXT
1: CURLINFO_HEADER_IN
2: CURLINFO_HEADER_OUT
3: CURLINFO_DATA_IN
4: CURLINFO_DATA_OUT
5: CURLINFO_unrecognized_type
"""
if _type == pycurl.INFOTYPE_HEADER_OUT:
if isinstance(text, six.text_type):
text = text.encode('utf-8')
self.request_head += text
if _type == pycurl.INFOTYPE_DATA_OUT:
# Untill 7.19.5.2 version
# pycurl gives unicode in `text` variable
# WTF??? Probably that codes would fails
# or does unexpected things if you use
# pycurl<7.19.5.2
if isinstance(text, six.text_type):
text = text.encode('utf-8')
self.request_body += text
#if _type == pycurl.INFOTYPE_TEXT:
# if self.request_log is None:
# self.request_log = ''
# self.request_log += text
if self.verbose_logging:
if _type in (pycurl.INFOTYPE_TEXT, pycurl.INFOTYPE_HEADER_IN,
pycurl.INFOTYPE_HEADER_OUT):
marker_types = {
pycurl.INFOTYPE_TEXT: 'i',
pycurl.INFOTYPE_HEADER_IN: '<',
pycurl.INFOTYPE_HEADER_OUT: '>',
}
marker = marker_types[_type]
logger.debug('%s: %s', marker, text.rstrip()) | python | def debug_processor(self, _type, text):
if _type == pycurl.INFOTYPE_HEADER_OUT:
if isinstance(text, six.text_type):
text = text.encode('utf-8')
self.request_head += text
if _type == pycurl.INFOTYPE_DATA_OUT:
# Untill 7.19.5.2 version
# pycurl gives unicode in `text` variable
# WTF??? Probably that codes would fails
# or does unexpected things if you use
# pycurl<7.19.5.2
if isinstance(text, six.text_type):
text = text.encode('utf-8')
self.request_body += text
#if _type == pycurl.INFOTYPE_TEXT:
# if self.request_log is None:
# self.request_log = ''
# self.request_log += text
if self.verbose_logging:
if _type in (pycurl.INFOTYPE_TEXT, pycurl.INFOTYPE_HEADER_IN,
pycurl.INFOTYPE_HEADER_OUT):
marker_types = {
pycurl.INFOTYPE_TEXT: 'i',
pycurl.INFOTYPE_HEADER_IN: '<',
pycurl.INFOTYPE_HEADER_OUT: '>',
}
marker = marker_types[_type]
logger.debug('%s: %s', marker, text.rstrip()) | [
"def",
"debug_processor",
"(",
"self",
",",
"_type",
",",
"text",
")",
":",
"if",
"_type",
"==",
"pycurl",
".",
"INFOTYPE_HEADER_OUT",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
":",
"text",
"=",
"text",
".",
"encode",
"("... | Process request details.
0: CURLINFO_TEXT
1: CURLINFO_HEADER_IN
2: CURLINFO_HEADER_OUT
3: CURLINFO_DATA_IN
4: CURLINFO_DATA_OUT
5: CURLINFO_unrecognized_type | [
"Process",
"request",
"details",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L160-L200 |
233,814 | lorien/grab | grab/transport/curl.py | CurlTransport.extract_cookiejar | def extract_cookiejar(self):
"""
Extract cookies that pycurl instance knows.
Returns `CookieJar` object.
"""
# Example of line:
# www.google.com\tFALSE\t/accounts/\tFALSE\t0'
# \tGoogleAccountsLocale_session\ten
# Fields:
# * domain
# * whether or not all machines under that domain can
# read the cookie's information.
# * path
# * Secure Flag: whether or not a secure connection (HTTPS)
# is required to read the cookie.
# * exp. timestamp
# * name
# * value
cookiejar = CookieJar()
for line in self.curl.getinfo(pycurl.INFO_COOKIELIST):
values = line.split('\t')
domain = values[0].lower()
if domain.startswith('#httponly_'):
domain = domain.replace('#httponly_', '')
httponly = True
else:
httponly = False
# old
# cookies[values[-2]] = values[-1]
# new
cookie = create_cookie(
name=values[5],
value=values[6],
domain=domain,
path=values[2],
secure=values[3] == "TRUE",
expires=int(values[4]) if values[4] else None,
httponly=httponly,
)
cookiejar.set_cookie(cookie)
return cookiejar | python | def extract_cookiejar(self):
# Example of line:
# www.google.com\tFALSE\t/accounts/\tFALSE\t0'
# \tGoogleAccountsLocale_session\ten
# Fields:
# * domain
# * whether or not all machines under that domain can
# read the cookie's information.
# * path
# * Secure Flag: whether or not a secure connection (HTTPS)
# is required to read the cookie.
# * exp. timestamp
# * name
# * value
cookiejar = CookieJar()
for line in self.curl.getinfo(pycurl.INFO_COOKIELIST):
values = line.split('\t')
domain = values[0].lower()
if domain.startswith('#httponly_'):
domain = domain.replace('#httponly_', '')
httponly = True
else:
httponly = False
# old
# cookies[values[-2]] = values[-1]
# new
cookie = create_cookie(
name=values[5],
value=values[6],
domain=domain,
path=values[2],
secure=values[3] == "TRUE",
expires=int(values[4]) if values[4] else None,
httponly=httponly,
)
cookiejar.set_cookie(cookie)
return cookiejar | [
"def",
"extract_cookiejar",
"(",
"self",
")",
":",
"# Example of line:",
"# www.google.com\\tFALSE\\t/accounts/\\tFALSE\\t0'",
"# \\tGoogleAccountsLocale_session\\ten",
"# Fields:",
"# * domain",
"# * whether or not all machines under that domain can",
"# read the cookie's information.",
"... | Extract cookies that pycurl instance knows.
Returns `CookieJar` object. | [
"Extract",
"cookies",
"that",
"pycurl",
"instance",
"knows",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L525-L567 |
233,815 | lorien/grab | grab/util/log.py | default_logging | def default_logging(grab_log=None, # '/tmp/grab.log',
network_log=None, # '/tmp/grab.network.log',
level=logging.DEBUG, mode='a',
propagate_network_logger=False):
"""
Customize logging output to display all log messages
except grab network logs.
Redirect grab network logs into file.
"""
logging.basicConfig(level=level)
network_logger = logging.getLogger('grab.network')
network_logger.propagate = propagate_network_logger
if network_log:
hdl = logging.FileHandler(network_log, mode)
network_logger.addHandler(hdl)
network_logger.setLevel(level)
grab_logger = logging.getLogger('grab')
if grab_log:
hdl = logging.FileHandler(grab_log, mode)
grab_logger.addHandler(hdl)
grab_logger.setLevel(level) | python | def default_logging(grab_log=None, # '/tmp/grab.log',
network_log=None, # '/tmp/grab.network.log',
level=logging.DEBUG, mode='a',
propagate_network_logger=False):
logging.basicConfig(level=level)
network_logger = logging.getLogger('grab.network')
network_logger.propagate = propagate_network_logger
if network_log:
hdl = logging.FileHandler(network_log, mode)
network_logger.addHandler(hdl)
network_logger.setLevel(level)
grab_logger = logging.getLogger('grab')
if grab_log:
hdl = logging.FileHandler(grab_log, mode)
grab_logger.addHandler(hdl)
grab_logger.setLevel(level) | [
"def",
"default_logging",
"(",
"grab_log",
"=",
"None",
",",
"# '/tmp/grab.log',",
"network_log",
"=",
"None",
",",
"# '/tmp/grab.network.log',",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"mode",
"=",
"'a'",
",",
"propagate_network_logger",
"=",
"False",
")",
... | Customize logging output to display all log messages
except grab network logs.
Redirect grab network logs into file. | [
"Customize",
"logging",
"output",
"to",
"display",
"all",
"log",
"messages",
"except",
"grab",
"network",
"logs",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/util/log.py#L7-L31 |
233,816 | lorien/grab | grab/script/crawl.py | save_list | def save_list(lst, path):
"""
Save items from list to the file.
"""
with open(path, 'wb') as out:
lines = []
for item in lst:
if isinstance(item, (six.text_type, six.binary_type)):
lines.append(make_str(item))
else:
lines.append(make_str(json.dumps(item)))
out.write(b'\n'.join(lines) + b'\n') | python | def save_list(lst, path):
with open(path, 'wb') as out:
lines = []
for item in lst:
if isinstance(item, (six.text_type, six.binary_type)):
lines.append(make_str(item))
else:
lines.append(make_str(json.dumps(item)))
out.write(b'\n'.join(lines) + b'\n') | [
"def",
"save_list",
"(",
"lst",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"out",
":",
"lines",
"=",
"[",
"]",
"for",
"item",
"in",
"lst",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"six",
".",
"text_type",
... | Save items from list to the file. | [
"Save",
"items",
"from",
"list",
"to",
"the",
"file",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/script/crawl.py#L57-L69 |
233,817 | lorien/grab | grab/proxylist.py | parse_proxy_line | def parse_proxy_line(line):
"""
Parse proxy details from the raw text line.
The text line could be in one of the following formats:
* host:port
* host:port:username:password
"""
line = line.strip()
match = RE_SIMPLE_PROXY.search(line)
if match:
return match.group(1), match.group(2), None, None
match = RE_AUTH_PROXY.search(line)
if match:
host, port, user, pwd = match.groups()
return host, port, user, pwd
raise InvalidProxyLine('Invalid proxy line: %s' % line) | python | def parse_proxy_line(line):
line = line.strip()
match = RE_SIMPLE_PROXY.search(line)
if match:
return match.group(1), match.group(2), None, None
match = RE_AUTH_PROXY.search(line)
if match:
host, port, user, pwd = match.groups()
return host, port, user, pwd
raise InvalidProxyLine('Invalid proxy line: %s' % line) | [
"def",
"parse_proxy_line",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"match",
"=",
"RE_SIMPLE_PROXY",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
... | Parse proxy details from the raw text line.
The text line could be in one of the following formats:
* host:port
* host:port:username:password | [
"Parse",
"proxy",
"details",
"from",
"the",
"raw",
"text",
"line",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L32-L51 |
233,818 | lorien/grab | grab/proxylist.py | parse_raw_list_data | def parse_raw_list_data(data, proxy_type='http', proxy_userpwd=None):
"""Iterate over proxy servers found in the raw data"""
if not isinstance(data, six.text_type):
data = data.decode('utf-8')
for orig_line in data.splitlines():
line = orig_line.strip().replace(' ', '')
if line and not line.startswith('#'):
try:
host, port, username, password = parse_proxy_line(line)
except InvalidProxyLine as ex:
logger.error(ex)
else:
if username is None and proxy_userpwd is not None:
username, password = proxy_userpwd.split(':')
yield Proxy(host, port, username, password, proxy_type) | python | def parse_raw_list_data(data, proxy_type='http', proxy_userpwd=None):
if not isinstance(data, six.text_type):
data = data.decode('utf-8')
for orig_line in data.splitlines():
line = orig_line.strip().replace(' ', '')
if line and not line.startswith('#'):
try:
host, port, username, password = parse_proxy_line(line)
except InvalidProxyLine as ex:
logger.error(ex)
else:
if username is None and proxy_userpwd is not None:
username, password = proxy_userpwd.split(':')
yield Proxy(host, port, username, password, proxy_type) | [
"def",
"parse_raw_list_data",
"(",
"data",
",",
"proxy_type",
"=",
"'http'",
",",
"proxy_userpwd",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
... | Iterate over proxy servers found in the raw data | [
"Iterate",
"over",
"proxy",
"servers",
"found",
"in",
"the",
"raw",
"data"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L54-L68 |
233,819 | lorien/grab | grab/proxylist.py | ProxyList.load | def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | python | def load(self):
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | [
"def",
"load",
"(",
"self",
")",
":",
"self",
".",
"_list",
"=",
"self",
".",
"_source",
".",
"load",
"(",
")",
"self",
".",
"_list_iter",
"=",
"itertools",
".",
"cycle",
"(",
"self",
".",
"_list",
")"
] | Load proxy list from configured proxy source | [
"Load",
"proxy",
"list",
"from",
"configured",
"proxy",
"source"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L156-L159 |
233,820 | lorien/grab | grab/proxylist.py | ProxyList.get_random_proxy | def get_random_proxy(self):
"""Return random proxy"""
idx = randint(0, len(self._list) - 1)
return self._list[idx] | python | def get_random_proxy(self):
idx = randint(0, len(self._list) - 1)
return self._list[idx] | [
"def",
"get_random_proxy",
"(",
"self",
")",
":",
"idx",
"=",
"randint",
"(",
"0",
",",
"len",
"(",
"self",
".",
"_list",
")",
"-",
"1",
")",
"return",
"self",
".",
"_list",
"[",
"idx",
"]"
] | Return random proxy | [
"Return",
"random",
"proxy"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L161-L164 |
233,821 | lorien/grab | grab/spider/task.py | Task.clone | def clone(self, **kwargs):
"""
Clone Task instance.
Reset network_try_count, increase task_try_count.
Reset priority attribute if it was not set explicitly.
"""
# First, create exact copy of the current Task object
attr_copy = self.__dict__.copy()
if attr_copy.get('grab_config') is not None:
del attr_copy['url']
if not attr_copy['priority_set_explicitly']:
attr_copy['priority'] = None
task = Task(**attr_copy)
# Reset some task properties if they have not
# been set explicitly in kwargs
if 'network_try_count' not in kwargs:
task.network_try_count = 0
if 'task_try_count' not in kwargs:
task.task_try_count = self.task_try_count + 1
if 'refresh_cache' not in kwargs:
task.refresh_cache = False
if 'disable_cache' not in kwargs:
task.disable_cache = False
if kwargs.get('url') is not None and kwargs.get('grab') is not None:
raise SpiderMisuseError('Options url and grab could not be '
'used together')
if (kwargs.get('url') is not None and
kwargs.get('grab_config') is not None):
raise SpiderMisuseError('Options url and grab_config could not '
'be used together')
if (kwargs.get('grab') is not None and
kwargs.get('grab_config') is not None):
raise SpiderMisuseError('Options grab and grab_config could not '
'be used together')
if kwargs.get('grab'):
task.setup_grab_config(kwargs['grab'].dump_config())
del kwargs['grab']
elif kwargs.get('grab_config'):
task.setup_grab_config(kwargs['grab_config'])
del kwargs['grab_config']
elif kwargs.get('url'):
task.url = kwargs['url']
if task.grab_config:
task.grab_config['url'] = kwargs['url']
del kwargs['url']
for key, value in kwargs.items():
setattr(task, key, value)
task.process_delay_option(None)
return task | python | def clone(self, **kwargs):
# First, create exact copy of the current Task object
attr_copy = self.__dict__.copy()
if attr_copy.get('grab_config') is not None:
del attr_copy['url']
if not attr_copy['priority_set_explicitly']:
attr_copy['priority'] = None
task = Task(**attr_copy)
# Reset some task properties if they have not
# been set explicitly in kwargs
if 'network_try_count' not in kwargs:
task.network_try_count = 0
if 'task_try_count' not in kwargs:
task.task_try_count = self.task_try_count + 1
if 'refresh_cache' not in kwargs:
task.refresh_cache = False
if 'disable_cache' not in kwargs:
task.disable_cache = False
if kwargs.get('url') is not None and kwargs.get('grab') is not None:
raise SpiderMisuseError('Options url and grab could not be '
'used together')
if (kwargs.get('url') is not None and
kwargs.get('grab_config') is not None):
raise SpiderMisuseError('Options url and grab_config could not '
'be used together')
if (kwargs.get('grab') is not None and
kwargs.get('grab_config') is not None):
raise SpiderMisuseError('Options grab and grab_config could not '
'be used together')
if kwargs.get('grab'):
task.setup_grab_config(kwargs['grab'].dump_config())
del kwargs['grab']
elif kwargs.get('grab_config'):
task.setup_grab_config(kwargs['grab_config'])
del kwargs['grab_config']
elif kwargs.get('url'):
task.url = kwargs['url']
if task.grab_config:
task.grab_config['url'] = kwargs['url']
del kwargs['url']
for key, value in kwargs.items():
setattr(task, key, value)
task.process_delay_option(None)
return task | [
"def",
"clone",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# First, create exact copy of the current Task object",
"attr_copy",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"if",
"attr_copy",
".",
"get",
"(",
"'grab_config'",
")",
"is",
"not",
... | Clone Task instance.
Reset network_try_count, increase task_try_count.
Reset priority attribute if it was not set explicitly. | [
"Clone",
"Task",
"instance",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/spider/task.py#L170-L228 |
233,822 | lorien/grab | grab/base.py | copy_config | def copy_config(config, mutable_config_keys=MUTABLE_CONFIG_KEYS):
"""
Copy grab config with correct handling of mutable config values.
"""
cloned_config = copy(config)
# Apply ``copy`` function to mutable config values
for key in mutable_config_keys:
cloned_config[key] = copy(config[key])
return cloned_config | python | def copy_config(config, mutable_config_keys=MUTABLE_CONFIG_KEYS):
cloned_config = copy(config)
# Apply ``copy`` function to mutable config values
for key in mutable_config_keys:
cloned_config[key] = copy(config[key])
return cloned_config | [
"def",
"copy_config",
"(",
"config",
",",
"mutable_config_keys",
"=",
"MUTABLE_CONFIG_KEYS",
")",
":",
"cloned_config",
"=",
"copy",
"(",
"config",
")",
"# Apply ``copy`` function to mutable config values",
"for",
"key",
"in",
"mutable_config_keys",
":",
"cloned_config",
... | Copy grab config with correct handling of mutable config values. | [
"Copy",
"grab",
"config",
"with",
"correct",
"handling",
"of",
"mutable",
"config",
"values",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L60-L69 |
233,823 | lorien/grab | grab/base.py | Grab.reset | def reset(self):
"""
Reset all attributes which could be modified during previous request
or which is not initialized yet if this is the new Grab instance.
This methods is automatically called before each network request.
"""
self.request_head = None
#self.request_log = None
self.request_body = None
self.request_method = None
self.request_counter = None
self.exception = None
if self.transport:
self.transport.reset() | python | def reset(self):
self.request_head = None
#self.request_log = None
self.request_body = None
self.request_method = None
self.request_counter = None
self.exception = None
if self.transport:
self.transport.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"request_head",
"=",
"None",
"#self.request_log = None",
"self",
".",
"request_body",
"=",
"None",
"self",
".",
"request_method",
"=",
"None",
"self",
".",
"request_counter",
"=",
"None",
"self",
".",
"exce... | Reset all attributes which could be modified during previous request
or which is not initialized yet if this is the new Grab instance.
This methods is automatically called before each network request. | [
"Reset",
"all",
"attributes",
"which",
"could",
"be",
"modified",
"during",
"previous",
"request",
"or",
"which",
"is",
"not",
"initialized",
"yet",
"if",
"this",
"is",
"the",
"new",
"Grab",
"instance",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L280-L295 |
233,824 | lorien/grab | grab/base.py | Grab.clone | def clone(self, **kwargs):
"""
Create clone of Grab instance.
Cloned instance will have the same state: cookies, referrer, response
document data
:param **kwargs: overrides settings of cloned grab instance
"""
grab = Grab(transport=self.transport_param)
grab.config = self.dump_config()
grab.doc = self.doc.copy()
#grab.doc.grab = weakref.proxy(grab)
for key in self.clonable_attributes:
setattr(grab, key, getattr(self, key))
grab.cookies = deepcopy(self.cookies)
if kwargs:
grab.setup(**kwargs)
return grab | python | def clone(self, **kwargs):
grab = Grab(transport=self.transport_param)
grab.config = self.dump_config()
grab.doc = self.doc.copy()
#grab.doc.grab = weakref.proxy(grab)
for key in self.clonable_attributes:
setattr(grab, key, getattr(self, key))
grab.cookies = deepcopy(self.cookies)
if kwargs:
grab.setup(**kwargs)
return grab | [
"def",
"clone",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"grab",
"=",
"Grab",
"(",
"transport",
"=",
"self",
".",
"transport_param",
")",
"grab",
".",
"config",
"=",
"self",
".",
"dump_config",
"(",
")",
"grab",
".",
"doc",
"=",
"self",
".",... | Create clone of Grab instance.
Cloned instance will have the same state: cookies, referrer, response
document data
:param **kwargs: overrides settings of cloned grab instance | [
"Create",
"clone",
"of",
"Grab",
"instance",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L297-L320 |
233,825 | lorien/grab | grab/base.py | Grab.adopt | def adopt(self, grab):
"""
Copy the state of another `Grab` instance.
Use case: create backup of current state to the cloned instance and
then restore the state from it.
"""
self.load_config(grab.config)
self.doc = grab.doc.copy(new_grab=self)
for key in self.clonable_attributes:
setattr(self, key, getattr(grab, key))
self.cookies = deepcopy(grab.cookies) | python | def adopt(self, grab):
self.load_config(grab.config)
self.doc = grab.doc.copy(new_grab=self)
for key in self.clonable_attributes:
setattr(self, key, getattr(grab, key))
self.cookies = deepcopy(grab.cookies) | [
"def",
"adopt",
"(",
"self",
",",
"grab",
")",
":",
"self",
".",
"load_config",
"(",
"grab",
".",
"config",
")",
"self",
".",
"doc",
"=",
"grab",
".",
"doc",
".",
"copy",
"(",
"new_grab",
"=",
"self",
")",
"for",
"key",
"in",
"self",
".",
"clonab... | Copy the state of another `Grab` instance.
Use case: create backup of current state to the cloned instance and
then restore the state from it. | [
"Copy",
"the",
"state",
"of",
"another",
"Grab",
"instance",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L322-L336 |
233,826 | lorien/grab | grab/base.py | Grab.dump_config | def dump_config(self):
"""
Make clone of current config.
"""
conf = copy_config(self.config, self.mutable_config_keys)
conf['state'] = {
'cookiejar_cookies': list(self.cookies.cookiejar),
}
return conf | python | def dump_config(self):
conf = copy_config(self.config, self.mutable_config_keys)
conf['state'] = {
'cookiejar_cookies': list(self.cookies.cookiejar),
}
return conf | [
"def",
"dump_config",
"(",
"self",
")",
":",
"conf",
"=",
"copy_config",
"(",
"self",
".",
"config",
",",
"self",
".",
"mutable_config_keys",
")",
"conf",
"[",
"'state'",
"]",
"=",
"{",
"'cookiejar_cookies'",
":",
"list",
"(",
"self",
".",
"cookies",
"."... | Make clone of current config. | [
"Make",
"clone",
"of",
"current",
"config",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L338-L347 |
233,827 | lorien/grab | grab/base.py | Grab.load_config | def load_config(self, config):
"""
Configure grab instance with external config object.
"""
self.config = copy_config(config, self.mutable_config_keys)
if 'cookiejar_cookies' in config['state']:
self.cookies = CookieManager.from_cookie_list(
config['state']['cookiejar_cookies']) | python | def load_config(self, config):
self.config = copy_config(config, self.mutable_config_keys)
if 'cookiejar_cookies' in config['state']:
self.cookies = CookieManager.from_cookie_list(
config['state']['cookiejar_cookies']) | [
"def",
"load_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"copy_config",
"(",
"config",
",",
"self",
".",
"mutable_config_keys",
")",
"if",
"'cookiejar_cookies'",
"in",
"config",
"[",
"'state'",
"]",
":",
"self",
".",
"cookies... | Configure grab instance with external config object. | [
"Configure",
"grab",
"instance",
"with",
"external",
"config",
"object",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L349-L357 |
233,828 | lorien/grab | grab/base.py | Grab.setup | def setup(self, **kwargs):
"""
Setting up Grab instance configuration.
"""
for key in kwargs:
if key not in self.config.keys():
raise error.GrabMisuseError('Unknown option: %s' % key)
if 'url' in kwargs:
if self.config.get('url'):
kwargs['url'] = self.make_url_absolute(kwargs['url'])
self.config.update(kwargs) | python | def setup(self, **kwargs):
for key in kwargs:
if key not in self.config.keys():
raise error.GrabMisuseError('Unknown option: %s' % key)
if 'url' in kwargs:
if self.config.get('url'):
kwargs['url'] = self.make_url_absolute(kwargs['url'])
self.config.update(kwargs) | [
"def",
"setup",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"not",
"in",
"self",
".",
"config",
".",
"keys",
"(",
")",
":",
"raise",
"error",
".",
"GrabMisuseError",
"(",
"'Unknown option: %s'",
"%"... | Setting up Grab instance configuration. | [
"Setting",
"up",
"Grab",
"instance",
"configuration",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L359-L371 |
233,829 | lorien/grab | grab/base.py | Grab.download | def download(self, url, location, **kwargs):
"""
Fetch document located at ``url`` and save to to ``location``.
"""
doc = self.go(url, **kwargs)
with open(location, 'wb') as out:
out.write(doc.body)
return len(doc.body) | python | def download(self, url, location, **kwargs):
doc = self.go(url, **kwargs)
with open(location, 'wb') as out:
out.write(doc.body)
return len(doc.body) | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"location",
",",
"*",
"*",
"kwargs",
")",
":",
"doc",
"=",
"self",
".",
"go",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"with",
"open",
"(",
"location",
",",
"'wb'",
")",
"as",
"out",
":",
"out",... | Fetch document located at ``url`` and save to to ``location``. | [
"Fetch",
"document",
"located",
"at",
"url",
"and",
"save",
"to",
"to",
"location",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L384-L392 |
233,830 | lorien/grab | grab/base.py | Grab.prepare_request | def prepare_request(self, **kwargs):
"""
Configure all things to make real network request.
This method is called before doing real request via
transport extension.
"""
if self.transport is None:
self.setup_transport(self.transport_param)
self.reset()
self.request_counter = next(REQUEST_COUNTER)
if kwargs:
self.setup(**kwargs)
if self.proxylist.size() and self.config['proxy_auto_change']:
self.change_proxy()
self.request_method = self.detect_request_method()
self.transport.process_config(self) | python | def prepare_request(self, **kwargs):
if self.transport is None:
self.setup_transport(self.transport_param)
self.reset()
self.request_counter = next(REQUEST_COUNTER)
if kwargs:
self.setup(**kwargs)
if self.proxylist.size() and self.config['proxy_auto_change']:
self.change_proxy()
self.request_method = self.detect_request_method()
self.transport.process_config(self) | [
"def",
"prepare_request",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"transport",
"is",
"None",
":",
"self",
".",
"setup_transport",
"(",
"self",
".",
"transport_param",
")",
"self",
".",
"reset",
"(",
")",
"self",
".",
"request... | Configure all things to make real network request.
This method is called before doing real request via
transport extension. | [
"Configure",
"all",
"things",
"to",
"make",
"real",
"network",
"request",
".",
"This",
"method",
"is",
"called",
"before",
"doing",
"real",
"request",
"via",
"transport",
"extension",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L394-L410 |
233,831 | lorien/grab | grab/base.py | Grab.log_request | def log_request(self, extra=''):
"""
Send request details to logging system.
"""
# pylint: disable=no-member
thread_name = threading.currentThread().getName().lower()
# pylint: enable=no-member
if thread_name == 'mainthread':
thread_name = ''
else:
thread_name = '-%s' % thread_name
if self.config['proxy']:
if self.config['proxy_userpwd']:
auth = ' with authorization'
else:
auth = ''
proxy_info = ' via %s proxy of type %s%s' % (
self.config['proxy'], self.config['proxy_type'], auth)
else:
proxy_info = ''
if extra:
extra = '[%s] ' % extra
logger_network.debug(
'[%s%s] %s%s %s%s',
('%02d' % self.request_counter
if self.request_counter is not None else 'NA'),
thread_name,
extra, self.request_method or 'GET',
self.config['url'], proxy_info) | python | def log_request(self, extra=''):
# pylint: disable=no-member
thread_name = threading.currentThread().getName().lower()
# pylint: enable=no-member
if thread_name == 'mainthread':
thread_name = ''
else:
thread_name = '-%s' % thread_name
if self.config['proxy']:
if self.config['proxy_userpwd']:
auth = ' with authorization'
else:
auth = ''
proxy_info = ' via %s proxy of type %s%s' % (
self.config['proxy'], self.config['proxy_type'], auth)
else:
proxy_info = ''
if extra:
extra = '[%s] ' % extra
logger_network.debug(
'[%s%s] %s%s %s%s',
('%02d' % self.request_counter
if self.request_counter is not None else 'NA'),
thread_name,
extra, self.request_method or 'GET',
self.config['url'], proxy_info) | [
"def",
"log_request",
"(",
"self",
",",
"extra",
"=",
"''",
")",
":",
"# pylint: disable=no-member",
"thread_name",
"=",
"threading",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
".",
"lower",
"(",
")",
"# pylint: enable=no-member",
"if",
"thread_... | Send request details to logging system. | [
"Send",
"request",
"details",
"to",
"logging",
"system",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L412-L442 |
233,832 | lorien/grab | grab/base.py | Grab.request | def request(self, **kwargs):
"""
Perform network request.
You can specify grab settings in ``**kwargs``.
Any keyword argument will be passed to ``self.config``.
Returns: ``Document`` objects.
"""
self.prepare_request(**kwargs)
refresh_count = 0
while True:
self.log_request()
try:
self.transport.request()
except error.GrabError as ex:
self.exception = ex
self.reset_temporary_options()
if self.config['log_dir']:
self.save_failed_dump()
raise
else:
doc = self.process_request_result()
if self.config['follow_location']:
if doc.code in (301, 302, 303, 307, 308):
if doc.headers.get('Location'):
refresh_count += 1
if refresh_count > self.config['redirect_limit']:
raise error.GrabTooManyRedirectsError()
else:
url = doc.headers.get('Location')
self.prepare_request(
url=self.make_url_absolute(url),
referer=None)
continue
if self.config['follow_refresh']:
refresh_url = self.doc.get_meta_refresh_url()
if refresh_url is not None:
refresh_count += 1
if refresh_count > self.config['redirect_limit']:
raise error.GrabTooManyRedirectsError()
else:
self.prepare_request(
url=self.make_url_absolute(refresh_url),
referer=None)
continue
return doc | python | def request(self, **kwargs):
self.prepare_request(**kwargs)
refresh_count = 0
while True:
self.log_request()
try:
self.transport.request()
except error.GrabError as ex:
self.exception = ex
self.reset_temporary_options()
if self.config['log_dir']:
self.save_failed_dump()
raise
else:
doc = self.process_request_result()
if self.config['follow_location']:
if doc.code in (301, 302, 303, 307, 308):
if doc.headers.get('Location'):
refresh_count += 1
if refresh_count > self.config['redirect_limit']:
raise error.GrabTooManyRedirectsError()
else:
url = doc.headers.get('Location')
self.prepare_request(
url=self.make_url_absolute(url),
referer=None)
continue
if self.config['follow_refresh']:
refresh_url = self.doc.get_meta_refresh_url()
if refresh_url is not None:
refresh_count += 1
if refresh_count > self.config['redirect_limit']:
raise error.GrabTooManyRedirectsError()
else:
self.prepare_request(
url=self.make_url_absolute(refresh_url),
referer=None)
continue
return doc | [
"def",
"request",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"prepare_request",
"(",
"*",
"*",
"kwargs",
")",
"refresh_count",
"=",
"0",
"while",
"True",
":",
"self",
".",
"log_request",
"(",
")",
"try",
":",
"self",
".",
"transport... | Perform network request.
You can specify grab settings in ``**kwargs``.
Any keyword argument will be passed to ``self.config``.
Returns: ``Document`` objects. | [
"Perform",
"network",
"request",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L444-L495 |
233,833 | lorien/grab | grab/base.py | Grab.submit | def submit(self, make_request=True, **kwargs):
"""
Submit current form.
:param make_request: if `False` then grab instance will be
configured with form post data but request will not be
performed
For details see `Document.submit()` method
Example::
# Assume that we going to some page with some form
g.go('some url')
# Fill some fields
g.doc.set_input('username', 'bob')
g.doc.set_input('pwd', '123')
# Submit the form
g.submit()
# or we can just fill the form
# and do manual submission
g.doc.set_input('foo', 'bar')
g.submit(make_request=False)
g.request()
# for multipart forms we can specify files
from grab import UploadFile
g.doc.set_input('img', UploadFile('/path/to/image.png'))
g.submit()
"""
result = self.doc.get_form_request(**kwargs)
if result['multipart_post']:
self.setup(multipart_post=result['multipart_post'])
if result['post']:
self.setup(post=result['post'])
if result['url']:
self.setup(url=result['url'])
if make_request:
return self.request()
else:
return None | python | def submit(self, make_request=True, **kwargs):
result = self.doc.get_form_request(**kwargs)
if result['multipart_post']:
self.setup(multipart_post=result['multipart_post'])
if result['post']:
self.setup(post=result['post'])
if result['url']:
self.setup(url=result['url'])
if make_request:
return self.request()
else:
return None | [
"def",
"submit",
"(",
"self",
",",
"make_request",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"doc",
".",
"get_form_request",
"(",
"*",
"*",
"kwargs",
")",
"if",
"result",
"[",
"'multipart_post'",
"]",
":",
"self",
".... | Submit current form.
:param make_request: if `False` then grab instance will be
configured with form post data but request will not be
performed
For details see `Document.submit()` method
Example::
# Assume that we going to some page with some form
g.go('some url')
# Fill some fields
g.doc.set_input('username', 'bob')
g.doc.set_input('pwd', '123')
# Submit the form
g.submit()
# or we can just fill the form
# and do manual submission
g.doc.set_input('foo', 'bar')
g.submit(make_request=False)
g.request()
# for multipart forms we can specify files
from grab import UploadFile
g.doc.set_input('img', UploadFile('/path/to/image.png'))
g.submit() | [
"Submit",
"current",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L497-L538 |
233,834 | lorien/grab | grab/base.py | Grab.process_request_result | def process_request_result(self, prepare_response_func=None):
"""
Process result of real request performed via transport extension.
"""
now = datetime.utcnow()
# TODO: move into separate method
if self.config['debug_post']:
post = self.config['post'] or self.config['multipart_post']
if isinstance(post, dict):
post = list(post.items())
if post:
if isinstance(post, six.string_types):
post = make_str(post[:self.config['debug_post_limit']],
errors='ignore') + b'...'
else:
items = normalize_http_values(
post, charset=self.config['charset'])
new_items = []
for key, value in items:
if len(value) > self.config['debug_post_limit']:
value = value[
:self.config['debug_post_limit']] + b'...'
else:
value = value
new_items.append((key, value))
post = '\n'.join('%-25s: %s' % x for x in new_items)
if post:
logger_network.debug('[%02d] POST request:\n%s\n',
self.request_counter, post)
# It's important to delete old POST data after request is performed.
# If POST data is not cleared then next request will try to use them
# again!
self.reset_temporary_options()
if prepare_response_func:
self.doc = prepare_response_func(self.transport, self)
else:
self.doc = self.transport.prepare_response(self)
self.doc.process_grab(self)
if self.config['reuse_cookies']:
self.cookies.update(self.doc.cookies)
self.doc.timestamp = now
self.config['charset'] = self.doc.charset
if self.config['log_file']:
with open(self.config['log_file'], 'wb') as out:
out.write(self.doc.body)
if self.config['cookiefile']:
self.cookies.save_to_file(self.config['cookiefile'])
if self.config['reuse_referer']:
self.config['referer'] = self.doc.url
self.copy_request_data()
# Should be called after `copy_request_data`
if self.config['log_dir']:
self.save_dumps()
return self.doc | python | def process_request_result(self, prepare_response_func=None):
now = datetime.utcnow()
# TODO: move into separate method
if self.config['debug_post']:
post = self.config['post'] or self.config['multipart_post']
if isinstance(post, dict):
post = list(post.items())
if post:
if isinstance(post, six.string_types):
post = make_str(post[:self.config['debug_post_limit']],
errors='ignore') + b'...'
else:
items = normalize_http_values(
post, charset=self.config['charset'])
new_items = []
for key, value in items:
if len(value) > self.config['debug_post_limit']:
value = value[
:self.config['debug_post_limit']] + b'...'
else:
value = value
new_items.append((key, value))
post = '\n'.join('%-25s: %s' % x for x in new_items)
if post:
logger_network.debug('[%02d] POST request:\n%s\n',
self.request_counter, post)
# It's important to delete old POST data after request is performed.
# If POST data is not cleared then next request will try to use them
# again!
self.reset_temporary_options()
if prepare_response_func:
self.doc = prepare_response_func(self.transport, self)
else:
self.doc = self.transport.prepare_response(self)
self.doc.process_grab(self)
if self.config['reuse_cookies']:
self.cookies.update(self.doc.cookies)
self.doc.timestamp = now
self.config['charset'] = self.doc.charset
if self.config['log_file']:
with open(self.config['log_file'], 'wb') as out:
out.write(self.doc.body)
if self.config['cookiefile']:
self.cookies.save_to_file(self.config['cookiefile'])
if self.config['reuse_referer']:
self.config['referer'] = self.doc.url
self.copy_request_data()
# Should be called after `copy_request_data`
if self.config['log_dir']:
self.save_dumps()
return self.doc | [
"def",
"process_request_result",
"(",
"self",
",",
"prepare_response_func",
"=",
"None",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# TODO: move into separate method",
"if",
"self",
".",
"config",
"[",
"'debug_post'",
"]",
":",
"post",
"=",
"s... | Process result of real request performed via transport extension. | [
"Process",
"result",
"of",
"real",
"request",
"performed",
"via",
"transport",
"extension",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L540-L606 |
233,835 | lorien/grab | grab/base.py | Grab.save_failed_dump | def save_failed_dump(self):
"""
Save dump of failed request for debugging.
This method is called then fatal network exception is raised.
The saved dump could be used for debugging the reason of the failure.
"""
# try/except for safety, to not break live spiders
try:
# FIXME
if (self.transport.__class__.__name__ == 'Urllib3Transport'
and not getattr(self.transport, '_response', None)):
self.doc = None
else:
self.doc = self.transport.prepare_response(self)
self.copy_request_data()
self.save_dumps()
except Exception as ex: # pylint: disable=broad-except
logger.error('', exc_info=ex) | python | def save_failed_dump(self):
# try/except for safety, to not break live spiders
try:
# FIXME
if (self.transport.__class__.__name__ == 'Urllib3Transport'
and not getattr(self.transport, '_response', None)):
self.doc = None
else:
self.doc = self.transport.prepare_response(self)
self.copy_request_data()
self.save_dumps()
except Exception as ex: # pylint: disable=broad-except
logger.error('', exc_info=ex) | [
"def",
"save_failed_dump",
"(",
"self",
")",
":",
"# try/except for safety, to not break live spiders",
"try",
":",
"# FIXME",
"if",
"(",
"self",
".",
"transport",
".",
"__class__",
".",
"__name__",
"==",
"'Urllib3Transport'",
"and",
"not",
"getattr",
"(",
"self",
... | Save dump of failed request for debugging.
This method is called then fatal network exception is raised.
The saved dump could be used for debugging the reason of the failure. | [
"Save",
"dump",
"of",
"failed",
"request",
"for",
"debugging",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L614-L633 |
233,836 | lorien/grab | grab/base.py | Grab.setup_document | def setup_document(self, content, **kwargs):
"""
Setup `response` object without real network requests.
Useful for testing and debuging.
All ``**kwargs`` will be passed to `Document` constructor.
"""
self.reset()
if isinstance(content, six.text_type):
raise error.GrabMisuseError('Method `setup_document` accepts only '
'byte string in `content` argument.')
# Configure Document instance
doc = Document(grab=self)
doc.body = content
doc.status = ''
doc.head = b'HTTP/1.1 200 OK\r\n\r\n'
doc.parse(charset=kwargs.get('document_charset'))
doc.code = 200
doc.total_time = 0
doc.connect_time = 0
doc.name_lookup_time = 0
doc.url = ''
for key, value in kwargs.items():
setattr(doc, key, value)
self.doc = doc | python | def setup_document(self, content, **kwargs):
self.reset()
if isinstance(content, six.text_type):
raise error.GrabMisuseError('Method `setup_document` accepts only '
'byte string in `content` argument.')
# Configure Document instance
doc = Document(grab=self)
doc.body = content
doc.status = ''
doc.head = b'HTTP/1.1 200 OK\r\n\r\n'
doc.parse(charset=kwargs.get('document_charset'))
doc.code = 200
doc.total_time = 0
doc.connect_time = 0
doc.name_lookup_time = 0
doc.url = ''
for key, value in kwargs.items():
setattr(doc, key, value)
self.doc = doc | [
"def",
"setup_document",
"(",
"self",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"reset",
"(",
")",
"if",
"isinstance",
"(",
"content",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"error",
".",
"GrabMisuseError",
"(",
"'Method... | Setup `response` object without real network requests.
Useful for testing and debuging.
All ``**kwargs`` will be passed to `Document` constructor. | [
"Setup",
"response",
"object",
"without",
"real",
"network",
"requests",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L641-L670 |
233,837 | lorien/grab | grab/base.py | Grab.change_proxy | def change_proxy(self, random=True):
"""
Set random proxy from proxylist.
"""
if self.proxylist.size():
if random:
proxy = self.proxylist.get_random_proxy()
else:
proxy = self.proxylist.get_next_proxy()
self.setup(proxy=proxy.get_address(),
proxy_userpwd=proxy.get_userpwd(),
proxy_type=proxy.proxy_type)
else:
logger.debug('Proxy list is empty') | python | def change_proxy(self, random=True):
if self.proxylist.size():
if random:
proxy = self.proxylist.get_random_proxy()
else:
proxy = self.proxylist.get_next_proxy()
self.setup(proxy=proxy.get_address(),
proxy_userpwd=proxy.get_userpwd(),
proxy_type=proxy.proxy_type)
else:
logger.debug('Proxy list is empty') | [
"def",
"change_proxy",
"(",
"self",
",",
"random",
"=",
"True",
")",
":",
"if",
"self",
".",
"proxylist",
".",
"size",
"(",
")",
":",
"if",
"random",
":",
"proxy",
"=",
"self",
".",
"proxylist",
".",
"get_random_proxy",
"(",
")",
"else",
":",
"proxy"... | Set random proxy from proxylist. | [
"Set",
"random",
"proxy",
"from",
"proxylist",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L672-L686 |
233,838 | lorien/grab | grab/base.py | Grab.make_url_absolute | def make_url_absolute(self, url, resolve_base=False):
"""
Make url absolute using previous request url as base url.
"""
if self.config['url']:
if resolve_base:
ubody = self.doc.unicode_body()
base_url = find_base_url(ubody)
if base_url:
return urljoin(base_url, url)
return urljoin(self.config['url'], url)
else:
return url | python | def make_url_absolute(self, url, resolve_base=False):
if self.config['url']:
if resolve_base:
ubody = self.doc.unicode_body()
base_url = find_base_url(ubody)
if base_url:
return urljoin(base_url, url)
return urljoin(self.config['url'], url)
else:
return url | [
"def",
"make_url_absolute",
"(",
"self",
",",
"url",
",",
"resolve_base",
"=",
"False",
")",
":",
"if",
"self",
".",
"config",
"[",
"'url'",
"]",
":",
"if",
"resolve_base",
":",
"ubody",
"=",
"self",
".",
"doc",
".",
"unicode_body",
"(",
")",
"base_url... | Make url absolute using previous request url as base url. | [
"Make",
"url",
"absolute",
"using",
"previous",
"request",
"url",
"as",
"base",
"url",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L734-L747 |
233,839 | lorien/grab | grab/base.py | Grab.detect_request_method | def detect_request_method(self):
"""
Analyze request config and find which
request method will be used.
Returns request method in upper case
This method needs simetime when `process_config` method
was not called yet.
"""
method = self.config['method']
if method:
method = method.upper()
else:
if self.config['post'] or self.config['multipart_post']:
method = 'POST'
else:
method = 'GET'
return method | python | def detect_request_method(self):
method = self.config['method']
if method:
method = method.upper()
else:
if self.config['post'] or self.config['multipart_post']:
method = 'POST'
else:
method = 'GET'
return method | [
"def",
"detect_request_method",
"(",
"self",
")",
":",
"method",
"=",
"self",
".",
"config",
"[",
"'method'",
"]",
"if",
"method",
":",
"method",
"=",
"method",
".",
"upper",
"(",
")",
"else",
":",
"if",
"self",
".",
"config",
"[",
"'post'",
"]",
"or... | Analyze request config and find which
request method will be used.
Returns request method in upper case
This method needs simetime when `process_config` method
was not called yet. | [
"Analyze",
"request",
"config",
"and",
"find",
"which",
"request",
"method",
"will",
"be",
"used",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L749-L768 |
233,840 | lorien/grab | grab/cookie.py | create_cookie | def create_cookie(name, value, domain, httponly=None, **kwargs):
"""Creates `cookielib.Cookie` instance"""
if domain == 'localhost':
domain = ''
config = dict(
name=name,
value=value,
version=0,
port=None,
domain=domain,
path='/',
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rfc2109=False,
rest={'HttpOnly': httponly},
)
for key in kwargs:
if key not in config:
raise GrabMisuseError('Function `create_cookie` does not accept '
'`%s` argument' % key)
config.update(**kwargs)
config['rest']['HttpOnly'] = httponly
config['port_specified'] = bool(config['port'])
config['domain_specified'] = bool(config['domain'])
config['domain_initial_dot'] = (config['domain'] or '').startswith('.')
config['path_specified'] = bool(config['path'])
return Cookie(**config) | python | def create_cookie(name, value, domain, httponly=None, **kwargs):
if domain == 'localhost':
domain = ''
config = dict(
name=name,
value=value,
version=0,
port=None,
domain=domain,
path='/',
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rfc2109=False,
rest={'HttpOnly': httponly},
)
for key in kwargs:
if key not in config:
raise GrabMisuseError('Function `create_cookie` does not accept '
'`%s` argument' % key)
config.update(**kwargs)
config['rest']['HttpOnly'] = httponly
config['port_specified'] = bool(config['port'])
config['domain_specified'] = bool(config['domain'])
config['domain_initial_dot'] = (config['domain'] or '').startswith('.')
config['path_specified'] = bool(config['path'])
return Cookie(**config) | [
"def",
"create_cookie",
"(",
"name",
",",
"value",
",",
"domain",
",",
"httponly",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"domain",
"==",
"'localhost'",
":",
"domain",
"=",
"''",
"config",
"=",
"dict",
"(",
"name",
"=",
"name",
",",
... | Creates `cookielib.Cookie` instance | [
"Creates",
"cookielib",
".",
"Cookie",
"instance"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L118-L152 |
233,841 | lorien/grab | grab/cookie.py | CookieManager.set | def set(self, name, value, domain, **kwargs):
"""Add new cookie or replace existing cookie with same parameters.
:param name: name of cookie
:param value: value of cookie
:param kwargs: extra attributes of cookie
"""
if domain == 'localhost':
domain = ''
self.cookiejar.set_cookie(create_cookie(name, value, domain, **kwargs)) | python | def set(self, name, value, domain, **kwargs):
if domain == 'localhost':
domain = ''
self.cookiejar.set_cookie(create_cookie(name, value, domain, **kwargs)) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"domain",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"domain",
"==",
"'localhost'",
":",
"domain",
"=",
"''",
"self",
".",
"cookiejar",
".",
"set_cookie",
"(",
"create_cookie",
"(",
"name",
","... | Add new cookie or replace existing cookie with same parameters.
:param name: name of cookie
:param value: value of cookie
:param kwargs: extra attributes of cookie | [
"Add",
"new",
"cookie",
"or",
"replace",
"existing",
"cookie",
"with",
"same",
"parameters",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L176-L187 |
233,842 | lorien/grab | grab/cookie.py | CookieManager.load_from_file | def load_from_file(self, path):
"""
Load cookies from the file.
Content of file should be a JSON-serialized list of dicts.
"""
with open(path) as inf:
data = inf.read()
if data:
items = json.loads(data)
else:
items = {}
for item in items:
extra = dict((x, y) for x, y in item.items()
if x not in ['name', 'value', 'domain'])
self.set(item['name'], item['value'], item['domain'], **extra) | python | def load_from_file(self, path):
with open(path) as inf:
data = inf.read()
if data:
items = json.loads(data)
else:
items = {}
for item in items:
extra = dict((x, y) for x, y in item.items()
if x not in ['name', 'value', 'domain'])
self.set(item['name'], item['value'], item['domain'], **extra) | [
"def",
"load_from_file",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"inf",
":",
"data",
"=",
"inf",
".",
"read",
"(",
")",
"if",
"data",
":",
"items",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"else",
":",
"i... | Load cookies from the file.
Content of file should be a JSON-serialized list of dicts. | [
"Load",
"cookies",
"from",
"the",
"file",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L245-L261 |
233,843 | lorien/grab | grab/cookie.py | CookieManager.save_to_file | def save_to_file(self, path):
"""
Dump all cookies to file.
Cookies are dumped as JSON-serialized dict of keys and values.
"""
with open(path, 'w') as out:
out.write(json.dumps(self.get_dict())) | python | def save_to_file(self, path):
with open(path, 'w') as out:
out.write(json.dumps(self.get_dict())) | [
"def",
"save_to_file",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"out",
":",
"out",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"get_dict",
"(",
")",
")",
")"
] | Dump all cookies to file.
Cookies are dumped as JSON-serialized dict of keys and values. | [
"Dump",
"all",
"cookies",
"to",
"file",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L269-L277 |
233,844 | lorien/grab | grab/spider/task_dispatcher_service.py | TaskDispatcherService.process_service_result | def process_service_result(self, result, task, meta=None):
"""
Process result submitted from any service to task dispatcher service.
Result could be:
* Task
* None
* Task instance
* ResponseNotValid-based exception
* Arbitrary exception
* Network response:
{ok, ecode, emsg, error_abbr, exc, grab, grab_config_backup}
Exception can come only from parser_service and it always has
meta {"from": "parser", "exc_info": <...>}
"""
if meta is None:
meta = {}
if isinstance(result, Task):
if meta.get('source') == 'cache_reader':
self.spider.add_task(result, queue=self.spider.task_queue)
else:
self.spider.add_task(result)
elif result is None:
pass
elif isinstance(result, ResponseNotValid):
self.spider.add_task(task.clone(refresh_cache=True))
error_code = result.__class__.__name__.replace('_', '-')
self.spider.stat.inc('integrity:%s' % error_code)
elif isinstance(result, Exception):
if task:
handler = self.spider.find_task_handler(task)
handler_name = getattr(handler, '__name__', 'NONE')
else:
handler_name = 'NA'
self.spider.process_parser_error(
handler_name, task, meta['exc_info'],
)
if isinstance(result, FatalError):
self.spider.fatal_error_queue.put(meta['exc_info'])
elif isinstance(result, dict) and 'grab' in result:
if (self.spider.cache_writer_service
and not result.get('from_cache')
and result['ok']):
self.spider.cache_writer_service.input_queue.put(
(task, result['grab'])
)
# TODO: Move to network service
# starts
self.spider.log_network_result_stats(result, task)
# ends
is_valid = False
if task.get('raw'):
is_valid = True
elif result['ok']:
res_code = result['grab'].doc.code
is_valid = self.spider.is_valid_network_response_code(
res_code, task
)
if is_valid:
self.spider.parser_service.input_queue.put((result, task))
else:
self.spider.log_failed_network_result(result)
# Try to do network request one more time
# TODO:
# Implement valid_try_limit
# Use it if request failed not because of network error
# But because of content integrity check
if self.spider.network_try_limit > 0:
task.refresh_cache = True
task.setup_grab_config(
result['grab_config_backup'])
self.spider.add_task(task)
if result.get('from_cache'):
self.spider.stat.inc('spider:task-%s-cache'
% task.name)
self.spider.stat.inc('spider:request')
else:
raise SpiderError('Unknown result received from a service: %s'
% result) | python | def process_service_result(self, result, task, meta=None):
if meta is None:
meta = {}
if isinstance(result, Task):
if meta.get('source') == 'cache_reader':
self.spider.add_task(result, queue=self.spider.task_queue)
else:
self.spider.add_task(result)
elif result is None:
pass
elif isinstance(result, ResponseNotValid):
self.spider.add_task(task.clone(refresh_cache=True))
error_code = result.__class__.__name__.replace('_', '-')
self.spider.stat.inc('integrity:%s' % error_code)
elif isinstance(result, Exception):
if task:
handler = self.spider.find_task_handler(task)
handler_name = getattr(handler, '__name__', 'NONE')
else:
handler_name = 'NA'
self.spider.process_parser_error(
handler_name, task, meta['exc_info'],
)
if isinstance(result, FatalError):
self.spider.fatal_error_queue.put(meta['exc_info'])
elif isinstance(result, dict) and 'grab' in result:
if (self.spider.cache_writer_service
and not result.get('from_cache')
and result['ok']):
self.spider.cache_writer_service.input_queue.put(
(task, result['grab'])
)
# TODO: Move to network service
# starts
self.spider.log_network_result_stats(result, task)
# ends
is_valid = False
if task.get('raw'):
is_valid = True
elif result['ok']:
res_code = result['grab'].doc.code
is_valid = self.spider.is_valid_network_response_code(
res_code, task
)
if is_valid:
self.spider.parser_service.input_queue.put((result, task))
else:
self.spider.log_failed_network_result(result)
# Try to do network request one more time
# TODO:
# Implement valid_try_limit
# Use it if request failed not because of network error
# But because of content integrity check
if self.spider.network_try_limit > 0:
task.refresh_cache = True
task.setup_grab_config(
result['grab_config_backup'])
self.spider.add_task(task)
if result.get('from_cache'):
self.spider.stat.inc('spider:task-%s-cache'
% task.name)
self.spider.stat.inc('spider:request')
else:
raise SpiderError('Unknown result received from a service: %s'
% result) | [
"def",
"process_service_result",
"(",
"self",
",",
"result",
",",
"task",
",",
"meta",
"=",
"None",
")",
":",
"if",
"meta",
"is",
"None",
":",
"meta",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"result",
",",
"Task",
")",
":",
"if",
"meta",
".",
"get"... | Process result submitted from any service to task dispatcher service.
Result could be:
* Task
* None
* Task instance
* ResponseNotValid-based exception
* Arbitrary exception
* Network response:
{ok, ecode, emsg, error_abbr, exc, grab, grab_config_backup}
Exception can come only from parser_service and it always has
meta {"from": "parser", "exc_info": <...>} | [
"Process",
"result",
"submitted",
"from",
"any",
"service",
"to",
"task",
"dispatcher",
"service",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/spider/task_dispatcher_service.py#L29-L109 |
233,845 | lorien/grab | grab/deprecated.py | DeprecatedThings.find_link | def find_link(self, href_pattern, make_absolute=True):
"""
Find link in response body which href value matches ``href_pattern``.
Returns found url or None.
"""
if make_absolute:
self.tree.make_links_absolute(self.doc.url)
if isinstance(href_pattern, six.text_type):
raise GrabMisuseError('Method `find_link` accepts only '
'byte-string argument')
href_pattern = make_unicode(href_pattern)
for elem, _, link, _ in self.tree.iterlinks():
if elem.tag == 'a' and href_pattern in link:
return link
return None | python | def find_link(self, href_pattern, make_absolute=True):
if make_absolute:
self.tree.make_links_absolute(self.doc.url)
if isinstance(href_pattern, six.text_type):
raise GrabMisuseError('Method `find_link` accepts only '
'byte-string argument')
href_pattern = make_unicode(href_pattern)
for elem, _, link, _ in self.tree.iterlinks():
if elem.tag == 'a' and href_pattern in link:
return link
return None | [
"def",
"find_link",
"(",
"self",
",",
"href_pattern",
",",
"make_absolute",
"=",
"True",
")",
":",
"if",
"make_absolute",
":",
"self",
".",
"tree",
".",
"make_links_absolute",
"(",
"self",
".",
"doc",
".",
"url",
")",
"if",
"isinstance",
"(",
"href_pattern... | Find link in response body which href value matches ``href_pattern``.
Returns found url or None. | [
"Find",
"link",
"in",
"response",
"body",
"which",
"href",
"value",
"matches",
"href_pattern",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L76-L93 |
233,846 | lorien/grab | grab/deprecated.py | DeprecatedThings.find_link_rex | def find_link_rex(self, rex, make_absolute=True):
"""
Find link matched the given regular expression in response body.
Returns found url or None.
"""
if make_absolute:
self.tree.make_links_absolute(self.doc.url)
for elem, _, link, _ in self.tree.iterlinks():
if elem.tag == 'a':
match = rex.search(link)
if match:
# That does not work for string object
# link.match = match
return link
return None | python | def find_link_rex(self, rex, make_absolute=True):
if make_absolute:
self.tree.make_links_absolute(self.doc.url)
for elem, _, link, _ in self.tree.iterlinks():
if elem.tag == 'a':
match = rex.search(link)
if match:
# That does not work for string object
# link.match = match
return link
return None | [
"def",
"find_link_rex",
"(",
"self",
",",
"rex",
",",
"make_absolute",
"=",
"True",
")",
":",
"if",
"make_absolute",
":",
"self",
".",
"tree",
".",
"make_links_absolute",
"(",
"self",
".",
"doc",
".",
"url",
")",
"for",
"elem",
",",
"_",
",",
"link",
... | Find link matched the given regular expression in response body.
Returns found url or None. | [
"Find",
"link",
"matched",
"the",
"given",
"regular",
"expression",
"in",
"response",
"body",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L96-L113 |
233,847 | lorien/grab | grab/deprecated.py | DeprecatedThings.css_one | def css_one(self, path, default=NULL):
"""
Get first element which matches the given css path
or raise DataNotFound.
"""
try:
return self.css_list(path)[0]
except IndexError:
if default is NULL:
raise DataNotFound('CSS path not found: %s' % path)
else:
return default | python | def css_one(self, path, default=NULL):
try:
return self.css_list(path)[0]
except IndexError:
if default is NULL:
raise DataNotFound('CSS path not found: %s' % path)
else:
return default | [
"def",
"css_one",
"(",
"self",
",",
"path",
",",
"default",
"=",
"NULL",
")",
":",
"try",
":",
"return",
"self",
".",
"css_list",
"(",
"path",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"if",
"default",
"is",
"NULL",
":",
"raise",
"DataNotFound... | Get first element which matches the given css path
or raise DataNotFound. | [
"Get",
"first",
"element",
"which",
"matches",
"the",
"given",
"css",
"path",
"or",
"raise",
"DataNotFound",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L150-L162 |
233,848 | lorien/grab | grab/deprecated.py | DeprecatedThings.css_text | def css_text(self, path, default=NULL, smart=False, normalize_space=True):
"""
Get normalized text of node which matches the css path.
"""
try:
return get_node_text(self.css_one(path), smart=smart,
normalize_space=normalize_space)
except IndexError:
if default is NULL:
raise
else:
return default | python | def css_text(self, path, default=NULL, smart=False, normalize_space=True):
try:
return get_node_text(self.css_one(path), smart=smart,
normalize_space=normalize_space)
except IndexError:
if default is NULL:
raise
else:
return default | [
"def",
"css_text",
"(",
"self",
",",
"path",
",",
"default",
"=",
"NULL",
",",
"smart",
"=",
"False",
",",
"normalize_space",
"=",
"True",
")",
":",
"try",
":",
"return",
"get_node_text",
"(",
"self",
".",
"css_one",
"(",
"path",
")",
",",
"smart",
"... | Get normalized text of node which matches the css path. | [
"Get",
"normalized",
"text",
"of",
"node",
"which",
"matches",
"the",
"css",
"path",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L173-L185 |
233,849 | lorien/grab | grab/deprecated.py | DeprecatedThings.css_number | def css_number(self, path, default=NULL, ignore_spaces=False, smart=False,
make_int=True):
"""
Find number in normalized text of node which
matches the given css path.
"""
try:
text = self.css_text(path, smart=smart)
return find_number(text, ignore_spaces=ignore_spaces,
make_int=make_int)
except IndexError:
if default is NULL:
raise
else:
return default | python | def css_number(self, path, default=NULL, ignore_spaces=False, smart=False,
make_int=True):
try:
text = self.css_text(path, smart=smart)
return find_number(text, ignore_spaces=ignore_spaces,
make_int=make_int)
except IndexError:
if default is NULL:
raise
else:
return default | [
"def",
"css_number",
"(",
"self",
",",
"path",
",",
"default",
"=",
"NULL",
",",
"ignore_spaces",
"=",
"False",
",",
"smart",
"=",
"False",
",",
"make_int",
"=",
"True",
")",
":",
"try",
":",
"text",
"=",
"self",
".",
"css_text",
"(",
"path",
",",
... | Find number in normalized text of node which
matches the given css path. | [
"Find",
"number",
"in",
"normalized",
"text",
"of",
"node",
"which",
"matches",
"the",
"given",
"css",
"path",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L188-L203 |
233,850 | lorien/grab | grab/deprecated.py | DeprecatedThings.strip_tags | def strip_tags(self, content, smart=False):
"""
Strip tags from the HTML content.
"""
from lxml.html import fromstring
return get_node_text(fromstring(content), smart=smart) | python | def strip_tags(self, content, smart=False):
from lxml.html import fromstring
return get_node_text(fromstring(content), smart=smart) | [
"def",
"strip_tags",
"(",
"self",
",",
"content",
",",
"smart",
"=",
"False",
")",
":",
"from",
"lxml",
".",
"html",
"import",
"fromstring",
"return",
"get_node_text",
"(",
"fromstring",
"(",
"content",
")",
",",
"smart",
"=",
"smart",
")"
] | Strip tags from the HTML content. | [
"Strip",
"tags",
"from",
"the",
"HTML",
"content",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L230-L236 |
233,851 | lorien/grab | grab/util/misc.py | camel_case_to_underscore | def camel_case_to_underscore(name):
"""Converts camel_case into CamelCase"""
res = RE_TOKEN1.sub(r'\1_\2', name)
res = RE_TOKEN2.sub(r'\1_\2', res)
return res.lower() | python | def camel_case_to_underscore(name):
res = RE_TOKEN1.sub(r'\1_\2', name)
res = RE_TOKEN2.sub(r'\1_\2', res)
return res.lower() | [
"def",
"camel_case_to_underscore",
"(",
"name",
")",
":",
"res",
"=",
"RE_TOKEN1",
".",
"sub",
"(",
"r'\\1_\\2'",
",",
"name",
")",
"res",
"=",
"RE_TOKEN2",
".",
"sub",
"(",
"r'\\1_\\2'",
",",
"res",
")",
"return",
"res",
".",
"lower",
"(",
")"
] | Converts camel_case into CamelCase | [
"Converts",
"camel_case",
"into",
"CamelCase"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/util/misc.py#L8-L12 |
233,852 | lorien/grab | grab/document.py | read_bom | def read_bom(data):
"""Read the byte order mark in the text, if present, and
return the encoding represented by the BOM and the BOM.
If no BOM can be detected, (None, None) is returned.
"""
# common case is no BOM, so this is fast
if data and data[0] in _FIRST_CHARS:
for bom, encoding in _BOM_TABLE:
if data.startswith(bom):
return encoding, bom
return None, None | python | def read_bom(data):
# common case is no BOM, so this is fast
if data and data[0] in _FIRST_CHARS:
for bom, encoding in _BOM_TABLE:
if data.startswith(bom):
return encoding, bom
return None, None | [
"def",
"read_bom",
"(",
"data",
")",
":",
"# common case is no BOM, so this is fast",
"if",
"data",
"and",
"data",
"[",
"0",
"]",
"in",
"_FIRST_CHARS",
":",
"for",
"bom",
",",
"encoding",
"in",
"_BOM_TABLE",
":",
"if",
"data",
".",
"startswith",
"(",
"bom",
... | Read the byte order mark in the text, if present, and
return the encoding represented by the BOM and the BOM.
If no BOM can be detected, (None, None) is returned. | [
"Read",
"the",
"byte",
"order",
"mark",
"in",
"the",
"text",
"if",
"present",
"and",
"return",
"the",
"encoding",
"represented",
"by",
"the",
"BOM",
"and",
"the",
"BOM",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L67-L78 |
233,853 | lorien/grab | grab/document.py | Document.parse | def parse(self, charset=None, headers=None):
"""
Parse headers.
This method is called after Grab instance performs network request.
"""
if headers:
self.headers = headers
else:
# Parse headers only from last response
# There could be multiple responses in `self.head`
# in case of 301/302 redirect
# Separate responses
if self.head:
responses = self.head.rsplit(b'\nHTTP/', 1)
# Cut off the 'HTTP/*' line from the last response
_, response = responses[-1].split(b'\n', 1)
response = response.decode('utf-8', 'ignore')
else:
response = u''
if six.PY2:
# email_from_string does not work with unicode input
response = response.encode('utf-8')
self.headers = email.message_from_string(response)
if charset is None:
if isinstance(self.body, six.text_type):
self.charset = 'utf-8'
else:
self.detect_charset()
else:
self.charset = charset.lower()
self._unicode_body = None | python | def parse(self, charset=None, headers=None):
if headers:
self.headers = headers
else:
# Parse headers only from last response
# There could be multiple responses in `self.head`
# in case of 301/302 redirect
# Separate responses
if self.head:
responses = self.head.rsplit(b'\nHTTP/', 1)
# Cut off the 'HTTP/*' line from the last response
_, response = responses[-1].split(b'\n', 1)
response = response.decode('utf-8', 'ignore')
else:
response = u''
if six.PY2:
# email_from_string does not work with unicode input
response = response.encode('utf-8')
self.headers = email.message_from_string(response)
if charset is None:
if isinstance(self.body, six.text_type):
self.charset = 'utf-8'
else:
self.detect_charset()
else:
self.charset = charset.lower()
self._unicode_body = None | [
"def",
"parse",
"(",
"self",
",",
"charset",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"headers",
":",
"self",
".",
"headers",
"=",
"headers",
"else",
":",
"# Parse headers only from last response",
"# There could be multiple responses in `self.head`... | Parse headers.
This method is called after Grab instance performs network request. | [
"Parse",
"headers",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L159-L193 |
233,854 | lorien/grab | grab/document.py | Document.detect_charset | def detect_charset(self):
"""
Detect charset of the response.
Try following methods:
* meta[name="Http-Equiv"]
* XML declaration
* HTTP Content-Type header
Ignore unknown charsets.
Use utf-8 as fallback charset.
"""
charset = None
body_chunk = self.get_body_chunk()
if body_chunk:
# Try to extract charset from http-equiv meta tag
match_charset = RE_META_CHARSET.search(body_chunk)
if match_charset:
charset = match_charset.group(1)
else:
match_charset_html5 = RE_META_CHARSET_HTML5.search(body_chunk)
if match_charset_html5:
charset = match_charset_html5.group(1)
# TODO: <meta charset="utf-8" />
bom_enc, bom = read_bom(body_chunk)
if bom_enc:
charset = bom_enc
self.bom = bom
# Try to process XML declaration
if not charset:
if body_chunk.startswith(b'<?xml'):
match = RE_XML_DECLARATION.search(body_chunk)
if match:
enc_match = RE_DECLARATION_ENCODING.search(
match.group(0))
if enc_match:
charset = enc_match.group(1)
if not charset:
if 'Content-Type' in self.headers:
pos = self.headers['Content-Type'].find('charset=')
if pos > -1:
charset = self.headers['Content-Type'][(pos + 8):]
if charset:
charset = charset.lower()
if not isinstance(charset, str):
# Convert to unicode (py2.x) or string (py3.x)
charset = charset.decode('utf-8')
# Check that python knows such charset
try:
codecs.lookup(charset)
except LookupError:
logger.debug('Unknown charset found: %s.'
' Using utf-8 istead.', charset)
self.charset = 'utf-8'
else:
self.charset = charset | python | def detect_charset(self):
charset = None
body_chunk = self.get_body_chunk()
if body_chunk:
# Try to extract charset from http-equiv meta tag
match_charset = RE_META_CHARSET.search(body_chunk)
if match_charset:
charset = match_charset.group(1)
else:
match_charset_html5 = RE_META_CHARSET_HTML5.search(body_chunk)
if match_charset_html5:
charset = match_charset_html5.group(1)
# TODO: <meta charset="utf-8" />
bom_enc, bom = read_bom(body_chunk)
if bom_enc:
charset = bom_enc
self.bom = bom
# Try to process XML declaration
if not charset:
if body_chunk.startswith(b'<?xml'):
match = RE_XML_DECLARATION.search(body_chunk)
if match:
enc_match = RE_DECLARATION_ENCODING.search(
match.group(0))
if enc_match:
charset = enc_match.group(1)
if not charset:
if 'Content-Type' in self.headers:
pos = self.headers['Content-Type'].find('charset=')
if pos > -1:
charset = self.headers['Content-Type'][(pos + 8):]
if charset:
charset = charset.lower()
if not isinstance(charset, str):
# Convert to unicode (py2.x) or string (py3.x)
charset = charset.decode('utf-8')
# Check that python knows such charset
try:
codecs.lookup(charset)
except LookupError:
logger.debug('Unknown charset found: %s.'
' Using utf-8 istead.', charset)
self.charset = 'utf-8'
else:
self.charset = charset | [
"def",
"detect_charset",
"(",
"self",
")",
":",
"charset",
"=",
"None",
"body_chunk",
"=",
"self",
".",
"get_body_chunk",
"(",
")",
"if",
"body_chunk",
":",
"# Try to extract charset from http-equiv meta tag",
"match_charset",
"=",
"RE_META_CHARSET",
".",
"search",
... | Detect charset of the response.
Try following methods:
* meta[name="Http-Equiv"]
* XML declaration
* HTTP Content-Type header
Ignore unknown charsets.
Use utf-8 as fallback charset. | [
"Detect",
"charset",
"of",
"the",
"response",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L195-L258 |
233,855 | lorien/grab | grab/document.py | Document.copy | def copy(self, new_grab=None):
"""
Clone the Response object.
"""
obj = self.__class__()
obj.process_grab(new_grab if new_grab else self.grab)
copy_keys = ('status', 'code', 'head', 'body', 'total_time',
'connect_time', 'name_lookup_time',
'url', 'charset', '_unicode_body',
'_grab_config')
for key in copy_keys:
setattr(obj, key, getattr(self, key))
obj.headers = copy(self.headers)
# TODO: Maybe, deepcopy?
obj.cookies = copy(self.cookies)
return obj | python | def copy(self, new_grab=None):
obj = self.__class__()
obj.process_grab(new_grab if new_grab else self.grab)
copy_keys = ('status', 'code', 'head', 'body', 'total_time',
'connect_time', 'name_lookup_time',
'url', 'charset', '_unicode_body',
'_grab_config')
for key in copy_keys:
setattr(obj, key, getattr(self, key))
obj.headers = copy(self.headers)
# TODO: Maybe, deepcopy?
obj.cookies = copy(self.cookies)
return obj | [
"def",
"copy",
"(",
"self",
",",
"new_grab",
"=",
"None",
")",
":",
"obj",
"=",
"self",
".",
"__class__",
"(",
")",
"obj",
".",
"process_grab",
"(",
"new_grab",
"if",
"new_grab",
"else",
"self",
".",
"grab",
")",
"copy_keys",
"=",
"(",
"'status'",
",... | Clone the Response object. | [
"Clone",
"the",
"Response",
"object",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L260-L279 |
233,856 | lorien/grab | grab/document.py | Document.save | def save(self, path):
"""
Save response body to file.
"""
path_dir = os.path.split(path)[0]
if not os.path.exists(path_dir):
try:
os.makedirs(path_dir)
except OSError:
pass
with open(path, 'wb') as out:
out.write(self._bytes_body if self._bytes_body is not None
else b'') | python | def save(self, path):
path_dir = os.path.split(path)[0]
if not os.path.exists(path_dir):
try:
os.makedirs(path_dir)
except OSError:
pass
with open(path, 'wb') as out:
out.write(self._bytes_body if self._bytes_body is not None
else b'') | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"path_dir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"[",
"0",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path_dir",
")",
":",
"try",
":",
"os",
".",
"makedirs",
... | Save response body to file. | [
"Save",
"response",
"body",
"to",
"file",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L281-L295 |
233,857 | lorien/grab | grab/document.py | Document.save_hash | def save_hash(self, location, basedir, ext=None):
"""
Save response body into file with special path
builded from hash. That allows to lower number of files
per directory.
:param location: URL of file or something else. It is
used to build the SHA1 hash.
:param basedir: base directory to save the file. Note that
file will not be saved directly to this directory but to
some sub-directory of `basedir`
:param ext: extension which should be appended to file name. The
dot is inserted automatically between filename and extension.
:returns: path to saved file relative to `basedir`
Example::
>>> url = 'http://yandex.ru/logo.png'
>>> g.go(url)
>>> g.response.save_hash(url, 'some_dir', ext='png')
'e8/dc/f2918108788296df1facadc975d32b361a6a.png'
# the file was saved to $PWD/some_dir/e8/dc/...
TODO: replace `basedir` with two options: root and save_to. And
returns save_to + path
"""
if isinstance(location, six.text_type):
location = location.encode('utf-8')
rel_path = hashed_path(location, ext=ext)
path = os.path.join(basedir, rel_path)
if not os.path.exists(path):
path_dir, _ = os.path.split(path)
try:
os.makedirs(path_dir)
except OSError:
pass
with open(path, 'wb') as out:
out.write(self._bytes_body)
return rel_path | python | def save_hash(self, location, basedir, ext=None):
if isinstance(location, six.text_type):
location = location.encode('utf-8')
rel_path = hashed_path(location, ext=ext)
path = os.path.join(basedir, rel_path)
if not os.path.exists(path):
path_dir, _ = os.path.split(path)
try:
os.makedirs(path_dir)
except OSError:
pass
with open(path, 'wb') as out:
out.write(self._bytes_body)
return rel_path | [
"def",
"save_hash",
"(",
"self",
",",
"location",
",",
"basedir",
",",
"ext",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"location",
",",
"six",
".",
"text_type",
")",
":",
"location",
"=",
"location",
".",
"encode",
"(",
"'utf-8'",
")",
"rel_path... | Save response body into file with special path
builded from hash. That allows to lower number of files
per directory.
:param location: URL of file or something else. It is
used to build the SHA1 hash.
:param basedir: base directory to save the file. Note that
file will not be saved directly to this directory but to
some sub-directory of `basedir`
:param ext: extension which should be appended to file name. The
dot is inserted automatically between filename and extension.
:returns: path to saved file relative to `basedir`
Example::
>>> url = 'http://yandex.ru/logo.png'
>>> g.go(url)
>>> g.response.save_hash(url, 'some_dir', ext='png')
'e8/dc/f2918108788296df1facadc975d32b361a6a.png'
# the file was saved to $PWD/some_dir/e8/dc/...
TODO: replace `basedir` with two options: root and save_to. And
returns save_to + path | [
"Save",
"response",
"body",
"into",
"file",
"with",
"special",
"path",
"builded",
"from",
"hash",
".",
"That",
"allows",
"to",
"lower",
"number",
"of",
"files",
"per",
"directory",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L297-L336 |
233,858 | lorien/grab | grab/document.py | Document.json | def json(self):
"""
Return response body deserialized into JSON object.
"""
if six.PY3:
return json.loads(self.body.decode(self.charset))
else:
return json.loads(self.body) | python | def json(self):
if six.PY3:
return json.loads(self.body.decode(self.charset))
else:
return json.loads(self.body) | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"six",
".",
"PY3",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"body",
".",
"decode",
"(",
"self",
".",
"charset",
")",
")",
"else",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"... | Return response body deserialized into JSON object. | [
"Return",
"response",
"body",
"deserialized",
"into",
"JSON",
"object",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L339-L347 |
233,859 | lorien/grab | grab/document.py | Document.browse | def browse(self):
"""
Save response in temporary file and open it in GUI browser.
"""
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open('file://' + path) | python | def browse(self):
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open('file://' + path) | [
"def",
"browse",
"(",
"self",
")",
":",
"_",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"self",
".",
"save",
"(",
"path",
")",
"webbrowser",
".",
"open",
"(",
"'file://'",
"+",
"path",
")"
] | Save response in temporary file and open it in GUI browser. | [
"Save",
"response",
"in",
"temporary",
"file",
"and",
"open",
"it",
"in",
"GUI",
"browser",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L363-L370 |
233,860 | lorien/grab | grab/document.py | Document.text_search | def text_search(self, anchor, byte=False):
"""
Search the substring in response body.
:param anchor: string to search
:param byte: if False then `anchor` should be the
unicode string, and search will be performed in
`response.unicode_body()` else `anchor` should be the byte-string
and search will be performed in `response.body`
If substring is found return True else False.
"""
if isinstance(anchor, six.text_type):
if byte:
raise GrabMisuseError('The anchor should be bytes string in '
'byte mode')
else:
return anchor in self.unicode_body()
if not isinstance(anchor, six.text_type):
if byte:
# if six.PY3:
# return anchor in self.body_as_bytes()
return anchor in self.body
else:
raise GrabMisuseError('The anchor should be byte string in '
'non-byte mode') | python | def text_search(self, anchor, byte=False):
if isinstance(anchor, six.text_type):
if byte:
raise GrabMisuseError('The anchor should be bytes string in '
'byte mode')
else:
return anchor in self.unicode_body()
if not isinstance(anchor, six.text_type):
if byte:
# if six.PY3:
# return anchor in self.body_as_bytes()
return anchor in self.body
else:
raise GrabMisuseError('The anchor should be byte string in '
'non-byte mode') | [
"def",
"text_search",
"(",
"self",
",",
"anchor",
",",
"byte",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"anchor",
",",
"six",
".",
"text_type",
")",
":",
"if",
"byte",
":",
"raise",
"GrabMisuseError",
"(",
"'The anchor should be bytes string in '",
"... | Search the substring in response body.
:param anchor: string to search
:param byte: if False then `anchor` should be the
unicode string, and search will be performed in
`response.unicode_body()` else `anchor` should be the byte-string
and search will be performed in `response.body`
If substring is found return True else False. | [
"Search",
"the",
"substring",
"in",
"response",
"body",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L403-L430 |
233,861 | lorien/grab | grab/document.py | Document.text_assert | def text_assert(self, anchor, byte=False):
"""
If `anchor` is not found then raise `DataNotFound` exception.
"""
if not self.text_search(anchor, byte=byte):
raise DataNotFound(u'Substring not found: %s' % anchor) | python | def text_assert(self, anchor, byte=False):
if not self.text_search(anchor, byte=byte):
raise DataNotFound(u'Substring not found: %s' % anchor) | [
"def",
"text_assert",
"(",
"self",
",",
"anchor",
",",
"byte",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"text_search",
"(",
"anchor",
",",
"byte",
"=",
"byte",
")",
":",
"raise",
"DataNotFound",
"(",
"u'Substring not found: %s'",
"%",
"anchor",
... | If `anchor` is not found then raise `DataNotFound` exception. | [
"If",
"anchor",
"is",
"not",
"found",
"then",
"raise",
"DataNotFound",
"exception",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L432-L438 |
233,862 | lorien/grab | grab/document.py | Document.text_assert_any | def text_assert_any(self, anchors, byte=False):
"""
If no `anchors` were found then raise `DataNotFound` exception.
"""
found = False
for anchor in anchors:
if self.text_search(anchor, byte=byte):
found = True
break
if not found:
raise DataNotFound(u'Substrings not found: %s'
% ', '.join(anchors)) | python | def text_assert_any(self, anchors, byte=False):
found = False
for anchor in anchors:
if self.text_search(anchor, byte=byte):
found = True
break
if not found:
raise DataNotFound(u'Substrings not found: %s'
% ', '.join(anchors)) | [
"def",
"text_assert_any",
"(",
"self",
",",
"anchors",
",",
"byte",
"=",
"False",
")",
":",
"found",
"=",
"False",
"for",
"anchor",
"in",
"anchors",
":",
"if",
"self",
".",
"text_search",
"(",
"anchor",
",",
"byte",
"=",
"byte",
")",
":",
"found",
"=... | If no `anchors` were found then raise `DataNotFound` exception. | [
"If",
"no",
"anchors",
"were",
"found",
"then",
"raise",
"DataNotFound",
"exception",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L440-L452 |
233,863 | lorien/grab | grab/document.py | Document.rex_text | def rex_text(self, regexp, flags=0, byte=False, default=NULL):
"""
Search regular expression in response body and return content of first
matching group.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
"""
# pylint: disable=no-member
try:
match = self.rex_search(regexp, flags=flags, byte=byte)
except DataNotFound:
if default is NULL:
raise DataNotFound('Regexp not found')
else:
return default
else:
return normalize_space(decode_entities(match.group(1))) | python | def rex_text(self, regexp, flags=0, byte=False, default=NULL):
# pylint: disable=no-member
try:
match = self.rex_search(regexp, flags=flags, byte=byte)
except DataNotFound:
if default is NULL:
raise DataNotFound('Regexp not found')
else:
return default
else:
return normalize_space(decode_entities(match.group(1))) | [
"def",
"rex_text",
"(",
"self",
",",
"regexp",
",",
"flags",
"=",
"0",
",",
"byte",
"=",
"False",
",",
"default",
"=",
"NULL",
")",
":",
"# pylint: disable=no-member",
"try",
":",
"match",
"=",
"self",
".",
"rex_search",
"(",
"regexp",
",",
"flags",
"=... | Search regular expression in response body and return content of first
matching group.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`. | [
"Search",
"regular",
"expression",
"in",
"response",
"body",
"and",
"return",
"content",
"of",
"first",
"matching",
"group",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L456-L474 |
233,864 | lorien/grab | grab/document.py | Document.rex_search | def rex_search(self, regexp, flags=0, byte=False, default=NULL):
"""
Search the regular expression in response body.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
Note: if you use default non-byte mode than do not forget to build your
regular expression with re.U flag.
Return found match object or None
"""
regexp = normalize_regexp(regexp, flags)
match = None
if byte:
if not isinstance(regexp.pattern, six.text_type) or not six.PY3:
# if six.PY3:
# body = self.body_as_bytes()
# else:
# body = self.body
match = regexp.search(self.body)
else:
if isinstance(regexp.pattern, six.text_type) or not six.PY3:
ubody = self.unicode_body()
match = regexp.search(ubody)
if match:
return match
else:
if default is NULL:
raise DataNotFound('Could not find regexp: %s' % regexp)
else:
return default | python | def rex_search(self, regexp, flags=0, byte=False, default=NULL):
regexp = normalize_regexp(regexp, flags)
match = None
if byte:
if not isinstance(regexp.pattern, six.text_type) or not six.PY3:
# if six.PY3:
# body = self.body_as_bytes()
# else:
# body = self.body
match = regexp.search(self.body)
else:
if isinstance(regexp.pattern, six.text_type) or not six.PY3:
ubody = self.unicode_body()
match = regexp.search(ubody)
if match:
return match
else:
if default is NULL:
raise DataNotFound('Could not find regexp: %s' % regexp)
else:
return default | [
"def",
"rex_search",
"(",
"self",
",",
"regexp",
",",
"flags",
"=",
"0",
",",
"byte",
"=",
"False",
",",
"default",
"=",
"NULL",
")",
":",
"regexp",
"=",
"normalize_regexp",
"(",
"regexp",
",",
"flags",
")",
"match",
"=",
"None",
"if",
"byte",
":",
... | Search the regular expression in response body.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
Note: if you use default non-byte mode than do not forget to build your
regular expression with re.U flag.
Return found match object or None | [
"Search",
"the",
"regular",
"expression",
"in",
"response",
"body",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L476-L509 |
233,865 | lorien/grab | grab/document.py | Document.rex_assert | def rex_assert(self, rex, byte=False):
"""
If `rex` expression is not found then raise `DataNotFound` exception.
"""
self.rex_search(rex, byte=byte) | python | def rex_assert(self, rex, byte=False):
self.rex_search(rex, byte=byte) | [
"def",
"rex_assert",
"(",
"self",
",",
"rex",
",",
"byte",
"=",
"False",
")",
":",
"self",
".",
"rex_search",
"(",
"rex",
",",
"byte",
"=",
"byte",
")"
] | If `rex` expression is not found then raise `DataNotFound` exception. | [
"If",
"rex",
"expression",
"is",
"not",
"found",
"then",
"raise",
"DataNotFound",
"exception",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L511-L516 |
233,866 | lorien/grab | grab/document.py | Document.pyquery | def pyquery(self):
"""
Returns pyquery handler.
"""
if not self._pyquery:
from pyquery import PyQuery
self._pyquery = PyQuery(self.tree)
return self._pyquery | python | def pyquery(self):
if not self._pyquery:
from pyquery import PyQuery
self._pyquery = PyQuery(self.tree)
return self._pyquery | [
"def",
"pyquery",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pyquery",
":",
"from",
"pyquery",
"import",
"PyQuery",
"self",
".",
"_pyquery",
"=",
"PyQuery",
"(",
"self",
".",
"tree",
")",
"return",
"self",
".",
"_pyquery"
] | Returns pyquery handler. | [
"Returns",
"pyquery",
"handler",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L521-L530 |
233,867 | lorien/grab | grab/document.py | Document.unicode_body | def unicode_body(self, ignore_errors=True, fix_special_entities=True):
"""
Return response body as unicode string.
"""
if not self._unicode_body:
self._unicode_body = self.convert_body_to_unicode(
body=self.body,
bom=self.bom,
charset=self.charset,
ignore_errors=ignore_errors,
fix_special_entities=fix_special_entities,
)
return self._unicode_body | python | def unicode_body(self, ignore_errors=True, fix_special_entities=True):
if not self._unicode_body:
self._unicode_body = self.convert_body_to_unicode(
body=self.body,
bom=self.bom,
charset=self.charset,
ignore_errors=ignore_errors,
fix_special_entities=fix_special_entities,
)
return self._unicode_body | [
"def",
"unicode_body",
"(",
"self",
",",
"ignore_errors",
"=",
"True",
",",
"fix_special_entities",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_unicode_body",
":",
"self",
".",
"_unicode_body",
"=",
"self",
".",
"convert_body_to_unicode",
"(",
"body",
... | Return response body as unicode string. | [
"Return",
"response",
"body",
"as",
"unicode",
"string",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L562-L575 |
233,868 | lorien/grab | grab/document.py | Document.choose_form | def choose_form(self, number=None, xpath=None, name=None, **kwargs):
"""
Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`DataNotFound` if form not found
:raises: :class:`GrabMisuseError`
if method is called without parameters
Selected form will be available via `form` attribute of `Grab`
instance. All form methods will work with default form.
Examples::
# Select second form
g.choose_form(1)
# Select by id
g.choose_form(id="register")
# Select by name
g.choose_form(name="signup")
# Select by xpath
g.choose_form(xpath='//form[contains(@action, "/submit")]')
"""
id_ = kwargs.pop('id', None)
if id_ is not None:
try:
self._lxml_form = self.select('//form[@id="%s"]' % id_).node()
except IndexError:
raise DataNotFound("There is no form with id: %s" % id_)
elif name is not None:
try:
self._lxml_form = self.select(
'//form[@name="%s"]' % name).node()
except IndexError:
raise DataNotFound('There is no form with name: %s' % name)
elif number is not None:
try:
self._lxml_form = self.tree.forms[number]
except IndexError:
raise DataNotFound('There is no form with number: %s' % number)
elif xpath is not None:
try:
self._lxml_form = self.select(xpath).node()
except IndexError:
raise DataNotFound(
'Could not find form with xpath: %s' % xpath)
else:
raise GrabMisuseError('choose_form methods requires one of '
'[number, id, name, xpath] arguments') | python | def choose_form(self, number=None, xpath=None, name=None, **kwargs):
id_ = kwargs.pop('id', None)
if id_ is not None:
try:
self._lxml_form = self.select('//form[@id="%s"]' % id_).node()
except IndexError:
raise DataNotFound("There is no form with id: %s" % id_)
elif name is not None:
try:
self._lxml_form = self.select(
'//form[@name="%s"]' % name).node()
except IndexError:
raise DataNotFound('There is no form with name: %s' % name)
elif number is not None:
try:
self._lxml_form = self.tree.forms[number]
except IndexError:
raise DataNotFound('There is no form with number: %s' % number)
elif xpath is not None:
try:
self._lxml_form = self.select(xpath).node()
except IndexError:
raise DataNotFound(
'Could not find form with xpath: %s' % xpath)
else:
raise GrabMisuseError('choose_form methods requires one of '
'[number, id, name, xpath] arguments') | [
"def",
"choose_form",
"(",
"self",
",",
"number",
"=",
"None",
",",
"xpath",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"id_",
"=",
"kwargs",
".",
"pop",
"(",
"'id'",
",",
"None",
")",
"if",
"id_",
"is",
"not",
"N... | Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`DataNotFound` if form not found
:raises: :class:`GrabMisuseError`
if method is called without parameters
Selected form will be available via `form` attribute of `Grab`
instance. All form methods will work with default form.
Examples::
# Select second form
g.choose_form(1)
# Select by id
g.choose_form(id="register")
# Select by name
g.choose_form(name="signup")
# Select by xpath
g.choose_form(xpath='//form[contains(@action, "/submit")]') | [
"Set",
"the",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L688-L743 |
233,869 | lorien/grab | grab/document.py | Document.form | def form(self):
"""
This attribute points to default form.
If form was not selected manually then select the form
which has the biggest number of input elements.
The form value is just an `lxml.html` form element.
Example::
g.go('some URL')
# Choose form automatically
print g.form
# And now choose form manually
g.choose_form(1)
print g.form
"""
if self._lxml_form is None:
forms = [(idx, len(list(x.fields)))
for idx, x in enumerate(self.tree.forms)]
if forms:
idx = sorted(forms, key=lambda x: x[1], reverse=True)[0][0]
self.choose_form(idx)
else:
raise DataNotFound('Response does not contains any form')
return self._lxml_form | python | def form(self):
if self._lxml_form is None:
forms = [(idx, len(list(x.fields)))
for idx, x in enumerate(self.tree.forms)]
if forms:
idx = sorted(forms, key=lambda x: x[1], reverse=True)[0][0]
self.choose_form(idx)
else:
raise DataNotFound('Response does not contains any form')
return self._lxml_form | [
"def",
"form",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"forms",
"=",
"[",
"(",
"idx",
",",
"len",
"(",
"list",
"(",
"x",
".",
"fields",
")",
")",
")",
"for",
"idx",
",",
"x",
"in",
"enumerate",
"(",
"self",
... | This attribute points to default form.
If form was not selected manually then select the form
which has the biggest number of input elements.
The form value is just an `lxml.html` form element.
Example::
g.go('some URL')
# Choose form automatically
print g.form
# And now choose form manually
g.choose_form(1)
print g.form | [
"This",
"attribute",
"points",
"to",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L746-L774 |
233,870 | lorien/grab | grab/document.py | Document.set_input | def set_input(self, name, value):
"""
Set the value of form element by its `name` attribute.
:param name: name of element
:param value: value which should be set to element
To check/uncheck the checkbox pass boolean value.
Example::
g.set_input('sex', 'male')
# Check the checkbox
g.set_input('accept', True)
"""
if self._lxml_form is None:
self.choose_form_by_element('.//*[@name="%s"]' % name)
elem = self.form.inputs[name] # pylint: disable=no-member
processed = False
if getattr(elem, 'type', None) == 'checkbox':
if isinstance(value, bool):
elem.checked = value
processed = True
if not processed:
# We need to remember original values of file fields
# Because lxml will convert UploadContent/UploadFile object to
# string
if getattr(elem, 'type', '').lower() == 'file':
self._file_fields[name] = value
elem.value = ''
else:
elem.value = value | python | def set_input(self, name, value):
if self._lxml_form is None:
self.choose_form_by_element('.//*[@name="%s"]' % name)
elem = self.form.inputs[name] # pylint: disable=no-member
processed = False
if getattr(elem, 'type', None) == 'checkbox':
if isinstance(value, bool):
elem.checked = value
processed = True
if not processed:
# We need to remember original values of file fields
# Because lxml will convert UploadContent/UploadFile object to
# string
if getattr(elem, 'type', '').lower() == 'file':
self._file_fields[name] = value
elem.value = ''
else:
elem.value = value | [
"def",
"set_input",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"self",
".",
"choose_form_by_element",
"(",
"'.//*[@name=\"%s\"]'",
"%",
"name",
")",
"elem",
"=",
"self",
".",
"form",
".",
"inputs... | Set the value of form element by its `name` attribute.
:param name: name of element
:param value: value which should be set to element
To check/uncheck the checkbox pass boolean value.
Example::
g.set_input('sex', 'male')
# Check the checkbox
g.set_input('accept', True) | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"its",
"name",
"attribute",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L776-L811 |
233,871 | lorien/grab | grab/document.py | Document.set_input_by_id | def set_input_by_id(self, _id, value):
"""
Set the value of form element by its `id` attribute.
:param _id: id of element
:param value: value which should be set to element
"""
xpath = './/*[@id="%s"]' % _id
if self._lxml_form is None:
self.choose_form_by_element(xpath)
sel = XpathSelector(self.form)
elem = sel.select(xpath).node()
# pylint: disable=no-member
return self.set_input(elem.get('name'), value) | python | def set_input_by_id(self, _id, value):
xpath = './/*[@id="%s"]' % _id
if self._lxml_form is None:
self.choose_form_by_element(xpath)
sel = XpathSelector(self.form)
elem = sel.select(xpath).node()
# pylint: disable=no-member
return self.set_input(elem.get('name'), value) | [
"def",
"set_input_by_id",
"(",
"self",
",",
"_id",
",",
"value",
")",
":",
"xpath",
"=",
"'.//*[@id=\"%s\"]'",
"%",
"_id",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"self",
".",
"choose_form_by_element",
"(",
"xpath",
")",
"sel",
"=",
"XpathSelec... | Set the value of form element by its `id` attribute.
:param _id: id of element
:param value: value which should be set to element | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"its",
"id",
"attribute",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L813-L827 |
233,872 | lorien/grab | grab/document.py | Document.set_input_by_number | def set_input_by_number(self, number, value):
"""
Set the value of form element by its number in the form
:param number: number of element
:param value: value which should be set to element
"""
sel = XpathSelector(self.form)
elem = sel.select('.//input[@type="text"]')[number].node()
return self.set_input(elem.get('name'), value) | python | def set_input_by_number(self, number, value):
sel = XpathSelector(self.form)
elem = sel.select('.//input[@type="text"]')[number].node()
return self.set_input(elem.get('name'), value) | [
"def",
"set_input_by_number",
"(",
"self",
",",
"number",
",",
"value",
")",
":",
"sel",
"=",
"XpathSelector",
"(",
"self",
".",
"form",
")",
"elem",
"=",
"sel",
".",
"select",
"(",
"'.//input[@type=\"text\"]'",
")",
"[",
"number",
"]",
".",
"node",
"(",... | Set the value of form element by its number in the form
:param number: number of element
:param value: value which should be set to element | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"its",
"number",
"in",
"the",
"form"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L829-L839 |
233,873 | lorien/grab | grab/document.py | Document.set_input_by_xpath | def set_input_by_xpath(self, xpath, value):
"""
Set the value of form element by xpath
:param xpath: xpath path
:param value: value which should be set to element
"""
elem = self.select(xpath).node()
if self._lxml_form is None:
# Explicitly set the default form
# which contains found element
parent = elem
while True:
parent = parent.getparent() # pylint: disable=no-member
if parent.tag == 'form':
self._lxml_form = parent
break
# pylint: disable=no-member
return self.set_input(elem.get('name'), value) | python | def set_input_by_xpath(self, xpath, value):
elem = self.select(xpath).node()
if self._lxml_form is None:
# Explicitly set the default form
# which contains found element
parent = elem
while True:
parent = parent.getparent() # pylint: disable=no-member
if parent.tag == 'form':
self._lxml_form = parent
break
# pylint: disable=no-member
return self.set_input(elem.get('name'), value) | [
"def",
"set_input_by_xpath",
"(",
"self",
",",
"xpath",
",",
"value",
")",
":",
"elem",
"=",
"self",
".",
"select",
"(",
"xpath",
")",
".",
"node",
"(",
")",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"# Explicitly set the default form",
"# which ... | Set the value of form element by xpath
:param xpath: xpath path
:param value: value which should be set to element | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"xpath"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L841-L862 |
233,874 | lorien/grab | grab/document.py | Document.get_form_request | def get_form_request(
self, submit_name=None,
url=None, extra_post=None, remove_from_post=None):
"""
Submit default form.
:param submit_name: name of button which should be "clicked" to
submit form
:param url: explicitly specify form action url
:param extra_post: (dict or list of pairs) additional form data which
will override data automatically extracted from the form.
:param remove_from_post: list of keys to remove from the submitted data
Following input elements are automatically processed:
* input[type="hidden"] - default value
* select: value of last option
* radio - ???
* checkbox - ???
Multipart forms are correctly recognized by grab library.
"""
# pylint: disable=no-member
post = self.form_fields()
# Build list of submit buttons which have a name
submit_controls = {}
for elem in self.form.inputs:
if (elem.tag == 'input' and elem.type == 'submit' and
elem.get('name') is not None):
submit_controls[elem.name] = elem
# All this code need only for one reason:
# to not send multiple submit keys in form data
# in real life only this key is submitted whose button
# was pressed
if submit_controls:
# If name of submit control is not given then
# use the name of first submit control
if submit_name is None or submit_name not in submit_controls:
controls = sorted(submit_controls.values(),
key=lambda x: x.name)
submit_name = controls[0].name
# Form data should contain only one submit control
for name in submit_controls:
if name != submit_name:
if name in post:
del post[name]
if url:
action_url = urljoin(self.url, url)
else:
action_url = urljoin(self.url,
self.form.action)
# Values from `extra_post` should override values in form
# `extra_post` allows multiple value of one key
# Process saved values of file fields
if self.form.method == 'POST':
if 'multipart' in self.form.get('enctype', ''):
for key, obj in self._file_fields.items():
post[key] = obj
post_items = list(post.items())
del post
if extra_post:
if isinstance(extra_post, dict):
extra_post_items = extra_post.items()
else:
extra_post_items = extra_post
# Drop existing post items with such key
keys_to_drop = set([x for x, y in extra_post_items])
for key in keys_to_drop:
post_items = [(x, y) for x, y in post_items if x != key]
for key, value in extra_post_items:
post_items.append((key, value))
if remove_from_post:
post_items = [(x, y) for x, y in post_items
if x not in remove_from_post]
result = {
'multipart_post': None,
'post': None,
'url': None,
}
if self.form.method == 'POST':
if 'multipart' in self.form.get('enctype', ''):
result['multipart_post'] = post_items
#self.grab.setup(multipart_post=post_items)
else:
result['post'] = post_items
#self.grab.setup(post=post_items)
result['url'] = action_url
#self.grab.setup(url=action_url)
else:
url = action_url.split('?')[0] + '?' + smart_urlencode(post_items)
result['url'] = url
#self.grab.setup(url=url)
return result | python | def get_form_request(
self, submit_name=None,
url=None, extra_post=None, remove_from_post=None):
# pylint: disable=no-member
post = self.form_fields()
# Build list of submit buttons which have a name
submit_controls = {}
for elem in self.form.inputs:
if (elem.tag == 'input' and elem.type == 'submit' and
elem.get('name') is not None):
submit_controls[elem.name] = elem
# All this code need only for one reason:
# to not send multiple submit keys in form data
# in real life only this key is submitted whose button
# was pressed
if submit_controls:
# If name of submit control is not given then
# use the name of first submit control
if submit_name is None or submit_name not in submit_controls:
controls = sorted(submit_controls.values(),
key=lambda x: x.name)
submit_name = controls[0].name
# Form data should contain only one submit control
for name in submit_controls:
if name != submit_name:
if name in post:
del post[name]
if url:
action_url = urljoin(self.url, url)
else:
action_url = urljoin(self.url,
self.form.action)
# Values from `extra_post` should override values in form
# `extra_post` allows multiple value of one key
# Process saved values of file fields
if self.form.method == 'POST':
if 'multipart' in self.form.get('enctype', ''):
for key, obj in self._file_fields.items():
post[key] = obj
post_items = list(post.items())
del post
if extra_post:
if isinstance(extra_post, dict):
extra_post_items = extra_post.items()
else:
extra_post_items = extra_post
# Drop existing post items with such key
keys_to_drop = set([x for x, y in extra_post_items])
for key in keys_to_drop:
post_items = [(x, y) for x, y in post_items if x != key]
for key, value in extra_post_items:
post_items.append((key, value))
if remove_from_post:
post_items = [(x, y) for x, y in post_items
if x not in remove_from_post]
result = {
'multipart_post': None,
'post': None,
'url': None,
}
if self.form.method == 'POST':
if 'multipart' in self.form.get('enctype', ''):
result['multipart_post'] = post_items
#self.grab.setup(multipart_post=post_items)
else:
result['post'] = post_items
#self.grab.setup(post=post_items)
result['url'] = action_url
#self.grab.setup(url=action_url)
else:
url = action_url.split('?')[0] + '?' + smart_urlencode(post_items)
result['url'] = url
#self.grab.setup(url=url)
return result | [
"def",
"get_form_request",
"(",
"self",
",",
"submit_name",
"=",
"None",
",",
"url",
"=",
"None",
",",
"extra_post",
"=",
"None",
",",
"remove_from_post",
"=",
"None",
")",
":",
"# pylint: disable=no-member",
"post",
"=",
"self",
".",
"form_fields",
"(",
")"... | Submit default form.
:param submit_name: name of button which should be "clicked" to
submit form
:param url: explicitly specify form action url
:param extra_post: (dict or list of pairs) additional form data which
will override data automatically extracted from the form.
:param remove_from_post: list of keys to remove from the submitted data
Following input elements are automatically processed:
* input[type="hidden"] - default value
* select: value of last option
* radio - ???
* checkbox - ???
Multipart forms are correctly recognized by grab library. | [
"Submit",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L869-L978 |
233,875 | lorien/grab | grab/document.py | Document.form_fields | def form_fields(self):
"""
Return fields of default form.
Fill some fields with reasonable values.
"""
fields = dict(self.form.fields) # pylint: disable=no-member
fields_to_remove = set()
for key, val in list(fields.items()):
if isinstance(val, CheckboxValues):
if not len(val): # pylint: disable=len-as-condition
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val)
if isinstance(val, MultipleSelectOptions):
if not len(val): # pylint: disable=len-as-condition
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val)
for elem in self.form.inputs: # pylint: disable=no-member
# Ignore elements without name
if not elem.get('name'):
continue
# Do not submit disabled fields
# http://www.w3.org/TR/html4/interact/forms.html#h-17.12
if elem.get('disabled'):
if elem.name in fields:
fields_to_remove.add(elem.name)
elif getattr(elem, 'type', None) == 'checkbox':
if not elem.checked:
if elem.name is not None:
if elem.name in fields and fields[elem.name] is None:
fields_to_remove.add(elem.name)
else:
if elem.name in fields_to_remove:
fields_to_remove.remove(elem.name)
if elem.tag == 'select':
if elem.name in fields and fields[elem.name] is None:
if elem.value_options:
fields[elem.name] = elem.value_options[0]
elif getattr(elem, 'type', None) == 'radio':
if fields[elem.name] is None:
fields[elem.name] = elem.get('value')
for fname in fields_to_remove:
del fields[fname]
return fields | python | def form_fields(self):
fields = dict(self.form.fields) # pylint: disable=no-member
fields_to_remove = set()
for key, val in list(fields.items()):
if isinstance(val, CheckboxValues):
if not len(val): # pylint: disable=len-as-condition
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val)
if isinstance(val, MultipleSelectOptions):
if not len(val): # pylint: disable=len-as-condition
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val)
for elem in self.form.inputs: # pylint: disable=no-member
# Ignore elements without name
if not elem.get('name'):
continue
# Do not submit disabled fields
# http://www.w3.org/TR/html4/interact/forms.html#h-17.12
if elem.get('disabled'):
if elem.name in fields:
fields_to_remove.add(elem.name)
elif getattr(elem, 'type', None) == 'checkbox':
if not elem.checked:
if elem.name is not None:
if elem.name in fields and fields[elem.name] is None:
fields_to_remove.add(elem.name)
else:
if elem.name in fields_to_remove:
fields_to_remove.remove(elem.name)
if elem.tag == 'select':
if elem.name in fields and fields[elem.name] is None:
if elem.value_options:
fields[elem.name] = elem.value_options[0]
elif getattr(elem, 'type', None) == 'radio':
if fields[elem.name] is None:
fields[elem.name] = elem.get('value')
for fname in fields_to_remove:
del fields[fname]
return fields | [
"def",
"form_fields",
"(",
"self",
")",
":",
"fields",
"=",
"dict",
"(",
"self",
".",
"form",
".",
"fields",
")",
"# pylint: disable=no-member",
"fields_to_remove",
"=",
"set",
"(",
")",
"for",
"key",
",",
"val",
"in",
"list",
"(",
"fields",
".",
"items"... | Return fields of default form.
Fill some fields with reasonable values. | [
"Return",
"fields",
"of",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L993-L1048 |
233,876 | maxpumperla/elephas | elephas/utils/functional_utils.py | add_params | def add_params(param_list_left, param_list_right):
"""Add two lists of parameters one by one
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
res = []
for x, y in zip(param_list_left, param_list_right):
res.append(x + y)
return res | python | def add_params(param_list_left, param_list_right):
res = []
for x, y in zip(param_list_left, param_list_right):
res.append(x + y)
return res | [
"def",
"add_params",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
".",
"append",
"(",
"x",
"+",
"y",
")",
"return",... | Add two lists of parameters one by one
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays | [
"Add",
"two",
"lists",
"of",
"parameters",
"one",
"by",
"one"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L7-L17 |
233,877 | maxpumperla/elephas | elephas/utils/functional_utils.py | subtract_params | def subtract_params(param_list_left, param_list_right):
"""Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
res = []
for x, y in zip(param_list_left, param_list_right):
res.append(x - y)
return res | python | def subtract_params(param_list_left, param_list_right):
res = []
for x, y in zip(param_list_left, param_list_right):
res.append(x - y)
return res | [
"def",
"subtract_params",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
".",
"append",
"(",
"x",
"-",
"y",
")",
"ret... | Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays | [
"Subtract",
"two",
"lists",
"of",
"parameters"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L20-L30 |
233,878 | maxpumperla/elephas | elephas/utils/functional_utils.py | get_neutral | def get_neutral(array_list):
"""Get list of zero-valued numpy arrays for
specified list of numpy arrays
:param array_list: list of numpy arrays
:return: list of zeros of same shape as input
"""
res = []
for x in array_list:
res.append(np.zeros_like(x))
return res | python | def get_neutral(array_list):
res = []
for x in array_list:
res.append(np.zeros_like(x))
return res | [
"def",
"get_neutral",
"(",
"array_list",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"array_list",
":",
"res",
".",
"append",
"(",
"np",
".",
"zeros_like",
"(",
"x",
")",
")",
"return",
"res"
] | Get list of zero-valued numpy arrays for
specified list of numpy arrays
:param array_list: list of numpy arrays
:return: list of zeros of same shape as input | [
"Get",
"list",
"of",
"zero",
"-",
"valued",
"numpy",
"arrays",
"for",
"specified",
"list",
"of",
"numpy",
"arrays"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L33-L43 |
233,879 | maxpumperla/elephas | elephas/utils/functional_utils.py | divide_by | def divide_by(array_list, num_workers):
"""Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return:
"""
for i, x in enumerate(array_list):
array_list[i] /= num_workers
return array_list | python | def divide_by(array_list, num_workers):
for i, x in enumerate(array_list):
array_list[i] /= num_workers
return array_list | [
"def",
"divide_by",
"(",
"array_list",
",",
"num_workers",
")",
":",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"array_list",
")",
":",
"array_list",
"[",
"i",
"]",
"/=",
"num_workers",
"return",
"array_list"
] | Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return: | [
"Divide",
"a",
"list",
"of",
"parameters",
"by",
"an",
"integer",
"num_workers",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L46-L55 |
233,880 | maxpumperla/elephas | elephas/parameter/server.py | HttpServer.start_flask_service | def start_flask_service(self):
"""Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get started.
"""
app = Flask(__name__)
self.app = app
@app.route('/')
def home():
return 'Elephas'
@app.route('/parameters', methods=['GET'])
def handle_get_parameters():
if self.mode == 'asynchronous':
self.lock.acquire_read()
self.pickled_weights = pickle.dumps(self.weights, -1)
pickled_weights = self.pickled_weights
if self.mode == 'asynchronous':
self.lock.release()
return pickled_weights
@app.route('/update', methods=['POST'])
def handle_update_parameters():
delta = pickle.loads(request.data)
if self.mode == 'asynchronous':
self.lock.acquire_write()
if not self.master_network.built:
self.master_network.build()
# Just apply the gradient
weights_before = self.weights
self.weights = subtract_params(weights_before, delta)
if self.mode == 'asynchronous':
self.lock.release()
return 'Update done'
master_url = determine_master(self.port)
host = master_url.split(':')[0]
self.app.run(host=host, debug=self.debug, port=self.port,
threaded=self.threaded, use_reloader=self.use_reloader) | python | def start_flask_service(self):
app = Flask(__name__)
self.app = app
@app.route('/')
def home():
return 'Elephas'
@app.route('/parameters', methods=['GET'])
def handle_get_parameters():
if self.mode == 'asynchronous':
self.lock.acquire_read()
self.pickled_weights = pickle.dumps(self.weights, -1)
pickled_weights = self.pickled_weights
if self.mode == 'asynchronous':
self.lock.release()
return pickled_weights
@app.route('/update', methods=['POST'])
def handle_update_parameters():
delta = pickle.loads(request.data)
if self.mode == 'asynchronous':
self.lock.acquire_write()
if not self.master_network.built:
self.master_network.build()
# Just apply the gradient
weights_before = self.weights
self.weights = subtract_params(weights_before, delta)
if self.mode == 'asynchronous':
self.lock.release()
return 'Update done'
master_url = determine_master(self.port)
host = master_url.split(':')[0]
self.app.run(host=host, debug=self.debug, port=self.port,
threaded=self.threaded, use_reloader=self.use_reloader) | [
"def",
"start_flask_service",
"(",
"self",
")",
":",
"app",
"=",
"Flask",
"(",
"__name__",
")",
"self",
".",
"app",
"=",
"app",
"@",
"app",
".",
"route",
"(",
"'/'",
")",
"def",
"home",
"(",
")",
":",
"return",
"'Elephas'",
"@",
"app",
".",
"route"... | Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get started. | [
"Define",
"Flask",
"parameter",
"server",
"service",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/parameter/server.py#L92-L138 |
233,881 | maxpumperla/elephas | elephas/mllib/adapter.py | to_matrix | def to_matrix(np_array):
"""Convert numpy array to MLlib Matrix
"""
if len(np_array.shape) == 2:
return Matrices.dense(np_array.shape[0],
np_array.shape[1],
np_array.ravel())
else:
raise Exception("An MLLib Matrix can only be created from a two-dimensional " +
"numpy array, got {}".format(len(np_array.shape))) | python | def to_matrix(np_array):
if len(np_array.shape) == 2:
return Matrices.dense(np_array.shape[0],
np_array.shape[1],
np_array.ravel())
else:
raise Exception("An MLLib Matrix can only be created from a two-dimensional " +
"numpy array, got {}".format(len(np_array.shape))) | [
"def",
"to_matrix",
"(",
"np_array",
")",
":",
"if",
"len",
"(",
"np_array",
".",
"shape",
")",
"==",
"2",
":",
"return",
"Matrices",
".",
"dense",
"(",
"np_array",
".",
"shape",
"[",
"0",
"]",
",",
"np_array",
".",
"shape",
"[",
"1",
"]",
",",
"... | Convert numpy array to MLlib Matrix | [
"Convert",
"numpy",
"array",
"to",
"MLlib",
"Matrix"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L11-L20 |
233,882 | maxpumperla/elephas | elephas/mllib/adapter.py | to_vector | def to_vector(np_array):
"""Convert numpy array to MLlib Vector
"""
if len(np_array.shape) == 1:
return Vectors.dense(np_array)
else:
raise Exception("An MLLib Vector can only be created from a one-dimensional " +
"numpy array, got {}".format(len(np_array.shape))) | python | def to_vector(np_array):
if len(np_array.shape) == 1:
return Vectors.dense(np_array)
else:
raise Exception("An MLLib Vector can only be created from a one-dimensional " +
"numpy array, got {}".format(len(np_array.shape))) | [
"def",
"to_vector",
"(",
"np_array",
")",
":",
"if",
"len",
"(",
"np_array",
".",
"shape",
")",
"==",
"1",
":",
"return",
"Vectors",
".",
"dense",
"(",
"np_array",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"An MLLib Vector can only be created from a one-d... | Convert numpy array to MLlib Vector | [
"Convert",
"numpy",
"array",
"to",
"MLlib",
"Vector"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L29-L36 |
233,883 | maxpumperla/elephas | elephas/java/adapter.py | retrieve_keras_weights | def retrieve_keras_weights(java_model):
"""For a previously imported Keras model, after training it with DL4J Spark,
we want to set the resulting weights back to the original Keras model.
:param java_model: DL4J model (MultiLayerNetwork or ComputationGraph
:return: list of numpy arrays in correct order for model.set_weights(...) of a corresponding Keras model
"""
weights = []
layers = java_model.getLayers()
for layer in layers:
params = layer.paramTable()
keys = params.keySet()
key_list = java_classes.ArrayList(keys)
for key in key_list:
weight = params.get(key)
np_weight = np.squeeze(to_numpy(weight))
weights.append(np_weight)
return weights | python | def retrieve_keras_weights(java_model):
weights = []
layers = java_model.getLayers()
for layer in layers:
params = layer.paramTable()
keys = params.keySet()
key_list = java_classes.ArrayList(keys)
for key in key_list:
weight = params.get(key)
np_weight = np.squeeze(to_numpy(weight))
weights.append(np_weight)
return weights | [
"def",
"retrieve_keras_weights",
"(",
"java_model",
")",
":",
"weights",
"=",
"[",
"]",
"layers",
"=",
"java_model",
".",
"getLayers",
"(",
")",
"for",
"layer",
"in",
"layers",
":",
"params",
"=",
"layer",
".",
"paramTable",
"(",
")",
"keys",
"=",
"param... | For a previously imported Keras model, after training it with DL4J Spark,
we want to set the resulting weights back to the original Keras model.
:param java_model: DL4J model (MultiLayerNetwork or ComputationGraph
:return: list of numpy arrays in correct order for model.set_weights(...) of a corresponding Keras model | [
"For",
"a",
"previously",
"imported",
"Keras",
"model",
"after",
"training",
"it",
"with",
"DL4J",
"Spark",
"we",
"want",
"to",
"set",
"the",
"resulting",
"weights",
"back",
"to",
"the",
"original",
"Keras",
"model",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/adapter.py#L35-L52 |
233,884 | maxpumperla/elephas | elephas/ml_model.py | ElephasEstimator._fit | def _fit(self, df):
"""Private fit method of the Estimator, which trains the model.
"""
simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(),
features_col=self.getFeaturesCol(), label_col=self.getLabelCol())
simple_rdd = simple_rdd.repartition(self.get_num_workers())
keras_model = model_from_yaml(self.get_keras_model_config())
metrics = self.get_metrics()
loss = self.get_loss()
optimizer = get_optimizer(self.get_optimizer_config())
keras_model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
spark_model = SparkModel(model=keras_model,
mode=self.get_mode(),
frequency=self.get_frequency(),
num_workers=self.get_num_workers())
spark_model.fit(simple_rdd,
epochs=self.get_epochs(),
batch_size=self.get_batch_size(),
verbose=self.get_verbosity(),
validation_split=self.get_validation_split())
model_weights = spark_model.master_network.get_weights()
weights = simple_rdd.ctx.broadcast(model_weights)
return ElephasTransformer(labelCol=self.getLabelCol(),
outputCol='prediction',
keras_model_config=spark_model.master_network.to_yaml(),
weights=weights) | python | def _fit(self, df):
simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(),
features_col=self.getFeaturesCol(), label_col=self.getLabelCol())
simple_rdd = simple_rdd.repartition(self.get_num_workers())
keras_model = model_from_yaml(self.get_keras_model_config())
metrics = self.get_metrics()
loss = self.get_loss()
optimizer = get_optimizer(self.get_optimizer_config())
keras_model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
spark_model = SparkModel(model=keras_model,
mode=self.get_mode(),
frequency=self.get_frequency(),
num_workers=self.get_num_workers())
spark_model.fit(simple_rdd,
epochs=self.get_epochs(),
batch_size=self.get_batch_size(),
verbose=self.get_verbosity(),
validation_split=self.get_validation_split())
model_weights = spark_model.master_network.get_weights()
weights = simple_rdd.ctx.broadcast(model_weights)
return ElephasTransformer(labelCol=self.getLabelCol(),
outputCol='prediction',
keras_model_config=spark_model.master_network.to_yaml(),
weights=weights) | [
"def",
"_fit",
"(",
"self",
",",
"df",
")",
":",
"simple_rdd",
"=",
"df_to_simple_rdd",
"(",
"df",
",",
"categorical",
"=",
"self",
".",
"get_categorical_labels",
"(",
")",
",",
"nb_classes",
"=",
"self",
".",
"get_nb_classes",
"(",
")",
",",
"features_col... | Private fit method of the Estimator, which trains the model. | [
"Private",
"fit",
"method",
"of",
"the",
"Estimator",
"which",
"trains",
"the",
"model",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L72-L99 |
233,885 | maxpumperla/elephas | elephas/ml_model.py | ElephasTransformer._transform | def _transform(self, df):
"""Private transform method of a Transformer. This serves as batch-prediction method for our purposes.
"""
output_col = self.getOutputCol()
label_col = self.getLabelCol()
new_schema = copy.deepcopy(df.schema)
new_schema.add(StructField(output_col, StringType(), True))
rdd = df.rdd.coalesce(1)
features = np.asarray(
rdd.map(lambda x: from_vector(x.features)).collect())
# Note that we collect, since executing this on the rdd would require model serialization once again
model = model_from_yaml(self.get_keras_model_config())
model.set_weights(self.weights.value)
predictions = rdd.ctx.parallelize(
model.predict_classes(features)).coalesce(1)
predictions = predictions.map(lambda x: tuple(str(x)))
results_rdd = rdd.zip(predictions).map(lambda x: x[0] + x[1])
results_df = df.sql_ctx.createDataFrame(results_rdd, new_schema)
results_df = results_df.withColumn(
output_col, results_df[output_col].cast(DoubleType()))
results_df = results_df.withColumn(
label_col, results_df[label_col].cast(DoubleType()))
return results_df | python | def _transform(self, df):
output_col = self.getOutputCol()
label_col = self.getLabelCol()
new_schema = copy.deepcopy(df.schema)
new_schema.add(StructField(output_col, StringType(), True))
rdd = df.rdd.coalesce(1)
features = np.asarray(
rdd.map(lambda x: from_vector(x.features)).collect())
# Note that we collect, since executing this on the rdd would require model serialization once again
model = model_from_yaml(self.get_keras_model_config())
model.set_weights(self.weights.value)
predictions = rdd.ctx.parallelize(
model.predict_classes(features)).coalesce(1)
predictions = predictions.map(lambda x: tuple(str(x)))
results_rdd = rdd.zip(predictions).map(lambda x: x[0] + x[1])
results_df = df.sql_ctx.createDataFrame(results_rdd, new_schema)
results_df = results_df.withColumn(
output_col, results_df[output_col].cast(DoubleType()))
results_df = results_df.withColumn(
label_col, results_df[label_col].cast(DoubleType()))
return results_df | [
"def",
"_transform",
"(",
"self",
",",
"df",
")",
":",
"output_col",
"=",
"self",
".",
"getOutputCol",
"(",
")",
"label_col",
"=",
"self",
".",
"getLabelCol",
"(",
")",
"new_schema",
"=",
"copy",
".",
"deepcopy",
"(",
"df",
".",
"schema",
")",
"new_sch... | Private transform method of a Transformer. This serves as batch-prediction method for our purposes. | [
"Private",
"transform",
"method",
"of",
"a",
"Transformer",
".",
"This",
"serves",
"as",
"batch",
"-",
"prediction",
"method",
"for",
"our",
"purposes",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L146-L171 |
233,886 | maxpumperla/elephas | elephas/java/ndarray.py | _from_numpy | def _from_numpy(np_array):
"""
Convert numpy array to nd4j array
"""
# Convert the numpy array to nd4j context dtype
required_dtype = get_np_dtype(get_context_dtype())
if np_array.dtype != required_dtype:
raise Exception("{} is required, got {}".format(
repr(required_dtype), repr(np_array.dtype)))
# Nd4j does not have 1-d vectors.
# So we add a dummy dimension.
if np_array.ndim == 1:
np_array = np.expand_dims(np_array, 0)
# We have to maintain references to all incoming
# numpy arrays. Else they will get GCed
# creates a Nd4j array from a numpy array
# To create an Nd4j array, we need 3 things:
# buffer, strides, and shape
# Get the buffer
# A buffer is basically an array. To get the buffer object
# we need a pointer to the first element and the size.
pointer_address, _ = np_array.__array_interface__['data']
_refs.append(np_array)
pointer = native_ops.pointerForAddress(pointer_address)
size = np_array.size
mapping = {
np.float64: DoublePointer,
np.float32: FloatPointer,
}
pointer = mapping[required_dtype](pointer)
buff = Nd4j.createBuffer(pointer, size)
assert buff.address() == pointer_address
_refs.append(buff)
# Get the strides
# strides = tuple of bytes to step in each
# dimension when traversing an array.
elem_size = buff.getElementSize()
# Make sure word size is same in both python
# and java worlds
assert elem_size == np_array.dtype.itemsize
strides = np_array.strides
# numpy uses byte wise strides. We have to
# convert it to word wise strides.
strides = [dim / elem_size for dim in strides]
# Finally, shape:
shape = np_array.shape
nd4j_array = Nd4j.create(buff, shape, strides, 0)
assert buff.address() == nd4j_array.data().address()
return nd4j_array | python | def _from_numpy(np_array):
# Convert the numpy array to nd4j context dtype
required_dtype = get_np_dtype(get_context_dtype())
if np_array.dtype != required_dtype:
raise Exception("{} is required, got {}".format(
repr(required_dtype), repr(np_array.dtype)))
# Nd4j does not have 1-d vectors.
# So we add a dummy dimension.
if np_array.ndim == 1:
np_array = np.expand_dims(np_array, 0)
# We have to maintain references to all incoming
# numpy arrays. Else they will get GCed
# creates a Nd4j array from a numpy array
# To create an Nd4j array, we need 3 things:
# buffer, strides, and shape
# Get the buffer
# A buffer is basically an array. To get the buffer object
# we need a pointer to the first element and the size.
pointer_address, _ = np_array.__array_interface__['data']
_refs.append(np_array)
pointer = native_ops.pointerForAddress(pointer_address)
size = np_array.size
mapping = {
np.float64: DoublePointer,
np.float32: FloatPointer,
}
pointer = mapping[required_dtype](pointer)
buff = Nd4j.createBuffer(pointer, size)
assert buff.address() == pointer_address
_refs.append(buff)
# Get the strides
# strides = tuple of bytes to step in each
# dimension when traversing an array.
elem_size = buff.getElementSize()
# Make sure word size is same in both python
# and java worlds
assert elem_size == np_array.dtype.itemsize
strides = np_array.strides
# numpy uses byte wise strides. We have to
# convert it to word wise strides.
strides = [dim / elem_size for dim in strides]
# Finally, shape:
shape = np_array.shape
nd4j_array = Nd4j.create(buff, shape, strides, 0)
assert buff.address() == nd4j_array.data().address()
return nd4j_array | [
"def",
"_from_numpy",
"(",
"np_array",
")",
":",
"# Convert the numpy array to nd4j context dtype",
"required_dtype",
"=",
"get_np_dtype",
"(",
"get_context_dtype",
"(",
")",
")",
"if",
"np_array",
".",
"dtype",
"!=",
"required_dtype",
":",
"raise",
"Exception",
"(",
... | Convert numpy array to nd4j array | [
"Convert",
"numpy",
"array",
"to",
"nd4j",
"array"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L78-L133 |
233,887 | maxpumperla/elephas | elephas/java/ndarray.py | _to_numpy | def _to_numpy(nd4j_array):
"""
Convert nd4j array to numpy array
"""
buff = nd4j_array.data()
address = buff.pointer().address()
dtype = get_context_dtype()
mapping = {
'double': ctypes.c_double,
'float': ctypes.c_float
}
Pointer = ctypes.POINTER(mapping[dtype])
pointer = ctypes.cast(address, Pointer)
np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape()))
return np_array | python | def _to_numpy(nd4j_array):
buff = nd4j_array.data()
address = buff.pointer().address()
dtype = get_context_dtype()
mapping = {
'double': ctypes.c_double,
'float': ctypes.c_float
}
Pointer = ctypes.POINTER(mapping[dtype])
pointer = ctypes.cast(address, Pointer)
np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape()))
return np_array | [
"def",
"_to_numpy",
"(",
"nd4j_array",
")",
":",
"buff",
"=",
"nd4j_array",
".",
"data",
"(",
")",
"address",
"=",
"buff",
".",
"pointer",
"(",
")",
".",
"address",
"(",
")",
"dtype",
"=",
"get_context_dtype",
"(",
")",
"mapping",
"=",
"{",
"'double'",... | Convert nd4j array to numpy array | [
"Convert",
"nd4j",
"array",
"to",
"numpy",
"array"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L136-L150 |
233,888 | maxpumperla/elephas | elephas/utils/rwlock.py | RWLock.acquire_read | def acquire_read(self):
"""
Acquire a read lock. Several threads can hold this typeof lock.
It is exclusive with write locks.
"""
self.monitor.acquire()
while self.rwlock < 0 or self.writers_waiting:
self.readers_ok.wait()
self.rwlock += 1
self.monitor.release() | python | def acquire_read(self):
self.monitor.acquire()
while self.rwlock < 0 or self.writers_waiting:
self.readers_ok.wait()
self.rwlock += 1
self.monitor.release() | [
"def",
"acquire_read",
"(",
"self",
")",
":",
"self",
".",
"monitor",
".",
"acquire",
"(",
")",
"while",
"self",
".",
"rwlock",
"<",
"0",
"or",
"self",
".",
"writers_waiting",
":",
"self",
".",
"readers_ok",
".",
"wait",
"(",
")",
"self",
".",
"rwloc... | Acquire a read lock. Several threads can hold this typeof lock.
It is exclusive with write locks. | [
"Acquire",
"a",
"read",
"lock",
".",
"Several",
"threads",
"can",
"hold",
"this",
"typeof",
"lock",
".",
"It",
"is",
"exclusive",
"with",
"write",
"locks",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L25-L34 |
233,889 | maxpumperla/elephas | elephas/utils/rwlock.py | RWLock.acquire_write | def acquire_write(self):
"""
Acquire a write lock. Only one thread can hold this lock, and
only when no read locks are also held.
"""
self.monitor.acquire()
while self.rwlock != 0:
self.writers_waiting += 1
self.writers_ok.wait()
self.writers_waiting -= 1
self.rwlock = -1
self.monitor.release() | python | def acquire_write(self):
self.monitor.acquire()
while self.rwlock != 0:
self.writers_waiting += 1
self.writers_ok.wait()
self.writers_waiting -= 1
self.rwlock = -1
self.monitor.release() | [
"def",
"acquire_write",
"(",
"self",
")",
":",
"self",
".",
"monitor",
".",
"acquire",
"(",
")",
"while",
"self",
".",
"rwlock",
"!=",
"0",
":",
"self",
".",
"writers_waiting",
"+=",
"1",
"self",
".",
"writers_ok",
".",
"wait",
"(",
")",
"self",
".",... | Acquire a write lock. Only one thread can hold this lock, and
only when no read locks are also held. | [
"Acquire",
"a",
"write",
"lock",
".",
"Only",
"one",
"thread",
"can",
"hold",
"this",
"lock",
"and",
"only",
"when",
"no",
"read",
"locks",
"are",
"also",
"held",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L36-L47 |
233,890 | maxpumperla/elephas | elephas/utils/rwlock.py | RWLock.release | def release(self):
"""
Release a lock, whether read or write.
"""
self.monitor.acquire()
if self.rwlock < 0:
self.rwlock = 0
else:
self.rwlock -= 1
wake_writers = self.writers_waiting and self.rwlock == 0
wake_readers = self.writers_waiting == 0
self.monitor.release()
if wake_writers:
self.writers_ok.acquire()
self.writers_ok.notify()
self.writers_ok.release()
elif wake_readers:
self.readers_ok.acquire()
self.readers_ok.notifyAll()
self.readers_ok.release() | python | def release(self):
self.monitor.acquire()
if self.rwlock < 0:
self.rwlock = 0
else:
self.rwlock -= 1
wake_writers = self.writers_waiting and self.rwlock == 0
wake_readers = self.writers_waiting == 0
self.monitor.release()
if wake_writers:
self.writers_ok.acquire()
self.writers_ok.notify()
self.writers_ok.release()
elif wake_readers:
self.readers_ok.acquire()
self.readers_ok.notifyAll()
self.readers_ok.release() | [
"def",
"release",
"(",
"self",
")",
":",
"self",
".",
"monitor",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"rwlock",
"<",
"0",
":",
"self",
".",
"rwlock",
"=",
"0",
"else",
":",
"self",
".",
"rwlock",
"-=",
"1",
"wake_writers",
"=",
"self",
".... | Release a lock, whether read or write. | [
"Release",
"a",
"lock",
"whether",
"read",
"or",
"write",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L49-L68 |
233,891 | maxpumperla/elephas | elephas/ml/adapter.py | to_data_frame | def to_data_frame(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into Spark DataFrame
"""
lp_rdd = to_labeled_point(sc, features, labels, categorical)
sql_context = SQLContext(sc)
df = sql_context.createDataFrame(lp_rdd)
return df | python | def to_data_frame(sc, features, labels, categorical=False):
lp_rdd = to_labeled_point(sc, features, labels, categorical)
sql_context = SQLContext(sc)
df = sql_context.createDataFrame(lp_rdd)
return df | [
"def",
"to_data_frame",
"(",
"sc",
",",
"features",
",",
"labels",
",",
"categorical",
"=",
"False",
")",
":",
"lp_rdd",
"=",
"to_labeled_point",
"(",
"sc",
",",
"features",
",",
"labels",
",",
"categorical",
")",
"sql_context",
"=",
"SQLContext",
"(",
"sc... | Convert numpy arrays of features and labels into Spark DataFrame | [
"Convert",
"numpy",
"arrays",
"of",
"features",
"and",
"labels",
"into",
"Spark",
"DataFrame"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L9-L15 |
233,892 | maxpumperla/elephas | elephas/ml/adapter.py | from_data_frame | def from_data_frame(df, categorical=False, nb_classes=None):
"""Convert DataFrame back to pair of numpy arrays
"""
lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features))
features, labels = from_labeled_point(lp_rdd, categorical, nb_classes)
return features, labels | python | def from_data_frame(df, categorical=False, nb_classes=None):
lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features))
features, labels = from_labeled_point(lp_rdd, categorical, nb_classes)
return features, labels | [
"def",
"from_data_frame",
"(",
"df",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"lp_rdd",
"=",
"df",
".",
"rdd",
".",
"map",
"(",
"lambda",
"row",
":",
"LabeledPoint",
"(",
"row",
".",
"label",
",",
"row",
".",
"featu... | Convert DataFrame back to pair of numpy arrays | [
"Convert",
"DataFrame",
"back",
"to",
"pair",
"of",
"numpy",
"arrays"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L18-L23 |
233,893 | maxpumperla/elephas | elephas/ml/adapter.py | df_to_simple_rdd | def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'):
"""Convert DataFrame into RDD of pairs
"""
sql_context = df.sql_ctx
sql_context.registerDataFrameAsTable(df, "temp_table")
selected_df = sql_context.sql(
"SELECT {0} AS features, {1} as label from temp_table".format(features_col, label_col))
if isinstance(selected_df.first().features, MLLibVector):
lp_rdd = selected_df.rdd.map(
lambda row: LabeledPoint(row.label, row.features))
else:
lp_rdd = selected_df.rdd.map(lambda row: LabeledPoint(
row.label, MLLibVectors.fromML(row.features)))
rdd = lp_to_simple_rdd(lp_rdd, categorical, nb_classes)
return rdd | python | def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'):
sql_context = df.sql_ctx
sql_context.registerDataFrameAsTable(df, "temp_table")
selected_df = sql_context.sql(
"SELECT {0} AS features, {1} as label from temp_table".format(features_col, label_col))
if isinstance(selected_df.first().features, MLLibVector):
lp_rdd = selected_df.rdd.map(
lambda row: LabeledPoint(row.label, row.features))
else:
lp_rdd = selected_df.rdd.map(lambda row: LabeledPoint(
row.label, MLLibVectors.fromML(row.features)))
rdd = lp_to_simple_rdd(lp_rdd, categorical, nb_classes)
return rdd | [
"def",
"df_to_simple_rdd",
"(",
"df",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
",",
"features_col",
"=",
"'features'",
",",
"label_col",
"=",
"'label'",
")",
":",
"sql_context",
"=",
"df",
".",
"sql_ctx",
"sql_context",
".",
"registe... | Convert DataFrame into RDD of pairs | [
"Convert",
"DataFrame",
"into",
"RDD",
"of",
"pairs"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L26-L40 |
233,894 | maxpumperla/elephas | elephas/spark_model.py | SparkModel.fit | def fit(self, rdd, epochs=10, batch_size=32,
verbose=0, validation_split=0.1):
"""
Train an elephas model on an RDD. The Keras model configuration as specified
in the elephas model is sent to Spark workers, abd each worker will be trained
on their data partition.
:param rdd: RDD with features and labels
:param epochs: number of epochs used for training
:param batch_size: batch size used for training
:param verbose: logging verbosity level (0, 1 or 2)
:param validation_split: percentage of data set aside for validation
"""
print('>>> Fit model')
if self.num_workers:
rdd = rdd.repartition(self.num_workers)
if self.mode in ['asynchronous', 'synchronous', 'hogwild']:
self._fit(rdd, epochs, batch_size, verbose, validation_split)
else:
raise ValueError(
"Choose from one of the modes: asynchronous, synchronous or hogwild") | python | def fit(self, rdd, epochs=10, batch_size=32,
verbose=0, validation_split=0.1):
print('>>> Fit model')
if self.num_workers:
rdd = rdd.repartition(self.num_workers)
if self.mode in ['asynchronous', 'synchronous', 'hogwild']:
self._fit(rdd, epochs, batch_size, verbose, validation_split)
else:
raise ValueError(
"Choose from one of the modes: asynchronous, synchronous or hogwild") | [
"def",
"fit",
"(",
"self",
",",
"rdd",
",",
"epochs",
"=",
"10",
",",
"batch_size",
"=",
"32",
",",
"verbose",
"=",
"0",
",",
"validation_split",
"=",
"0.1",
")",
":",
"print",
"(",
"'>>> Fit model'",
")",
"if",
"self",
".",
"num_workers",
":",
"rdd"... | Train an elephas model on an RDD. The Keras model configuration as specified
in the elephas model is sent to Spark workers, abd each worker will be trained
on their data partition.
:param rdd: RDD with features and labels
:param epochs: number of epochs used for training
:param batch_size: batch size used for training
:param verbose: logging verbosity level (0, 1 or 2)
:param validation_split: percentage of data set aside for validation | [
"Train",
"an",
"elephas",
"model",
"on",
"an",
"RDD",
".",
"The",
"Keras",
"model",
"configuration",
"as",
"specified",
"in",
"the",
"elephas",
"model",
"is",
"sent",
"to",
"Spark",
"workers",
"abd",
"each",
"worker",
"will",
"be",
"trained",
"on",
"their"... | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L133-L154 |
233,895 | maxpumperla/elephas | elephas/spark_model.py | SparkModel._fit | def _fit(self, rdd, epochs, batch_size, verbose, validation_split):
"""Protected train method to make wrapping of modes easier
"""
self._master_network.compile(optimizer=self.master_optimizer,
loss=self.master_loss,
metrics=self.master_metrics)
if self.mode in ['asynchronous', 'hogwild']:
self.start_server()
train_config = self.get_train_config(
epochs, batch_size, verbose, validation_split)
mode = self.parameter_server_mode
freq = self.frequency
optimizer = self.master_optimizer
loss = self.master_loss
metrics = self.master_metrics
custom = self.custom_objects
yaml = self._master_network.to_yaml()
init = self._master_network.get_weights()
parameters = rdd.context.broadcast(init)
if self.mode in ['asynchronous', 'hogwild']:
print('>>> Initialize workers')
worker = AsynchronousSparkWorker(
yaml, parameters, mode, train_config, freq, optimizer, loss, metrics, custom)
print('>>> Distribute load')
rdd.mapPartitions(worker.train).collect()
print('>>> Async training complete.')
new_parameters = self.client.get_parameters()
elif self.mode == 'synchronous':
worker = SparkWorker(yaml, parameters, train_config,
optimizer, loss, metrics, custom)
gradients = rdd.mapPartitions(worker.train).collect()
new_parameters = self._master_network.get_weights()
for grad in gradients: # simply accumulate gradients one by one
new_parameters = subtract_params(new_parameters, grad)
print('>>> Synchronous training complete.')
else:
raise ValueError("Unsupported mode {}".format(self.mode))
self._master_network.set_weights(new_parameters)
if self.mode in ['asynchronous', 'hogwild']:
self.stop_server() | python | def _fit(self, rdd, epochs, batch_size, verbose, validation_split):
self._master_network.compile(optimizer=self.master_optimizer,
loss=self.master_loss,
metrics=self.master_metrics)
if self.mode in ['asynchronous', 'hogwild']:
self.start_server()
train_config = self.get_train_config(
epochs, batch_size, verbose, validation_split)
mode = self.parameter_server_mode
freq = self.frequency
optimizer = self.master_optimizer
loss = self.master_loss
metrics = self.master_metrics
custom = self.custom_objects
yaml = self._master_network.to_yaml()
init = self._master_network.get_weights()
parameters = rdd.context.broadcast(init)
if self.mode in ['asynchronous', 'hogwild']:
print('>>> Initialize workers')
worker = AsynchronousSparkWorker(
yaml, parameters, mode, train_config, freq, optimizer, loss, metrics, custom)
print('>>> Distribute load')
rdd.mapPartitions(worker.train).collect()
print('>>> Async training complete.')
new_parameters = self.client.get_parameters()
elif self.mode == 'synchronous':
worker = SparkWorker(yaml, parameters, train_config,
optimizer, loss, metrics, custom)
gradients = rdd.mapPartitions(worker.train).collect()
new_parameters = self._master_network.get_weights()
for grad in gradients: # simply accumulate gradients one by one
new_parameters = subtract_params(new_parameters, grad)
print('>>> Synchronous training complete.')
else:
raise ValueError("Unsupported mode {}".format(self.mode))
self._master_network.set_weights(new_parameters)
if self.mode in ['asynchronous', 'hogwild']:
self.stop_server() | [
"def",
"_fit",
"(",
"self",
",",
"rdd",
",",
"epochs",
",",
"batch_size",
",",
"verbose",
",",
"validation_split",
")",
":",
"self",
".",
"_master_network",
".",
"compile",
"(",
"optimizer",
"=",
"self",
".",
"master_optimizer",
",",
"loss",
"=",
"self",
... | Protected train method to make wrapping of modes easier | [
"Protected",
"train",
"method",
"to",
"make",
"wrapping",
"of",
"modes",
"easier"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L156-L197 |
233,896 | maxpumperla/elephas | elephas/spark_model.py | SparkMLlibModel.fit | def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1,
categorical=False, nb_classes=None):
"""Train an elephas model on an RDD of LabeledPoints
"""
rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes)
rdd = rdd.repartition(self.num_workers)
self._fit(rdd=rdd, epochs=epochs, batch_size=batch_size,
verbose=verbose, validation_split=validation_split) | python | def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1,
categorical=False, nb_classes=None):
rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes)
rdd = rdd.repartition(self.num_workers)
self._fit(rdd=rdd, epochs=epochs, batch_size=batch_size,
verbose=verbose, validation_split=validation_split) | [
"def",
"fit",
"(",
"self",
",",
"labeled_points",
",",
"epochs",
"=",
"10",
",",
"batch_size",
"=",
"32",
",",
"verbose",
"=",
"0",
",",
"validation_split",
"=",
"0.1",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"rdd",
... | Train an elephas model on an RDD of LabeledPoints | [
"Train",
"an",
"elephas",
"model",
"on",
"an",
"RDD",
"of",
"LabeledPoints"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L235-L242 |
233,897 | maxpumperla/elephas | elephas/spark_model.py | SparkMLlibModel.predict | def predict(self, mllib_data):
"""Predict probabilities for an RDD of features
"""
if isinstance(mllib_data, pyspark.mllib.linalg.Matrix):
return to_matrix(self._master_network.predict(from_matrix(mllib_data)))
elif isinstance(mllib_data, pyspark.mllib.linalg.Vector):
return to_vector(self._master_network.predict(from_vector(mllib_data)))
else:
raise ValueError(
'Provide either an MLLib matrix or vector, got {}'.format(mllib_data.__name__)) | python | def predict(self, mllib_data):
if isinstance(mllib_data, pyspark.mllib.linalg.Matrix):
return to_matrix(self._master_network.predict(from_matrix(mllib_data)))
elif isinstance(mllib_data, pyspark.mllib.linalg.Vector):
return to_vector(self._master_network.predict(from_vector(mllib_data)))
else:
raise ValueError(
'Provide either an MLLib matrix or vector, got {}'.format(mllib_data.__name__)) | [
"def",
"predict",
"(",
"self",
",",
"mllib_data",
")",
":",
"if",
"isinstance",
"(",
"mllib_data",
",",
"pyspark",
".",
"mllib",
".",
"linalg",
".",
"Matrix",
")",
":",
"return",
"to_matrix",
"(",
"self",
".",
"_master_network",
".",
"predict",
"(",
"fro... | Predict probabilities for an RDD of features | [
"Predict",
"probabilities",
"for",
"an",
"RDD",
"of",
"features"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L244-L253 |
233,898 | maxpumperla/elephas | elephas/worker.py | SparkWorker.train | def train(self, data_iterator):
"""Train a keras model on a worker
"""
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_yaml(self.yaml, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=self.master_metrics)
self.model.set_weights(self.parameters.value)
feature_iterator, label_iterator = tee(data_iterator, 2)
x_train = np.asarray([x for x, y in feature_iterator])
y_train = np.asarray([y for x, y in label_iterator])
self.model.compile(optimizer=self.master_optimizer,
loss=self.master_loss,
metrics=self.master_metrics)
weights_before_training = self.model.get_weights()
if x_train.shape[0] > self.train_config.get('batch_size'):
self.model.fit(x_train, y_train, **self.train_config)
weights_after_training = self.model.get_weights()
deltas = subtract_params(
weights_before_training, weights_after_training)
yield deltas | python | def train(self, data_iterator):
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_yaml(self.yaml, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=self.master_metrics)
self.model.set_weights(self.parameters.value)
feature_iterator, label_iterator = tee(data_iterator, 2)
x_train = np.asarray([x for x, y in feature_iterator])
y_train = np.asarray([y for x, y in label_iterator])
self.model.compile(optimizer=self.master_optimizer,
loss=self.master_loss,
metrics=self.master_metrics)
weights_before_training = self.model.get_weights()
if x_train.shape[0] > self.train_config.get('batch_size'):
self.model.fit(x_train, y_train, **self.train_config)
weights_after_training = self.model.get_weights()
deltas = subtract_params(
weights_before_training, weights_after_training)
yield deltas | [
"def",
"train",
"(",
"self",
",",
"data_iterator",
")",
":",
"optimizer",
"=",
"get_optimizer",
"(",
"self",
".",
"master_optimizer",
")",
"self",
".",
"model",
"=",
"model_from_yaml",
"(",
"self",
".",
"yaml",
",",
"self",
".",
"custom_objects",
")",
"sel... | Train a keras model on a worker | [
"Train",
"a",
"keras",
"model",
"on",
"a",
"worker"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L26-L49 |
233,899 | maxpumperla/elephas | elephas/worker.py | AsynchronousSparkWorker.train | def train(self, data_iterator):
"""Train a keras model on a worker and send asynchronous updates
to parameter server
"""
feature_iterator, label_iterator = tee(data_iterator, 2)
x_train = np.asarray([x for x, y in feature_iterator])
y_train = np.asarray([y for x, y in label_iterator])
if x_train.size == 0:
return
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_yaml(self.yaml, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=self.master_metrics)
self.model.set_weights(self.parameters.value)
epochs = self.train_config['epochs']
batch_size = self.train_config.get('batch_size')
nb_train_sample = x_train.shape[0]
nb_batch = int(np.ceil(nb_train_sample / float(batch_size)))
index_array = np.arange(nb_train_sample)
batches = [
(i * batch_size, min(nb_train_sample, (i + 1) * batch_size))
for i in range(0, nb_batch)
]
if self.frequency == 'epoch':
for epoch in range(epochs):
weights_before_training = self.client.get_parameters()
self.model.set_weights(weights_before_training)
self.train_config['epochs'] = 1
if x_train.shape[0] > batch_size:
self.model.fit(x_train, y_train, **self.train_config)
self.train_config['epochs'] = epochs
weights_after_training = self.model.get_weights()
deltas = subtract_params(
weights_before_training, weights_after_training)
self.client.update_parameters(deltas)
elif self.frequency == 'batch':
for epoch in range(epochs):
if x_train.shape[0] > batch_size:
for (batch_start, batch_end) in batches:
weights_before_training = self.client.get_parameters()
self.model.set_weights(weights_before_training)
batch_ids = index_array[batch_start:batch_end]
x = slice_arrays(x_train, batch_ids)
y = slice_arrays(y_train, batch_ids)
self.model.train_on_batch(x, y)
weights_after_training = self.model.get_weights()
deltas = subtract_params(
weights_before_training, weights_after_training)
self.client.update_parameters(deltas)
else:
raise ValueError(
'frequency parameter can be `epoch` or `batch, got {}'.format(self.frequency))
yield [] | python | def train(self, data_iterator):
feature_iterator, label_iterator = tee(data_iterator, 2)
x_train = np.asarray([x for x, y in feature_iterator])
y_train = np.asarray([y for x, y in label_iterator])
if x_train.size == 0:
return
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_yaml(self.yaml, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=self.master_metrics)
self.model.set_weights(self.parameters.value)
epochs = self.train_config['epochs']
batch_size = self.train_config.get('batch_size')
nb_train_sample = x_train.shape[0]
nb_batch = int(np.ceil(nb_train_sample / float(batch_size)))
index_array = np.arange(nb_train_sample)
batches = [
(i * batch_size, min(nb_train_sample, (i + 1) * batch_size))
for i in range(0, nb_batch)
]
if self.frequency == 'epoch':
for epoch in range(epochs):
weights_before_training = self.client.get_parameters()
self.model.set_weights(weights_before_training)
self.train_config['epochs'] = 1
if x_train.shape[0] > batch_size:
self.model.fit(x_train, y_train, **self.train_config)
self.train_config['epochs'] = epochs
weights_after_training = self.model.get_weights()
deltas = subtract_params(
weights_before_training, weights_after_training)
self.client.update_parameters(deltas)
elif self.frequency == 'batch':
for epoch in range(epochs):
if x_train.shape[0] > batch_size:
for (batch_start, batch_end) in batches:
weights_before_training = self.client.get_parameters()
self.model.set_weights(weights_before_training)
batch_ids = index_array[batch_start:batch_end]
x = slice_arrays(x_train, batch_ids)
y = slice_arrays(y_train, batch_ids)
self.model.train_on_batch(x, y)
weights_after_training = self.model.get_weights()
deltas = subtract_params(
weights_before_training, weights_after_training)
self.client.update_parameters(deltas)
else:
raise ValueError(
'frequency parameter can be `epoch` or `batch, got {}'.format(self.frequency))
yield [] | [
"def",
"train",
"(",
"self",
",",
"data_iterator",
")",
":",
"feature_iterator",
",",
"label_iterator",
"=",
"tee",
"(",
"data_iterator",
",",
"2",
")",
"x_train",
"=",
"np",
".",
"asarray",
"(",
"[",
"x",
"for",
"x",
",",
"y",
"in",
"feature_iterator",
... | Train a keras model on a worker and send asynchronous updates
to parameter server | [
"Train",
"a",
"keras",
"model",
"on",
"a",
"worker",
"and",
"send",
"asynchronous",
"updates",
"to",
"parameter",
"server"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L77-L133 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.