signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def process_block(self, block): | ret = []<EOL>output = None<EOL>input_lines = None<EOL>lineno = self.IP.execution_count<EOL>input_prompt = self.promptin%lineno<EOL>output_prompt = self.promptout%lineno<EOL>image_file = None<EOL>image_directive = None<EOL>for token, data in block:<EOL><INDENT>if token==COMMENT:<EOL><INDENT>out_data = self.process_comme... | process block from the block_parser and return a list of processed lines | f5151:c0:m8 |
def process_pure_python(self, content): | output = []<EOL>savefig = False <EOL>multiline = False <EOL>fmtin = self.promptin<EOL>for lineno, line in enumerate(content):<EOL><INDENT>line_stripped = line.strip()<EOL>if not len(line):<EOL><INDENT>output.append(line) <EOL>continue<EOL><DEDENT>if line_stripped.startswith('<STR_LIT:@>'):<EOL><INDENT>output.extend([li... | content is a list of strings. it is unedited directive conent
This runs it line by line in the InteractiveShell, prepends
prompts as needed capturing stderr and stdout, then returns
the content as a list as if it were ipython code | f5151:c0:m10 |
def process_pure_python2(self, content): | output = []<EOL>savefig = False <EOL>multiline = False <EOL>multiline_start = None<EOL>fmtin = self.promptin<EOL>ct = <NUM_LIT:0><EOL>content = [line for line in content if len(line.strip()) > <NUM_LIT:0>]<EOL>for lineno, line in enumerate(content):<EOL><INDENT>line_stripped = line.strip()<EOL>if not len(line):<EOL><IN... | content is a list of strings. it is unedited directive conent
This runs it line by line in the InteractiveShell, prepends
prompts as needed capturing stderr and stdout, then returns
the content as a list as if it were ipython code | f5151:c0:m11 |
def setup(app): | <EOL>pass<EOL> | Setup as a sphinx extension. | f5152:m0 |
def __init__(self, weights_file: str=None, min_face_size: int=<NUM_LIT:20>, steps_threshold: list=None,<EOL>scale_factor: float=<NUM_LIT>): | if steps_threshold is None:<EOL><INDENT>steps_threshold = [<NUM_LIT>, <NUM_LIT>, <NUM_LIT>]<EOL><DEDENT>if weights_file is None:<EOL><INDENT>weights_file = pkg_resources.resource_stream('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>self.__min_face_size = min_face_size<EOL>self.__steps_threshold = steps_threshold<EOL>self.__sca... | Initializes the MTCNN.
:param weights_file: file uri with the weights of the P, R and O networks from MTCNN. By default it will load
the ones bundled with the package.
:param min_face_size: minimum size of the face to detect
:param steps_threshold: step's thresholds values
:param scale_factor: scale factor | f5158:c4:m0 |
@staticmethod<EOL><INDENT>def __scale_image(image, scale: float):<DEDENT> | height, width, _ = image.shape<EOL>width_scaled = int(np.ceil(width * scale))<EOL>height_scaled = int(np.ceil(height * scale))<EOL>im_data = cv2.resize(image, (width_scaled, height_scaled), interpolation=cv2.INTER_AREA)<EOL>im_data_normalized = (im_data - <NUM_LIT>) * <NUM_LIT><EOL>return im_data_normalized<EOL> | Scales the image to a given scale.
:param image:
:param scale:
:return: | f5158:c4:m4 |
@staticmethod<EOL><INDENT>def __nms(boxes, threshold, method):<DEDENT> | if boxes.size == <NUM_LIT:0>:<EOL><INDENT>return np.empty((<NUM_LIT:0>, <NUM_LIT:3>))<EOL><DEDENT>x1 = boxes[:, <NUM_LIT:0>]<EOL>y1 = boxes[:, <NUM_LIT:1>]<EOL>x2 = boxes[:, <NUM_LIT:2>]<EOL>y2 = boxes[:, <NUM_LIT:3>]<EOL>s = boxes[:, <NUM_LIT:4>]<EOL>area = (x2 - x1 + <NUM_LIT:1>) * (y2 - y1 + <NUM_LIT:1>)<EOL>sorted_... | Non Maximum Suppression.
:param boxes: np array with bounding boxes.
:param threshold:
:param method: NMS method to apply. Available values ('Min', 'Union')
:return: | f5158:c4:m6 |
def detect_faces(self, img) -> list: | if img is None or not hasattr(img, "<STR_LIT>"):<EOL><INDENT>raise InvalidImage("<STR_LIT>")<EOL><DEDENT>height, width, _ = img.shape<EOL>stage_status = StageStatus(width=width, height=height)<EOL>m = <NUM_LIT:12> / self.__min_face_size<EOL>min_layer = np.amin([height, width]) * m<EOL>scales = self.__compute_scale_pyra... | Detects bounding boxes from the specified image.
:param img: image to process
:return: list containing all the bounding boxes detected with their keypoints. | f5158:c4:m10 |
def __stage1(self, image, scales: list, stage_status: StageStatus): | total_boxes = np.empty((<NUM_LIT:0>, <NUM_LIT:9>))<EOL>status = stage_status<EOL>for scale in scales:<EOL><INDENT>scaled_image = self.__scale_image(image, scale)<EOL>img_x = np.expand_dims(scaled_image, <NUM_LIT:0>)<EOL>img_y = np.transpose(img_x, (<NUM_LIT:0>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:3>))<EOL>out = self.__p... | First stage of the MTCNN.
:param image:
:param scales:
:param stage_status:
:return: | f5158:c4:m11 |
def __stage2(self, img, total_boxes, stage_status:StageStatus): | num_boxes = total_boxes.shape[<NUM_LIT:0>]<EOL>if num_boxes == <NUM_LIT:0>:<EOL><INDENT>return total_boxes, stage_status<EOL><DEDENT>tempimg = np.zeros(shape=(<NUM_LIT>, <NUM_LIT>, <NUM_LIT:3>, num_boxes))<EOL>for k in range(<NUM_LIT:0>, num_boxes):<EOL><INDENT>tmp = np.zeros((int(stage_status.tmph[k]), int(stage_statu... | Second stage of the MTCNN.
:param img:
:param total_boxes:
:param stage_status:
:return: | f5158:c4:m12 |
def __stage3(self, img, total_boxes, stage_status: StageStatus): | num_boxes = total_boxes.shape[<NUM_LIT:0>]<EOL>if num_boxes == <NUM_LIT:0>:<EOL><INDENT>return total_boxes, np.empty(shape=(<NUM_LIT:0>,))<EOL><DEDENT>total_boxes = np.fix(total_boxes).astype(np.int32)<EOL>status = StageStatus(self.__pad(total_boxes.copy(), stage_status.width, stage_status.height),<EOL>width=stage_stat... | Third stage of the MTCNN.
:param img:
:param total_boxes:
:param stage_status:
:return: | f5158:c4:m13 |
def __init__(self, session, trainable: bool=True): | self._session = session<EOL>self.__trainable = trainable<EOL>self.__layers = {}<EOL>self.__last_layer_name = None<EOL>with tf.variable_scope(self.__class__.__name__.lower()):<EOL><INDENT>self._config()<EOL><DEDENT> | Initializes the network.
:param trainable: flag to determine if this network should be trainable or not. | f5159:c0:m0 |
def _config(self): | raise NotImplementedError("<STR_LIT>")<EOL> | Configures the network layers.
It is usually done using the LayerFactory() class. | f5159:c0:m1 |
def add_layer(self, name: str, layer_output): | self.__layers[name] = layer_output<EOL>self.__last_layer_name = name<EOL> | Adds a layer to the network.
:param name: name of the layer to add
:param layer_output: output layer. | f5159:c0:m2 |
def get_layer(self, name: str=None): | if name is None:<EOL><INDENT>name = self.__last_layer_name<EOL><DEDENT>return self.__layers[name]<EOL> | Retrieves the layer by its name.
:param name: name of the layer to retrieve. If name is None, it will retrieve the last added layer to the
network.
:return: layer output | f5159:c0:m3 |
def is_trainable(self): | return self.__trainable<EOL> | Getter for the trainable flag. | f5159:c0:m4 |
def set_weights(self, weights_values: dict, ignore_missing=False): | network_name = self.__class__.__name__.lower()<EOL>with tf.variable_scope(network_name):<EOL><INDENT>for layer_name in weights_values:<EOL><INDENT>with tf.variable_scope(layer_name, reuse=True):<EOL><INDENT>for param_name, data in weights_values[layer_name].items():<EOL><INDENT>try:<EOL><INDENT>var = tf.get_variable(pa... | Sets the weights values of the network.
:param weights_values: dictionary with weights for each layer | f5159:c0:m5 |
def feed(self, image): | network_name = self.__class__.__name__.lower()<EOL>with tf.variable_scope(network_name):<EOL><INDENT>return self._feed(image)<EOL><DEDENT> | Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result | f5159:c0:m6 |
def __make_var(self, name: str, shape: list): | return tf.get_variable(name, shape, trainable=self.__network.is_trainable())<EOL> | Creates a tensorflow variable with the given name and shape.
:param name: name to set for the variable.
:param shape: list defining the shape of the variable.
:return: created TF variable. | f5160:c0:m4 |
def new_feed(self, name: str, layer_shape: tuple): | feed_data = tf.placeholder(tf.float32, layer_shape, '<STR_LIT:input>')<EOL>self.__network.add_layer(name, layer_output=feed_data)<EOL> | Creates a feed layer. This is usually the first layer in the network.
:param name: name of the layer
:return: | f5160:c0:m5 |
def new_conv(self, name: str, kernel_size: tuple, channels_output: int,<EOL>stride_size: tuple, padding: str='<STR_LIT>',<EOL>group: int=<NUM_LIT:1>, biased: bool=True, relu: bool=True, input_layer_name: str=None): | <EOL>self.__validate_padding(padding)<EOL>input_layer = self.__network.get_layer(input_layer_name)<EOL>channels_input = int(input_layer.get_shape()[-<NUM_LIT:1>])<EOL>self.__validate_grouping(channels_input, channels_output, group)<EOL>convolve = lambda input_val, kernel: tf.nn.conv2d(input_val, kernel, [<NUM_LIT:1>, s... | Creates a convolution layer for the network.
:param name: name for the layer
:param kernel_size: tuple containing the size of the kernel (Width, Height)
:param channels_output: ¿? Perhaps number of channels in the output? it is used as the bias size.
:param stride_size: tuple containing the size of the stride (Width, H... | f5160:c0:m6 |
def new_prelu(self, name: str, input_layer_name: str=None): | input_layer = self.__network.get_layer(input_layer_name)<EOL>with tf.variable_scope(name):<EOL><INDENT>channels_input = int(input_layer.get_shape()[-<NUM_LIT:1>])<EOL>alpha = self.__make_var('<STR_LIT>', shape=[channels_input])<EOL>output = tf.nn.relu(input_layer) + tf.multiply(alpha, -tf.nn.relu(-input_layer))<EOL><DE... | Creates a new prelu layer with the given name and input.
:param name: name for this layer.
:param input_layer_name: name of the layer that serves as input for this one. | f5160:c0:m7 |
def new_max_pool(self, name:str, kernel_size: tuple, stride_size: tuple, padding='<STR_LIT>',<EOL>input_layer_name: str=None): | self.__validate_padding(padding)<EOL>input_layer = self.__network.get_layer(input_layer_name)<EOL>output = tf.nn.max_pool(input_layer,<EOL>ksize=[<NUM_LIT:1>, kernel_size[<NUM_LIT:1>], kernel_size[<NUM_LIT:0>], <NUM_LIT:1>],<EOL>strides=[<NUM_LIT:1>, stride_size[<NUM_LIT:1>], stride_size[<NUM_LIT:0>], <NUM_LIT:1>],<EOL... | Creates a new max pooling layer.
:param name: name for the layer.
:param kernel_size: tuple containing the size of the kernel (Width, Height)
:param stride_size: tuple containing the size of the stride (Width, Height)
:param padding: Type of padding. Available values are: ('SAME', 'VALID')
:param input_layer_name: name... | f5160:c0:m8 |
def new_fully_connected(self, name: str, output_count: int, relu=True, input_layer_name: str=None): | with tf.variable_scope(name):<EOL><INDENT>input_layer = self.__network.get_layer(input_layer_name)<EOL>vectorized_input, dimension = self.vectorize_input(input_layer)<EOL>weights = self.__make_var('<STR_LIT>', shape=[dimension, output_count])<EOL>biases = self.__make_var('<STR_LIT>', shape=[output_count])<EOL>operation... | Creates a new fully connected layer.
:param name: name for the layer.
:param output_count: number of outputs of the fully connected layer.
:param relu: boolean flag to set if ReLu should be applied at the end of this layer.
:param input_layer_name: name of the input layer for this layer. If None, it will take the last... | f5160:c0:m9 |
def new_softmax(self, name, axis, input_layer_name: str=None): | input_layer = self.__network.get_layer(input_layer_name)<EOL>if LooseVersion(tf.__version__) < LooseVersion("<STR_LIT>"):<EOL><INDENT>max_axis = tf.reduce_max(input_layer, axis, keep_dims=True)<EOL>target_exp = tf.exp(input_layer - max_axis)<EOL>normalize = tf.reduce_sum(target_exp, axis, keep_dims=True)<EOL><DEDENT>el... | Creates a new softmax layer
:param name: name to set for the layer
:param axis:
:param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of
the network. | f5160:c0:m10 |
def dameraulevenshtein(seq1, seq2): | <EOL>oneago = None<EOL>thisrow = list(range_(<NUM_LIT:1>, len(seq2) + <NUM_LIT:1>)) + [<NUM_LIT:0>]<EOL>for x in range_(len(seq1)):<EOL><INDENT>twoago, oneago, thisrow = oneago, thisrow, [<NUM_LIT:0>] * len(seq2) + [x + <NUM_LIT:1>]<EOL>for y in range_(len(seq2)):<EOL><INDENT>delcost = oneago[y] + <NUM_LIT:1><EOL>addco... | Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with strings, any sequences of
comparable objects will work.
Transpos... | f5162:m0 |
def evaluation_metrics(predicted, actual, bow=True): | if bow:<EOL><INDENT>p = set(predicted)<EOL>a = set(actual)<EOL>true_positive = <NUM_LIT:0><EOL>for token in p:<EOL><INDENT>if token in a:<EOL><INDENT>true_positive += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>from collections import defaultdict<EOL>act = defaultdict(lambda: <NUM_LIT:0>)<EOL>for token in... | Input:
predicted, actual = lists of the predicted and actual tokens
bow: if true use bag of words assumption
Returns:
precision, recall, F1, Levenshtein distance | f5162:m1 |
def get_and_union_features(features): | if not features:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(features, (list, tuple)):<EOL><INDENT>if isinstance(features[<NUM_LIT:0>], tuple):<EOL><INDENT>return FeatureUnion(features)<EOL><DEDENT>elif isinstance(features[<NUM_LIT:0>], string_):<EOL><INDENT>return FeatureUnion([(feature, get_fe... | Get and combine features in a :class:`FeatureUnion`.
Args:
features (str or List[str], ``Features`` or List[``Features``], or List[Tuple[str, ``Features``]]):
One or more features to be used to transform blocks into a matrix of
numeric values. If more than one, a :class:`FeatureUnion` is
au... | f5162:m2 |
def load_pickled_model(filename, dirname=None): | if dirname is None:<EOL><INDENT>pkg_filename = pkgutil.get_loader('<STR_LIT>').get_filename('<STR_LIT>')<EOL>pkg_dirname = os.path.dirname(pkg_filename)<EOL>dirname = os.path.join(pkg_dirname, '<STR_LIT>', model_path)<EOL><DEDENT>filepath = os.path.join(dirname, filename)<EOL>return joblib.load(filepath)<EOL> | Load a pickled ``Extractor`` model from disk.
Args:
filename (str): Name of pickled model file under ``dirname``.
dirname (str): Name of directory on disk containing the pickled model.
If None, dragnet's default pickled model directory is used:
/path/to/dragnet/pickled_models/[PY_VERSION]_[SKLE... | f5162:m3 |
def str_cast(maybe_bytes, encoding='<STR_LIT:utf-8>'): | if isinstance(maybe_bytes, bytes_):<EOL><INDENT>return maybe_bytes.decode(encoding)<EOL><DEDENT>else:<EOL><INDENT>return maybe_bytes<EOL><DEDENT> | Converts any bytes-like input to a string-like output, with respect to
python version
Parameters
----------
maybe_bytes : if this is a bytes-like object, it will be converted to a string
encoding : str, default='utf-8'
encoding to be used when decoding bytes | f5163:m0 |
def bytes_cast(maybe_str, encoding='<STR_LIT:utf-8>'): | if isinstance(maybe_str, unicode_):<EOL><INDENT>return maybe_str.encode(encoding)<EOL><DEDENT>else:<EOL><INDENT>return maybe_str<EOL><DEDENT> | Converts any string-like input to a bytes-like output, with respect to
python version
Parameters
----------
maybe_str : if this is a string-like object, it will be converted to bytes
encoding : str, default='utf-8'
encoding to be used when encoding string | f5163:m1 |
def str_list_cast(list_, **kwargs): | return [str_cast(elem, **kwargs) for elem in list_]<EOL> | Converts any bytes-like items in input list to string-like values, with
respect to python version
Parameters
----------
list_ : list
any bytes-like objects contained in the list will be converted to
strings
kwargs:
encoding: str, default: 'utf-8'
encoding to be used when decoding bytes | f5163:m2 |
def bytes_list_cast(list_, **kwargs): | return [bytes_cast(elem, **kwargs) for elem in list_]<EOL> | Converts any string-like items in input list to bytes-like values, with
respect to python version
Parameters
----------
list_ : list
any string-like objects contained in the list will be converted to bytes
kwargs:
encoding: str, default: 'utf-8'
encoding to be used when encoding string | f5163:m3 |
def str_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs): | new_keys = str_list_cast(dict_.keys(), **kwargs) if include_keys else dict_.keys()<EOL>new_vals = str_list_cast(dict_.values(), **kwargs) if include_vals else dict_.values()<EOL>new_dict = dict(zip_(new_keys, new_vals))<EOL>return new_dict<EOL> | Converts any bytes-like items in input dict to string-like values, with
respect to python version
Parameters
----------
dict_ : dict
any bytes-like objects contained in the dict will be converted to a
string
include_keys : bool, default=True
if True, cast keys to a string, else ignore
include_values : bool... | f5163:m4 |
def bytes_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs): | new_keys = bytes_list_cast(dict_.keys(), **kwargs) if include_keys else dict_.keys()<EOL>new_vals = bytes_list_cast(dict_.values(), **kwargs) if include_vals else dict_.values()<EOL>new_dict = dict(zip_(new_keys, new_vals))<EOL>return new_dict<EOL> | Converts any string-like items in input dict to bytes-like values, with
respect to python version
Parameters
----------
dict_ : dict
any string-like objects contained in the dict will be converted to bytes
include_keys : bool, default=True
if True, cast keys to bytes, else ignore
include_values : bool, default... | f5163:m5 |
def str_block_cast(block,<EOL>include_text=True,<EOL>include_link_tokens=True,<EOL>include_css=True,<EOL>include_features=True,<EOL>**kwargs): | if include_text:<EOL><INDENT>block.text = str_cast(block.text, **kwargs)<EOL><DEDENT>if include_link_tokens:<EOL><INDENT>block.link_tokens = str_list_cast(block.link_tokens, **kwargs)<EOL><DEDENT>if include_css:<EOL><INDENT>block.css = str_dict_cast(block.css, **kwargs)<EOL><DEDENT>if include_features:<EOL><INDENT>bloc... | Converts any bytes-like items in input Block object to string-like values,
with respect to python version
Parameters
----------
block : blocks.Block
any bytes-like objects contained in the block object will be converted
to a string
include_text : bool, default=True
if True, cast text to a string, else igno... | f5163:m6 |
def bytes_block_cast(block,<EOL>include_text=True,<EOL>include_link_tokens=True,<EOL>include_css=True,<EOL>include_features=True,<EOL>**kwargs): | if include_text:<EOL><INDENT>block.text = bytes_cast(block.text, **kwargs)<EOL><DEDENT>if include_link_tokens:<EOL><INDENT>block.link_tokens = bytes_list_cast(block.link_tokens, **kwargs)<EOL><DEDENT>if include_css:<EOL><INDENT>block.css = bytes_dict_cast(block.css, **kwargs)<EOL><DEDENT>if include_features:<EOL><INDEN... | Converts any string-like items in input Block object to bytes-like values,
with respect to python version
Parameters
----------
block : blocks.Block
any string-like objects contained in the block object will be converted
to bytes
include_text : bool, default=True
if True, cast text to bytes, else ignore
in... | f5163:m7 |
def str_block_list_cast(blocks, **kwargs): | return [str_block_cast(block, **kwargs) for block in blocks]<EOL> | Converts any bytes-like items in input lxml.Blocks to string-like values,
with respect to python version
Parameters
----------
blocks : list[lxml.Block]
any bytes-like objects contained in the block object will be converted
to a string
kwargs:
include_text : bool, default=True
if True, cast text to... | f5163:m8 |
def bytes_block_list_cast(blocks, **kwargs): | return [bytes_block_cast(block, **kwargs) for block in blocks]<EOL> | Converts any string-like items in input lxml.Blocks to bytes-like values,
with respect to python version
Parameters
----------
blocks : list[lxml.Block]
any string-like objects contained in the block object will be converted
to bytes
kwargs:
include_text : bool, default=True
if True, cast text to b... | f5163:m9 |
def evaluate_model_predictions(y_true, y_pred, weights=None): | if isinstance(y_pred[<NUM_LIT:0>], np.ndarray):<EOL><INDENT>y_pred = np.concatenate(y_pred)<EOL><DEDENT>if isinstance(y_true[<NUM_LIT:0>], np.ndarray):<EOL><INDENT>y_true = np.concatenate(y_true)<EOL><DEDENT>if (weights is not None) and (isinstance(weights[<NUM_LIT:0>], np.ndarray)):<EOL><INDENT>weights = np.concatenat... | Evaluate the performance of an extractor model's binary classification
predictions, typically at the block level, of whether a block is content
or not.
Args:
y_true (``np.ndarray``)
y_pred (``np.ndarray``)
weights (``np.ndarray``)
Returns:
Dict[str, float] | f5164:m0 |
def evaluate_extracted_tokens(gold_content, extr_content): | if isinstance(gold_content, string_):<EOL><INDENT>gold_content = simple_tokenizer(gold_content)<EOL><DEDENT>if isinstance(extr_content, string_):<EOL><INDENT>extr_content = simple_tokenizer(extr_content)<EOL><DEDENT>gold_set = set(gold_content)<EOL>extr_set = set(extr_content)<EOL>jaccard = len(gold_set & extr_set) / l... | Evaluate the similarity between gold-standard and extracted content,
typically for a single HTML document, as another way of evaluating the
performance of an extractor model.
Args:
gold_content (str or Sequence[str]): Gold-standard content, either as a
string or as an already-tokenized list of tokens.
... | f5164:m1 |
def train_model(extractor, data_dir, output_dir=None): | <EOL>output_dir, fname_prefix = _set_up_output_dir_and_fname_prefix(output_dir, extractor)<EOL>logging.info('<STR_LIT>')<EOL>data = prepare_all_data(data_dir)<EOL>training_data, test_data = train_test_split(<EOL>data, test_size=<NUM_LIT>, random_state=<NUM_LIT>)<EOL>train_html, train_labels, train_weights = extractor.g... | Train an extractor model, then write train/test block-level classification
performance as well as the model itself to disk in ``output_dir``.
Args:
extractor (:class:`Extractor`): Instance of the ``Extractor`` class to
be trained.
data_dir (str): Directory on disk containing subdirectories for all
... | f5164:m2 |
def train_many_models(extractor, param_grid, data_dir, output_dir=None,<EOL>**kwargs): | <EOL>output_dir, fname_prefix = _set_up_output_dir_and_fname_prefix(output_dir, extractor)<EOL>logging.info('<STR_LIT>')<EOL>data = prepare_all_data(data_dir)<EOL>training_data, test_data = train_test_split(<EOL>data, test_size=<NUM_LIT>, random_state=<NUM_LIT>)<EOL>train_html, train_labels, train_weights = extractor.g... | Train many extractor models, then for the best-scoring model, write
train/test block-level classification performance as well as the model itself
to disk in ``output_dir``.
Args:
extractor (:class:`Extractor`): Instance of the ``Extractor`` class to
be trained.
param_grid (dict or List[dict]): Dictiona... | f5164:m3 |
def extract_all_gold_standard_data(data_dir, nprocesses=<NUM_LIT:1>,<EOL>overwrite=False, **kwargs): | use_pool = nprocesses > <NUM_LIT:1><EOL>if use_pool:<EOL><INDENT>pool = multiprocessing.Pool(processes=nprocesses)<EOL><DEDENT>if overwrite is False:<EOL><INDENT>gs_blocks_dir = os.path.join(data_dir, GOLD_STANDARD_BLOCKS_DIRNAME)<EOL>if not os.path.isdir(gs_blocks_dir):<EOL><INDENT>os.mkdir(gs_blocks_dir)<EOL><DEDENT>... | Extract the gold standard block-level content and comment percentages from a
directory of labeled data (only those for which the gold standard blocks are
not found), and save results to corresponding files in a block-level
gold standard directory under ``data_dir``.
Args:
data_dir (str): Directory on disk containi... | f5165:m0 |
def extract_gold_standard_blocks(data_dir, fileroot, encoding=None,<EOL>tokenizer=simple_tokenizer, cetr=False): | <EOL>raw_html = read_html_file(data_dir, fileroot, encoding=encoding) <EOL>from dragnet.blocks import BlockifyError<EOL>try:<EOL><INDENT>blocks = [b.text for b in Blockifier.blockify(raw_html)] <EOL><DEDENT>except BlockifyError as e:<EOL><INDENT>print('<STR_LIT>'.format(fileroot))<EOL>return<EOL><DEDENT>blocks_tokens... | Extract the gold standard block-level content and comments for a single
observation identified by ``fileroot``, and write the results to file.
Args:
data_dir (str): The root directory containing sub-directories for
raw HTML, gold standard extracted content, and gold standard blocks.
fileroot (str): Uni... | f5165:m1 |
def get_filenames(dirname, full_path=False, match_regex=None, extension=None): | if not os.path.exists(dirname):<EOL><INDENT>raise OSError('<STR_LIT>'.format(dirname))<EOL><DEDENT>match_regex = re.compile(match_regex) if match_regex else None<EOL>for filename in sorted(os.listdir(dirname)):<EOL><INDENT>if extension and not os.path.splitext(filename)[-<NUM_LIT:1>] == extension:<EOL><INDENT>continue<... | Get all filenames under ``dirname`` that match ``match_regex`` or have file
extension equal to ``extension``, optionally prepending the full path.
Args:
dirname (str): /path/to/dir on disk where files to read are saved
full_path (bool): if False, return filenames without path; if True,
return filenames... | f5165:m2 |
def read_html_file(data_dir, fileroot, encoding=None): | fname = os.path.join(<EOL>data_dir, RAW_HTML_DIRNAME, fileroot + RAW_HTML_EXT)<EOL>encodings = (encoding,) if encoding else ('<STR_LIT:utf-8>', '<STR_LIT>') <EOL>for encoding in encodings:<EOL><INDENT>try:<EOL><INDENT>with io.open(fname, mode='<STR_LIT>', encoding=encoding) as f:<EOL><INDENT>raw_html = f.read()<EOL><D... | Read the HTML file corresponding to identifier ``fileroot``
in the raw HTML directory below the root ``data_dir``.
Args:
data_dir (str)
fileroot (str)
encoding (str)
Returns:
str | f5165:m3 |
def read_gold_standard_file(data_dir, fileroot, encoding=None, cetr=False): | fname = os.path.join(<EOL>data_dir, GOLD_STANDARD_DIRNAME, fileroot + GOLD_STANDARD_EXT)<EOL>encodings = (encoding,) if encoding else ('<STR_LIT:utf-8>', '<STR_LIT>', '<STR_LIT>')<EOL>for encoding in encodings:<EOL><INDENT>try:<EOL><INDENT>with io.open(fname, mode='<STR_LIT>', encoding=encoding) as f:<EOL><INDENT>gold_... | Read the gold standard content file corresponding to identifier ``fileroot``
in the gold standard directory below the root ``data_dir``.
Args:
data_dir (str)
fileroot (str)
encoding (str)
cetr (bool): if True, assume no comments and parse the gold standard
to remove tags
Returns:
List[str,... | f5165:m4 |
def read_gold_standard_blocks_file(data_dir, fileroot, split_blocks=True): | fname = os.path.join(<EOL>data_dir, GOLD_STANDARD_BLOCKS_DIRNAME, fileroot + GOLD_STANDARD_BLOCKS_EXT)<EOL>with io.open(fname, mode='<STR_LIT:r>') as f:<EOL><INDENT>data = f.read()<EOL><DEDENT>if split_blocks:<EOL><INDENT>return filter(None, data[:-<NUM_LIT:1>].split('<STR_LIT:\n>'))<EOL><DEDENT>return filter(None, dat... | Read the gold standard blocks file corresponding to identifier ``fileroot``
in the gold standard blocks directory below the root ``data_dir``.
Args:
data_dir (str)
fileroot (str)
split_blocks (bool): If True, split the file's content into blocks.
Returns:
str or List[str] | f5165:m5 |
def prepare_data(data_dir, fileroot, block_pct_tokens_thresh=<NUM_LIT:0.1>): | if not <NUM_LIT:0.0> <= block_pct_tokens_thresh <= <NUM_LIT:1.0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>html = read_html_file(data_dir, fileroot)<EOL>blocks = read_gold_standard_blocks_file(data_dir, fileroot, split_blocks=True)<EOL>content_blocks = []<EOL>comments_blocks = []<EOL>for block in blocks:<E... | Prepare data for a single HTML + gold standard blocks example, uniquely
identified by ``fileroot``.
Args:
data_dir (str)
fileroot (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
Tuple[str, Tuple[np.array[int], np.array[int], List[str]], Tuple[np.array[int], np.array[int], List[st... | f5165:m7 |
def prepare_all_data(data_dir, block_pct_tokens_thresh=<NUM_LIT:0.1>): | gs_blocks_dir = os.path.join(data_dir, GOLD_STANDARD_BLOCKS_DIRNAME)<EOL>gs_blocks_filenames = get_filenames(<EOL>gs_blocks_dir, full_path=False, match_regex=re.escape(GOLD_STANDARD_BLOCKS_EXT))<EOL>gs_blocks_fileroots = (<EOL>re.search(r'<STR_LIT>' + re.escape(GOLD_STANDARD_BLOCKS_EXT), gs_blocks_filename).group(<NUM_... | Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
Args:
data_dir (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
List[Tuple[str, List[float, int, List[str]], List[float, int, List[str]]]]
See Also:
:func:`prepare_data` | f5165:m8 |
def fit(self, documents, labels, weights=None): | block_groups = np.array([self.blockifier.blockify(doc) for doc in documents])<EOL>mask = [self._has_enough_blocks(blocks) for blocks in block_groups]<EOL>block_groups = block_groups[mask]<EOL>labels = np.concatenate(np.array(labels)[mask])<EOL>features_mat = np.concatenate([self.features.fit_transform(blocks)<EOL>for b... | Fit :class`Extractor` features and model to a training dataset.
Args:
blocks (List[Block])
labels (``np.ndarray``)
weights (``np.ndarray``)
Returns:
:class`Extractor` | f5166:c0:m3 |
def get_html_labels_weights(self, data): | all_html = []<EOL>all_labels = []<EOL>all_weights = []<EOL>for html, content, comments in data:<EOL><INDENT>all_html.append(html)<EOL>labels, weights = self._get_labels_and_weights(<EOL>content, comments)<EOL>all_labels.append(labels)<EOL>all_weights.append(weights)<EOL><DEDENT>return np.array(all_html), np.array(all_l... | Gather the html, labels, and weights of many files' data.
Primarily useful for training/testing an :class`Extractor`.
Args:
data: Output of :func:`dragnet.data_processing.prepare_all_data`.
Returns:
Tuple[List[Block], np.array(int), np.array(int)]: All blocks, all
labels, and all weights, respectively... | f5166:c0:m4 |
def _get_labels_and_weights(self, content, comments): | <EOL>if '<STR_LIT:content>' in self.to_extract and '<STR_LIT>' in self.to_extract:<EOL><INDENT>labels = np.logical_or(content[<NUM_LIT:0>], comments[<NUM_LIT:0>]).astype(int)<EOL>weights = content[<NUM_LIT:1>],<EOL><DEDENT>elif '<STR_LIT:content>' in self.to_extract:<EOL><INDENT>labels = content[<NUM_LIT:0>]<EOL>weight... | Args:
content (Tuple[np.array[int], np.array[int], List[str]])
comments (Tuple[np.array[int], np.array[int], List[str]])
Returns:
Tuple[np.array[int], np.array[int], List[str]] | f5166:c0:m6 |
def extract(self, html, encoding=None, as_blocks=False): | preds, blocks = self.predict(html, encoding=encoding, return_blocks=True)<EOL>if as_blocks is False:<EOL><INDENT>return str_cast(b'<STR_LIT:\n>'.join(blocks[ind].text for ind in np.flatnonzero(preds)))<EOL><DEDENT>else:<EOL><INDENT>return [blocks[ind] for ind in np.flatnonzero(preds)]<EOL><DEDENT> | Extract the main content and/or comments from an HTML document and
return it as a string or as a sequence of block objects.
Args:
html (str): HTML document as a string.
encoding (str): Encoding of ``html``. If None (encoding unknown), the
original encoding will be guessed from the HTML itself.
as_b... | f5166:c0:m7 |
def predict(self, documents, **kwargs): | if isinstance(documents, (str, bytes, unicode_, np.unicode_)):<EOL><INDENT>return self._predict_one(documents, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>return np.concatenate([self._predict_one(doc, **kwargs) for doc in documents])<EOL><DEDENT> | Predict class (content=1 or not-content=0) of the blocks in one or many
HTML document(s).
Args:
documents (str or List[str]): HTML document(s)
Returns:
``np.ndarray`` or List[``np.ndarray``]: array of binary predictions
for content (1) or not-content (0). | f5166:c0:m8 |
def _predict_one(self, document, encoding=None, return_blocks=False): | <EOL>blocks = self.blockifier.blockify(document, encoding=encoding)<EOL>try:<EOL><INDENT>features = self.features.transform(blocks)<EOL><DEDENT>except ValueError: <EOL><INDENT>preds = np.zeros((len(blocks)))<EOL><DEDENT>else:<EOL><INDENT>if self.prob_threshold is None:<EOL><INDENT>preds = self.model.predict(features)<E... | Predict class (content=1 or not-content=0) of each block in an HTML
document.
Args:
documents (str): HTML document
Returns:
``np.ndarray``: array of binary predictions for content (1) or
not-content (0). | f5166:c0:m9 |
def fit(self, blocks, y=None): | feature_array = self.feature.fit_transform(blocks)<EOL>self.scaler = self.scaler.fit(feature_array)<EOL>return self<EOL> | Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
:class:`StandardizedFeature`: an instance of this class with the
``self.scaler`` attribute fit to the ``blocks`` data
Note:
When fitting the :class:`Sta... | f5168:c0:m1 |
def transform(self, blocks, y=None): | return self.scaler.transform(self.feature.transform(blocks))<EOL> | Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features) and standardized feature values.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
`np.ndarray`: 2D array of s... | f5168:c0:m2 |
def fit(self, blocks, y=None): | return self<EOL> | This method returns the current instance unchanged, since no fitting is
required for this ``Feature``. It's here only for API consistency. | f5169:c0:m0 |
def transform(self, blocks, y=None): | feature_vecs = (<EOL>tuple(re.search(token, block.css[attrib]) is not None<EOL>for block in blocks)<EOL>for attrib, tokens in self.attribute_tokens<EOL>for token in tokens<EOL>)<EOL>return np.column_stack(tuple(feature_vecs)).astype(int)<EOL> | Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features).
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
`np.ndarray`: 2D array of shape (num blocks, num CSS attrib... | f5169:c0:m1 |
def fit(self, blocks, y=None): | return self<EOL> | This method returns the current instance unchanged, since no fitting is
required for this ``Feature``. It's here only for API consistency. | f5170:c0:m0 |
def transform(self, blocks, y=None): | return make_kohlschuetter_features(blocks)<EOL> | Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features).
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
`np.ndarray`: 2D array of shape (num blocks, 6), where valu... | f5170:c0:m1 |
def get_feature(name): | if name == '<STR_LIT>':<EOL><INDENT>return CSSFeatures()<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>return KohlschuetterFeatures()<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>return ReadabilityFeatures()<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>return WeningerFeatures()<EOL><DEDENT>elif name == '<... | Get an instance of a ``Features`` class by ``name`` (str). | f5171:m0 |
def fit(self, blocks, y=None): | return self<EOL> | This method returns the current instance unchanged, since no fitting is
required for this ``Feature``. It's here only for API consistency. | f5172:c0:m0 |
def transform(self, blocks, y=None): | return make_readability_features(blocks)<EOL> | Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features).
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
`np.ndarray`: 2D array of shape (num blocks, 1) | f5172:c0:m1 |
def fit(self, blocks, y=None): | return self<EOL> | This method returns the current instance unchanged, since no fitting is
required for this ``Feature``. It's here only for API consistency. | f5173:c0:m1 |
def transform(self, blocks, y=None): | return make_weninger_features(blocks, sigma=self.sigma)<EOL> | Computes the content to tag ratio per block and returns the smoothed
values and the smoothed absolute differences for each block.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
:class:`np.ndarray`: 2D array of s... | f5173:c0:m2 |
def fit(self, blocks, y=None): | self.kmeans.fit(make_weninger_features(blocks))<EOL>self.kmeans.cluster_centers_.sort(axis=<NUM_LIT:0>)<EOL>self.kmeans.cluster_centers_[<NUM_LIT:0>, :] = np.zeros(<NUM_LIT:2>)<EOL>return self<EOL> | Fit a k-means clustering model using an ordered sequence of blocks. | f5173:c1:m1 |
def transform(self, blocks, y=None): | preds = (self.kmeans.predict(make_weninger_features(blocks)) > <NUM_LIT:0>).astype(int)<EOL>return np.reshape(preds, (-<NUM_LIT:1>, <NUM_LIT:1>))<EOL> | Computes the content to tag ratio per block, smooths the values, then
predicts content (1) or not-content (0) using a fit k-means cluster model.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
:class:`np.ndarray`... | f5173:c1:m2 |
def block_output_tokens(blocks, true_tokens): | assert len(blocks) == len(true_tokens)<EOL>for k in range_(len(blocks)):<EOL><INDENT>block_tokens = re.split(r"<STR_LIT>", blocks[k].text.strip())<EOL>assert block_tokens == true_tokens[k]<EOL><DEDENT> | blocks = the output from blockify
true_tokens = a list of true tokens | f5178:m1 |
@property<EOL><INDENT>def sources(<EOL>self):<DEDENT> | sourceResultsList = []<EOL>sourceResultsList[:] = [dict(l) for l in self.sourceResultsList]<EOL>return sourceResultsList<EOL> | *The results of the search returned as a python list of dictionaries*
**Usage:**
.. code-block:: python
sources = tns.sources | f5187:c0:m1 |
@property<EOL><INDENT>def spectra(<EOL>self):<DEDENT> | specResultsList = []<EOL>specResultsList[:] = [dict(l) for l in self.specResultsList]<EOL>return specResultsList<EOL> | *The associated source spectral data*
**Usage:**
.. code-block:: python
sourceSpectra = tns.spectra | f5187:c0:m2 |
@property<EOL><INDENT>def files(<EOL>self):<DEDENT> | relatedFilesResultsList = []<EOL>relatedFilesResultsList[:] = [dict(l)<EOL>for l in self.relatedFilesResultsList]<EOL>return relatedFilesResultsList<EOL> | *The associated source files*
**Usage:**
.. code-block:: python
sourceFiles = tns.files | f5187:c0:m3 |
@property<EOL><INDENT>def photometry(<EOL>self):<DEDENT> | photResultsList = []<EOL>photResultsList[:] = [dict(l) for l in self.photResultsList]<EOL>return photResultsList<EOL> | *The associated source photometry*
**Usage:**
.. code-block:: python
sourcePhotometry = tns.photometry | f5187:c0:m4 |
@property<EOL><INDENT>def url(<EOL>self):<DEDENT> | return self._searchURL<EOL> | *The generated URL used for searching of the TNS*
**Usage:**
.. code-block:: python
searchURL = tns.url | f5187:c0:m5 |
def csv(<EOL>self,<EOL>dirPath=None): | if dirPath:<EOL><INDENT>p = self._file_prefix()<EOL>csvSources = self.sourceResults.csv(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>csvPhot = self.photResults.csv(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>csvSpec = self.specResults.csv(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<ST... | *Render the results in csv format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `csvSources` -- the top-level transient data
- `csvPhot` -- all photometry associated with the transients
... | f5187:c0:m6 |
def json(<EOL>self,<EOL>dirPath=None): | if dirPath:<EOL><INDENT>p = self._file_prefix()<EOL>jsonSources = self.sourceResults.json(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>jsonPhot = self.photResults.json(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>jsonSpec = self.specResults.json(<EOL>filepath=dirPath + "<STR_LIT:/>" + p ... | *Render the results in json format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `jsonSources` -- the top-level transient data
- `jsonPhot` -- all photometry associated with the transient... | f5187:c0:m7 |
def yaml(<EOL>self,<EOL>dirPath=None): | if dirPath:<EOL><INDENT>p = self._file_prefix()<EOL>yamlSources = self.sourceResults.yaml(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>yamlPhot = self.photResults.yaml(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>yamlSpec = self.specResults.yaml(<EOL>filepath=dirPath + "<STR_LIT:/>" + p ... | *Render the results in yaml format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `yamlSources` -- the top-level transient data
- `yamlPhot` -- all photometry associated with the transient... | f5187:c0:m8 |
def markdown(<EOL>self,<EOL>dirPath=None): | if dirPath:<EOL><INDENT>p = self._file_prefix()<EOL>markdownSources = self.sourceResults.markdown(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>markdownPhot = self.photResults.markdown(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>markdownSpec = self.specResults.markdown(<EOL>filepath=dirP... | *Render the results in markdown format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `markdownSources` -- the top-level transient data
- `markdownPhot` -- all photometry associated with t... | f5187:c0:m9 |
def table(<EOL>self,<EOL>dirPath=None): | if dirPath:<EOL><INDENT>p = self._file_prefix()<EOL>tableSources = self.sourceResults.table(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>tablePhot = self.photResults.table(<EOL>filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>")<EOL>tableSpec = self.specResults.table(<EOL>filepath=dirPath + "<STR_LIT:/>... | *Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data
- `tablePhot` -- all photometry associated with the tran... | f5187:c0:m10 |
def mysql(<EOL>self,<EOL>tableNamePrefix="<STR_LIT>",<EOL>dirPath=None): | if dirPath:<EOL><INDENT>p = self._file_prefix()<EOL>createStatement = """<STR_LIT>""" % locals()<EOL>mysqlSources = self.sourceResults.mysql(<EOL>tableNamePrefix + "<STR_LIT>", filepath=dirPath + "<STR_LIT:/>" + p + "<STR_LIT>", createStatement=createStatement)<EOL>createStatement = """<STR_LIT>""" % locals()<EOL>mysql... | *Render the results as MySQL Insert statements*
**Key Arguments:**
- ``tableNamePrefix`` -- the prefix for the database table names to assign the insert statements to. Default *TNS*.
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Re... | f5187:c0:m11 |
def _query_tns(self): | self.log.info('<STR_LIT>')<EOL>sourceTable = []<EOL>photoTable = []<EOL>specTable = []<EOL>relatedFilesTable = []<EOL>stop = False<EOL>sourceCount = <NUM_LIT:0><EOL>while not stop:<EOL><INDENT>status_code, content, self._searchURL = self._get_tns_search_results()<EOL>if status_code != <NUM_LIT:200>:<EOL><INDENT>self.lo... | *determine how to query the TNS, send query and parse the results*
**Return:**
- ``results`` -- a list of dictionaries (one dictionary for each result set returned from the TNS) | f5187:c0:m12 |
def _get_tns_search_results(<EOL>self): | self.log.info('<STR_LIT>')<EOL>try:<EOL><INDENT>response = requests.get(<EOL>url="<STR_LIT>",<EOL>params={<EOL>"<STR_LIT>": self.page,<EOL>"<STR_LIT>": self.ra,<EOL>"<STR_LIT>": self.dec,<EOL>"<STR_LIT>": self.radiusArcsec,<EOL>"<STR_LIT:name>": self.name,<EOL>"<STR_LIT>": self.internal_name,<EOL>"<STR_LIT>": self.star... | *query the tns and result the response* | f5187:c0:m13 |
def _file_prefix(<EOL>self): | self.log.info('<STR_LIT>')<EOL>if self.ra:<EOL><INDENT>now = datetime.now()<EOL>prefix = now.strftime("<STR_LIT>")<EOL><DEDENT>elif self.name:<EOL><INDENT>prefix = self.name + "<STR_LIT>"<EOL><DEDENT>elif self.internal_name:<EOL><INDENT>prefix = self.internal_name + "<STR_LIT>"<EOL><DEDENT>elif self.discInLastDays:<EOL... | *Generate a file prefix based on the type of search for saving files to disk*
**Return:**
- ``prefix`` -- the file prefix | f5187:c0:m14 |
def _parse_transient_rows(<EOL>self,<EOL>content,<EOL>count=False): | self.log.info('<STR_LIT>')<EOL>regexForRow = r"""<STR_LIT>"""<EOL>if count:<EOL><INDENT>matchedSources = re.findall(<EOL>regexForRow,<EOL>content,<EOL>flags=re.S <EOL>)<EOL>return len(matchedSources)<EOL><DEDENT>matchedSources = re.finditer(<EOL>regexForRow,<EOL>content,<EOL>flags=re.S <EOL>)<EOL>self.log.info('<STR_... | * parse transient rows from the TNS result page content*
**Key Arguments:**
- ``content`` -- the content from the TNS results page.
- ``count`` -- return only the number of rows
**Return:**
- ``transientRows`` | f5187:c0:m15 |
def _parse_discovery_information(<EOL>self,<EOL>content): | self.log.info('<STR_LIT>')<EOL>converter = unit_conversion(<EOL>log=self.log<EOL>)<EOL>matches = re.finditer(<EOL>r"""<STR_LIT>""",<EOL>content,<EOL>flags=<NUM_LIT:0> <EOL>)<EOL>discoveryData = []<EOL>for match in matches:<EOL><INDENT>row = match.groupdict()<EOL>for k, v in row.items():<EOL><INDENT>row[k] = v.strip()<... | * parse discovery information from one row on the TNS results page*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page.
**Return:**
- ``discoveryData`` -- dictionary of results
- ``TNSId`` -- the unique TNS id for the transient | f5187:c0:m16 |
def _parse_photometry_data(<EOL>self,<EOL>content,<EOL>TNSId): | self.log.info('<STR_LIT>')<EOL>photData = []<EOL>relatedFilesTable = []<EOL>ATBlock = re.search(<EOL>r"""<STR_LIT>""",<EOL>content,<EOL>flags=re.S <EOL>)<EOL>if ATBlock:<EOL><INDENT>ATBlock = ATBlock.group()<EOL>reports = re.finditer(<EOL>r"""<STR_LIT>""",<EOL>ATBlock,<EOL>flags=re.S <EOL>)<EOL>relatedFiles = self._p... | *parse photometry data from a row in the tns results content*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page
- ``TNSId`` -- the tns id of the transient
**Return:**
- ``photData`` -- a list of dictionaries of the photometry data
... | f5187:c0:m17 |
def _parse_related_files(<EOL>self,<EOL>content): | self.log.info('<STR_LIT>')<EOL>relatedFilesList = re.finditer(<EOL>r"""<STR_LIT>""",<EOL>content,<EOL>flags=<NUM_LIT:0> <EOL>)<EOL>relatedFiles = []<EOL>for f in relatedFilesList:<EOL><INDENT>f = f.groupdict()<EOL>relatedFiles.append(f)<EOL><DEDENT>self.log.info('<STR_LIT>')<EOL>return relatedFiles<EOL> | *parse the contents for related files URLs and comments*
**Key Arguments:**
- ``content`` -- the content to parse.
**Return:**
- ``relatedFiles`` -- a list of dictionaries of transient related files | f5187:c0:m18 |
def _parse_spectral_data(<EOL>self,<EOL>content,<EOL>TNSId): | self.log.info('<STR_LIT>')<EOL>specData = []<EOL>relatedFilesTable = []<EOL>classBlock = re.search(<EOL>r"""<STR_LIT>""",<EOL>content,<EOL>flags=re.S <EOL>)<EOL>if classBlock:<EOL><INDENT>classBlock = classBlock.group()<EOL>reports = re.finditer(<EOL>r"""<STR_LIT>""",<EOL>classBlock,<EOL>flags=re.S <EOL>)<EOL>related... | *parse spectra data from a row in the tns results content*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page
- ``TNSId`` -- the tns id of the transient
**Return:**
- ``specData`` -- a list of dictionaries of the spectral data
- ... | f5187:c0:m19 |
def getpackagepath(): | moduleDirectory = os.path.dirname(__file__)<EOL>packagePath = os.path.dirname(__file__) + "<STR_LIT>"<EOL>return packagePath<EOL> | *getpackagepath* | f5188:m0 |
def main(arguments=None): | <EOL>su = tools(<EOL>arguments=arguments,<EOL>docString=__doc__,<EOL>logLevel="<STR_LIT>",<EOL>options_first=False,<EOL>projectName="<STR_LIT>"<EOL>)<EOL>arguments, settings, log, dbConn = su.setup()<EOL>readline.set_completer_delims('<STR_LIT>')<EOL>readline.parse_and_bind("<STR_LIT>")<EOL>readline.set_completer(tab_c... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* | f5190:m1 |
def match(list_a, list_b, not_found='<STR_LIT>', enforce_sublist=False,<EOL>country_data=COUNTRY_DATA_FILE, additional_data=None): | if isinstance(list_a, str):<EOL><INDENT>list_a = [list_a]<EOL><DEDENT>if isinstance(list_b, str):<EOL><INDENT>list_b = [list_b]<EOL><DEDENT>if isinstance(list_a, tuple):<EOL><INDENT>list_a = list(list_a)<EOL><DEDENT>if isinstance(list_b, tuple):<EOL><INDENT>list_b = list(list_b)<EOL><DEDENT>coco = CountryConverter(coun... | Matches the country names given in two lists into a dictionary.
This function matches names given in list_a to the one provided in list_b
using regular expressions defined in country_data.
Parameters
----------
list_a : list
Names of countries to identify
list_b : list
Master l... | f5198:m1 |
def convert(*args, **kargs): | init = {'<STR_LIT>': COUNTRY_DATA_FILE,<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': False}<EOL>init.update({kk: kargs.get(kk) for kk in init.keys() if kk in kargs})<EOL>coco = CountryConverter(**init)<EOL>kargs = {kk: ii for kk, ii in kargs.items() if kk not in init.keys()}<EOL>return coco.convert(*... | Wrapper around CountryConverter.convert()
Uses the same parameters. This function has the same performance as
CountryConverter.convert for one call; for multiple calls it is better to
instantiate a common CountryConverter (this avoid loading the source data
file multiple times).
Note
----
... | f5198:m2 |
def _parse_arg(valid_classifications): | parser = argparse.ArgumentParser(<EOL>description=('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(__version__)<EOL>), prog='<STR_LIT>', usage=('<STR_LIT>'))<EOL>parser.add_argument('<STR_LIT>',<EOL>help=('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' +<EOL>'<STR_LIT:U+002CU+0020>'.join(... | Command line parser for coco
Parameters
----------
valid_classifications: list
Available classifications, used for checking input parameters.
Returns
-------
args : ArgumentParser namespace | f5198:m3 |
def main(): | args = _parse_arg(CountryConverter().valid_class)<EOL>coco = CountryConverter(additional_data=args.additional_data)<EOL>converted_names = coco.convert(<EOL>names=args.names,<EOL>src=args.src,<EOL>to=args.to,<EOL>enforce_list=False,<EOL>not_found=args.not_found)<EOL>print(args.output_sep.join(<EOL>[str(etr) for etr in c... | Main entry point - used for command line call | f5198:m4 |
@staticmethod<EOL><INDENT>def _separate_exclude_cases(name, exclude_prefix):<DEDENT> | excluder = re.compile('<STR_LIT:|>'.join(exclude_prefix))<EOL>split_entries = excluder.split(name)<EOL>return {'<STR_LIT>': split_entries[<NUM_LIT:0>],<EOL>'<STR_LIT>': split_entries[<NUM_LIT:1>:]}<EOL> | Splits the excluded
Parameters
----------
name : str
Name of the country/region to convert.
exclude_prefix : list of valid regex strings
List of indicators which negate the subsequent country/region.
These prefixes and everything following will not b... | f5198:c0:m0 |
def __init__(self, country_data=COUNTRY_DATA_FILE,<EOL>additional_data=None, only_UNmember=False,<EOL>include_obsolete=False): | must_be_unique = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>must_be_string = must_be_unique + (['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>def test_for_unique_names(df, data_name='<STR_LIT>',<EOL>report_fun=logging.error):<EOL><INDENT>for na... | Parameters
----------
country_data : Pandas DataFrame or path to data file
This is by default set to COUNTRY_DATA_FILE - the standard
(tested) country list for coco.
additional_data: (list of) Pandas DataFrames or data files
Additioanl data to include for a specific analysis.
This must be given in the... | f5198:c0:m1 |
def convert(self, names, src=None, to='<STR_LIT>', enforce_list=False,<EOL>not_found='<STR_LIT>',<EOL>exclude_prefix=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']): | <EOL>names = list(names) if (<EOL>isinstance(names, tuple) or<EOL>isinstance(names, set)) else names<EOL>names = names if isinstance(names, list) else [names]<EOL>names = [str(n) for n in names]<EOL>outlist = names.copy()<EOL>to = [self._validate_input_para(to, self.data.columns)]<EOL>exclude_split = {name: self._separ... | Convert names from a list to another list.
Note
----
A lot of the functionality can also be done directly in Pandas
DataFrames.
For example:
coco = CountryConverter()
names = ['USA', 'SWZ', 'PRI']
coco.data[coco.data['ISO3'].isin(names)][['ISO2', 'contine... | f5198:c0:m2 |
def EU28as(self, to='<STR_LIT>'): | if type(to) is str:<EOL><INDENT>to = [to]<EOL><DEDENT>return self.data[self.data.EU < <NUM_LIT>][to]<EOL> | Return EU28 countries in the specified classification
Parameters
----------
to : str, optional
Output classification (valid str for an index of
country_data file), default: name_short
Returns
-------
Pandas DataFrame | f5198:c0:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.