code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
parser = subparsers.add_parser( 'lifetime', description=constants.LIFETIME_DESCRIPTION, epilog=constants.LIFETIME_EPILOG, formatter_class=ParagraphFormatter, help=constants.LIFETIME_HELP) parser.set_defaults(func=lifetime_report) utils.add_tokenizer_argument(parser) utils.ad...
def generate_lifetime_subparser(subparsers)
Adds a sub-command parser to `subparsers` to make a lifetime report.
2.328526
2.257298
1.031555
store = utils.get_data_store(args) corpus = utils.get_corpus(args) if args.catalogue: catalogue = utils.get_catalogue(args) else: catalogue = None store.add_ngrams(corpus, args.min_size, args.max_size, catalogue)
def generate_ngrams(args, parser)
Adds n-grams data to the data store.
3.277057
2.801637
1.169694
parser = subparsers.add_parser( 'ngrams', description=constants.NGRAMS_DESCRIPTION, epilog=constants.NGRAMS_EPILOG, formatter_class=ParagraphFormatter, help=constants.NGRAMS_HELP) parser.set_defaults(func=generate_ngrams) utils.add_common_arguments(parser) parser.add_argumen...
def generate_ngrams_subparser(subparsers)
Adds a sub-command parser to `subparsers` to add n-grams data to the data store.
2.007282
2.047238
0.980483
parser = subparsers.add_parser( 'prepare', description=constants.PREPARE_DESCRIPTION, epilog=constants.PREPARE_EPILOG, formatter_class=ParagraphFormatter, help=constants.PREPARE_HELP) parser.set_defaults(func=prepare_xml) utils.add_common_arguments(parser) parser.add_argumen...
def generate_prepare_subparser(subparsers)
Adds a sub-command parser to `subparsers` to prepare source XML files for stripping.
2.405291
2.364001
1.017466
parser = subparsers.add_parser( 'search', description=constants.SEARCH_DESCRIPTION, epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter, help=constants.SEARCH_HELP) parser.set_defaults(func=search_texts) utils.add_common_arguments(parser) utils.add_db_argument...
def generate_search_subparser(subparsers)
Adds a sub-command parser to `subparsers` to generate search results for a set of n-grams.
2.45235
2.386484
1.0276
parser = subparsers.add_parser( 'stats', description=constants.STATISTICS_DESCRIPTION, formatter_class=ParagraphFormatter, help=constants.STATISTICS_HELP) parser.set_defaults(func=generate_statistics) utils.add_common_arguments(parser) utils.add_corpus_arguments(parser) parser.a...
def generate_statistics_subparser(subparsers)
Adds a sub-command parser to `subparsers` to generate statistics from a set of results.
2.959809
2.901685
1.020031
parser = subparsers.add_parser( 'strip', description=constants.STRIP_DESCRIPTION, epilog=constants.STRIP_EPILOG, formatter_class=ParagraphFormatter, help=constants.STRIP_HELP) parser.set_defaults(func=strip_files) utils.add_common_arguments(parser) parser.add_argument('input...
def generate_strip_subparser(subparsers)
Adds a sub-command parser to `subparsers` to process prepared files for use with the tacl ngrams command.
2.10414
2.143768
0.981515
parser = subparsers.add_parser( 'sdiff', description=constants.SUPPLIED_DIFF_DESCRIPTION, epilog=constants.SUPPLIED_DIFF_EPILOG, formatter_class=ParagraphFormatter, help=constants.SUPPLIED_DIFF_HELP) parser.set_defaults(func=supplied_diff) utils.add_common_arguments(parser) ...
def generate_supplied_diff_subparser(subparsers)
Adds a sub-command parser to `subparsers` to run a diff query using the supplied results sets.
2.650738
2.649847
1.000336
parser = subparsers.add_parser( 'sintersect', description=constants.SUPPLIED_INTERSECT_DESCRIPTION, epilog=constants.SUPPLIED_INTERSECT_EPILOG, formatter_class=ParagraphFormatter, help=constants.SUPPLIED_INTERSECT_HELP) parser.set_defaults(func=supplied_intersect) utils....
def generate_supplied_intersect_subparser(subparsers)
Adds a sub-command parser to `subparsers` to run an intersect query using the supplied results sets.
2.43497
2.516333
0.967666
tokenizer = utils.get_tokenizer(args) corpus = utils.get_corpus(args) output_dir = os.path.abspath(args.output) if os.path.exists(output_dir): parser.exit(status=3, message='Output directory already exists, ' 'aborting.\n') os.makedirs(output_dir, exist_ok=True) ...
def highlight_text(args, parser)
Outputs the result of highlighting a text.
2.824295
2.795323
1.010365
catalogue = utils.get_catalogue(args) tokenizer = utils.get_tokenizer(args) results = tacl.Results(args.results, tokenizer) output_dir = os.path.abspath(args.output) os.makedirs(output_dir, exist_ok=True) report = tacl.LifetimeReport() report.generate(output_dir, catalogue, results, arg...
def lifetime_report(args, parser)
Generates a lifetime report.
4.370699
4.260892
1.025771
store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) store.validate(corpus, catalogue) store.counts(catalogue, sys.stdout)
def ngram_counts(args, parser)
Outputs the results of performing a counts query.
5.101862
4.892623
1.042766
store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) tokenizer = utils.get_tokenizer(args) store.validate(corpus, catalogue) if args.asymmetric: store.diff_asymmetric(catalogue, args.asymmetric, tokenizer, ...
def ngram_diff(args, parser)
Outputs the results of performing a diff query.
3.718074
3.626085
1.025369
store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) store.validate(corpus, catalogue) store.intersection(catalogue, sys.stdout)
def ngram_intersection(args, parser)
Outputs the results of performing an intersection query.
5.263859
5.088349
1.034493
if args.source == constants.TEI_SOURCE_CBETA_GITHUB: corpus_class = tacl.TEICorpusCBETAGitHub else: raise Exception('Unsupported TEI source option provided') corpus = corpus_class(args.input, args.output) corpus.tidy()
def prepare_xml(args, parser)
Prepares XML files for stripping. This process creates a single, normalised TEI XML file for each work.
11.111982
11.953403
0.929608
store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) store.validate(corpus, catalogue) ngrams = [] for ngram_file in args.ngrams: ngrams.extend(utils.get_ngrams(ngram_file)) store.search(catalogue, ngrams, sys.stdout)
def search_texts(args, parser)
Searches texts for presence of n-grams.
3.787799
3.545366
1.06838
stripper = tacl.Stripper(args.input, args.output) stripper.strip_files()
def strip_files(args, parser)
Processes prepared XML files for use with the tacl ngrams command.
8.241524
5.545815
1.48608
# For each flow process the contents for flow in self.input_stream: # Client to Server if flow['direction'] == 'CTS': try: request = dpkt.http.Request(flow['payload']) request_data = data_utils.make_dict(request) ...
def http_meta_data(self)
Pull out the application metadata for each flow in the input_stream
3.54974
3.33188
1.065387
# For each packet in the pcap process the contents for item in self.input_stream: # Get the transport data and type trans_data = item['packet']['data'] trans_type = self._get_transport_type(trans_data) if trans_type and trans_data: ...
def transport_meta_data(self)
Pull out the transport metadata for each packet in the input_stream
5.175003
4.55336
1.136524
if 'flags' not in transport: return None _flag_list = [] flags = transport['flags'] if flags & dpkt.tcp.TH_SYN: if flags & dpkt.tcp.TH_ACK: _flag_list.append('syn_ack') else: _flag_list.append('syn') eli...
def _readable_flags(transport)
Method that turns bit flags into a human readable list Args: transport (dict): transport info, specifically needs a 'flags' key with bit_flags Returns: list: a list of human readable flags (e.g. ['syn_ack', 'fin', 'rst', ...]
1.726327
1.603532
1.076578
chart_data = data.loc[work].sort_values(by=SHARED, ascending=False)[ [SHARED, UNIQUE, COMMON]] csv_path = os.path.join(output_dir, 'breakdown_{}.csv'.format( work)) chart_data.to_csv(csv_path)
def _create_breakdown_chart(self, data, work, output_dir)
Generates and writes to a file in `output_dir` the data used to display a stacked bar chart. The generated data gives the percentages of the text of the work (across all witnesses) that are in common with all other works, shared with each "maybe" work, and unique. :param data: ...
4.291176
3.954529
1.08513
matrix = [] chord_data = data.unstack(BASE_WORK)[SHARED] for index, row_data in chord_data.fillna(value=0).iterrows(): matrix.append([value / 100 for value in row_data]) colours = generate_colours(len(works)) colour_works = [{'work': work, 'colour': colour} f...
def _create_chord_chart(self, data, works, output_dir)
Generates and writes to a file in `output_dir` the data used to display a chord chart. :param data: data to derive the chord data from :type data: `pandas.DataFrame` :param works: works to display :type works: `list` :param output_dir: directory to output data file to ...
3.84838
3.928892
0.979508
nodes = [{'work': work, 'group': 1} for work in works] weights = data.stack().unstack(RELATED_WORK).max() seen = [] links = [] for (source, target), weight in weights.iteritems(): if target not in seen and target != source: seen.append(source)...
def _create_matrix_chart(self, data, works, output_dir)
Generates and writes to a file in `output_dir` the data used to display a matrix chart. :param data: data to derive the matrix data from :type data: `pandas.DataFrame` :param works: works to display :type works: `list` :param output_dir: directory to output data file to ...
3.423804
3.454982
0.990976
chart_data = data[work].dropna().sort_values(by=SHARED_RELATED_WORK, ascending=False) csv_path = os.path.join(output_dir, 'related_{}.csv'.format(work)) chart_data.to_csv(csv_path)
def _create_related_chart(self, data, work, output_dir)
Generates and writes to a file in `output_dir` the data used to display a grouped bar chart. This data gives, for each "maybe" work, the percentage of it that is shared with `work`, and the percentage of `work` that is shared with the "maybe" work. :param data: data to derive t...
4.162075
5.164149
0.805956
results.seek(0) results = Results(results, self._tokenizer) results.remove_label(self._no_label) results.csv(fh)
def _drop_no_label_results(self, results, fh)
Writes `results` to `fh` minus those results associated with the 'no' label. :param results: results to be manipulated :type results: file-like object :param fh: output destination :type fh: file-like object
6.614167
7.896943
0.83756
if not os.path.exists(out_path): report = StatisticsReport(self._corpus, self._tokenizer, results_path) report.generate_statistics() with open(out_path, mode='w', encoding='utf-8', newline='') as fh: report.csv(fh...
def _generate_statistics(self, out_path, results_path)
Writes a statistics report for the results at `results_path` to `out_path`. Reuses an existing statistics report if one exists at `out_path`. :param out_path: path to output statistics report to :type out_path: `str` :param results_path: path of results to generate stat...
3.85936
3.962912
0.97387
distinct_results_path = os.path.join( work_dir, 'distinct_{}.csv'.format(maybe_work)) results = [yn_results_path, ym_results_path] labels = [self._no_label, self._maybe_label] self._run_query(distinct_results_path, self._store.diff_supplied, [...
def _process_diff(self, yes_work, maybe_work, work_dir, ym_results_path, yn_results_path, stats)
Returns statistics on the difference between the intersection of `yes_work` and `maybe_work` and the intersection of `yes_work` and "no" works. :param yes_work: name of work for which stats are collected :type yes_work: `str` :param maybe_work: name of work being compared with `...
5.926621
6.501381
0.911594
catalogue = {yes_work: self._no_label, maybe_work: self._maybe_label} self._run_query(ym_results_path, self._store.intersection, [catalogue], False) # Though this is the intersection only between "yes" and # "maybe", the percentage of overlap is added to ...
def _process_intersection(self, yes_work, maybe_work, work_dir, ym_results_path, stats)
Returns statistics on the intersection between `yes_work` and `maybe_work`. :param yes_work: name of work for which stats are collected :type yes_work: `str` :param maybe_work: name of work being compared with `yes_work` :type maybe_work: `str` :param work_dir: directory...
8.353204
8.609282
0.970256
if maybe_work == yes_work: return stats self._logger.info( 'Processing "maybe" work {} against "yes" work {}.'.format( maybe_work, yes_work)) # Set base values for each statistic of interest, for each # witness. for siglum in self....
def _process_maybe_work(self, yes_work, maybe_work, work_dir, yn_results_path, stats)
Returns statistics of how `yes_work` compares with `maybe_work`. :param yes_work: name of work for which stats are collected :type yes_work: `str` :param maybe_work: name of work being compared with `yes_work` :type maybe_work: `str` :param work_dir: directory where generated fi...
5.630404
5.372463
1.048012
output_data_dir = os.path.join(output_dir, 'data') no_catalogue = {work: self._no_label for work in no_works} self._ym_intersects_dir = os.path.join(output_data_dir, 'ym_intersects') data = {} os.makedirs(self._ym_intersects...
def _process_works(self, maybe_works, no_works, output_dir)
Collect and return the data of how each work in `maybe_works` relates to each other work. :param maybe_works: :type maybe_works: `list` of `str` :param no_works: :type no_works: `list` of `str` :param output_dir: base output directory :type output_dir: `str` ...
3.69156
3.603437
1.024455
self._logger.info('Processing "maybe" work {} as "yes".'.format( yes_work)) stats = {COMMON: {}, SHARED: {}, UNIQUE: {}} yes_work_dir = os.path.join(output_dir, yes_work) os.makedirs(yes_work_dir, exist_ok=True) results_path = os.path.join(yes_work_dir, 'inte...
def _process_yes_work(self, yes_work, no_catalogue, maybe_works, output_dir)
Returns statistics of how `yes_work` compares with the other works in `no_catalogue` and the "maybe" works. :param yes_work: name of work being processed :type yes_work: `str` :param no_catalogue: catalogue of containing `yes_work` and the "no" works ...
3.796655
3.395307
1.118207
if os.path.exists(path): return output_results = io.StringIO(newline='') query(*query_args, output_fh=output_results) with open(path, mode='w', encoding='utf-8', newline='') as fh: if drop_no: self._drop_no_label_results(output_results, fh...
def _run_query(self, path, query, query_args, drop_no=True)
Runs `query` and outputs results to a file at `path`. If `path` exists, the query is not run. :param path: path to output results to :type path: `str` :param query: query to run :type query: `method` :param query_args: arguments to supply to the query :type quer...
3.36091
2.963052
1.134273
self._logger.info('Adding database indices') self._conn.execute(constants.CREATE_INDEX_TEXTNGRAM_SQL) self._logger.info('Indices added')
def _add_indices(self)
Adds the database indices relating to n-grams.
8.064191
4.996406
1.613998
self._initialise_database() if catalogue: for work in catalogue: for witness in corpus.get_witnesses(work): self._add_text_ngrams(witness, minimum, maximum) else: for witness in corpus.get_witnesses(): self._add...
def add_ngrams(self, corpus, minimum, maximum, catalogue=None)
Adds n-gram data from `corpus` to the data store. :param corpus: corpus of works :type corpus: `Corpus` :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` :param catalogue: optional catalogue to limit...
3.589495
3.329803
1.07799
# Remove duplicate n-grams, empty n-grams, and non-string n-grams. ngrams = [ngram for ngram in ngrams if ngram and isinstance(ngram, str)] # Deduplicate while preserving order (useful for testing). seen = {} ngrams = [seen.setdefault(x, x) for x in ngr...
def _add_temporary_ngrams(self, ngrams)
Adds `ngrams` to a temporary table.
2.797546
2.645679
1.057402
NGRAM, SIZE, NAME, SIGLUM, COUNT, LABEL = constants.QUERY_FIELDNAMES reader = csv.DictReader(results) data = [(row[NGRAM], row[SIZE], row[NAME], row[SIGLUM], row[COUNT], label) for row in reader] self._conn.executemany(constants.INSERT_TEMPORARY_RESULTS_SQL, dat...
def _add_temporary_results(self, results, label)
Adds `results` to a temporary table with `label`. :param results: results file :type results: `File` :param label: label to be associated with results :type label: `str`
5.703716
5.901984
0.966407
text_id = self._get_text_id(witness) self._logger.info('Adding n-grams ({} <= n <= {}) for {}'.format( minimum, maximum, witness.get_filename())) skip_sizes = [] for size in range(minimum, maximum + 1): if self._has_ngrams(text_id, size): ...
def _add_text_ngrams(self, witness, minimum, maximum)
Adds n-gram data from `witness` to the data store. :param witness: witness to get n-grams from :type witness: `WitnessText` :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int`
2.861224
2.804785
1.020122
filename = witness.get_filename() name, siglum = witness.get_names() self._logger.info('Adding record for text {}'.format(filename)) checksum = witness.get_checksum() token_count = len(witness.get_tokens()) with self._conn: cursor = self._conn.execute...
def _add_text_record(self, witness)
Adds a Text record for `witness`. :param witness: witness to add a record for :type text: `WitnessText`
4.965434
5.209725
0.953109
unique_ngrams = len(ngrams) self._logger.info('Adding {} unique {}-grams'.format( unique_ngrams, size)) parameters = [[text_id, ngram, size, count] for ngram, count in ngrams.items()] with self._conn: self._conn.execute(constants.INS...
def _add_text_size_ngrams(self, text_id, size, ngrams)
Adds `ngrams`, that are of size `size`, to the data store. The added `ngrams` are associated with `text_id`. :param text_id: database ID of text associated with `ngrams` :type text_id: `int` :param size: size of n-grams :type size: `int` :param ngrams: n-grams to be add...
3.167825
3.072859
1.030905
self._logger.info('Starting analysis of database') self._conn.execute(constants.ANALYSE_SQL.format(table)) self._logger.info('Analysis of database complete')
def _analyse(self, table='')
Analyses the database, or `table` if it is supplied. :param table: optional name of table to analyse :type table: `str`
5.443831
4.924014
1.105568
ngram_tokens = tokenize(row[constants.NGRAM_FIELDNAME]) sub_ngram1 = join(ngram_tokens[:-1]) sub_ngram2 = join(ngram_tokens[1:]) count = constants.COUNT_FIELDNAME discard = False # For performance reasons, avoid searching through matches # unless necessar...
def _check_diff_result(row, matches, tokenize, join)
Returns `row`, possibly with its count changed to 0, depending on the status of the n-grams that compose it. The n-gram represented in `row` can be decomposed into two (n-1)-grams. If neither sub-n-gram is present in `matches`, do not change the count since this is a new difference. ...
3.596566
3.14999
1.141771
labels = list(self._set_labels(catalogue)) label_placeholders = self._get_placeholders(labels) query = constants.SELECT_COUNTS_SQL.format(label_placeholders) self._logger.info('Running counts query') self._logger.debug('Query: {}\nLabels: {}'.format(query, labels)) ...
def counts(self, catalogue, output_fh)
Returns `output_fh` populated with CSV results giving n-gram counts of the witnesses of the works in `catalogue`. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogue` :param output_fh: object to output results to :type output_fh: file-like object...
4.349523
4.468392
0.973398
self._logger.info('Finished query; outputting results in CSV format') # Specify a lineterminator to avoid an extra \r being added on # Windows; see # https://stackoverflow.com/questions/3191528/csv-in-python-adding-extra-carriage-return if sys.platform in ('win32', 'cygw...
def _csv(self, cursor, fieldnames, output_fh)
Writes the rows of `cursor` in CSV format to `output_fh` and returns it. :param cursor: database cursor containing data to be output :type cursor: `sqlite3.Cursor` :param fieldnames: row headings :type fieldnames: `list` :param output_fh: file to write data to :t...
3.450009
3.490861
0.988297
temp_fd, temp_path = tempfile.mkstemp(text=True) with open(temp_fd, 'w', encoding='utf-8', newline='') as results_fh: self._csv(cursor, fieldnames, results_fh) return temp_path
def _csv_temp(self, cursor, fieldnames)
Writes the rows of `cursor` in CSV format to a temporary file and returns the path to that file. :param cursor: database cursor containing data to be output :type cursor: `sqlite3.Cursor` :param fieldnames: row headings :type fieldnames: `list` :rtype: `str`
3.233788
3.3751
0.958131
with self._conn: self._conn.execute(constants.DELETE_TEXT_NGRAMS_SQL, [text_id]) self._conn.execute(constants.DELETE_TEXT_HAS_NGRAMS_SQL, [text_id])
def _delete_text_ngrams(self, text_id)
Deletes all n-grams associated with `text_id` from the data store. :param text_id: database ID of text :type text_id: `int`
3.034001
3.386116
0.896012
temp_path = self._csv_temp(cursor, constants.QUERY_FIELDNAMES) output_fh = self._reduce_diff_results(temp_path, tokenizer, output_fh) try: os.remove(temp_path) except OSError as e: self._logger.error('Failed to remove temporary file containing ' ...
def _diff(self, cursor, tokenizer, output_fh)
Returns output_fh with diff results that have been reduced. Uses a temporary file to store the results from `cursor` before being reduced, in order to not have the results stored in memory twice. :param cursor: database cursor containing raw diff data :type cursor: `sqlite3.Cur...
5.368261
4.644476
1.155838
labels = self._sort_labels(self._set_labels(catalogue)) if len(labels) < 2: raise MalformedQueryError( constants.INSUFFICIENT_LABELS_QUERY_ERROR) label_placeholders = self._get_placeholders(labels) query = constants.SELECT_DIFF_SQL.format(label_placeh...
def diff(self, catalogue, tokenizer, output_fh)
Returns `output_fh` populated with CSV results giving the n-grams that are unique to the witnesses of each labelled set of works in `catalogue`. Note that this is not the same as the symmetric difference of these sets, except in the case where there are only two labels. ...
4.11289
4.424435
0.929585
labels = list(self._set_labels(catalogue)) if len(labels) < 2: raise MalformedQueryError( constants.INSUFFICIENT_LABELS_QUERY_ERROR) try: labels.remove(prime_label) except ValueError: raise MalformedQueryError(constants.LABEL_N...
def diff_asymmetric(self, catalogue, prime_label, tokenizer, output_fh)
Returns `output_fh` populated with CSV results giving the difference in n-grams between the witnesses of labelled sets of works in `catalogue`, limited to those works labelled with `prime_label`. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogu...
3.25515
3.414979
0.953198
self._add_temporary_results_sets(results_filenames, labels) query = constants.SELECT_DIFF_SUPPLIED_SQL self._logger.info('Running supplied diff query') self._logger.debug('Query: {}'.format(query)) self._log_query_plan(query, []) cursor = self._conn.execute(query...
def diff_supplied(self, results_filenames, labels, tokenizer, output_fh)
Returns `output_fh` populated with CSV results giving the n-grams that are unique to the witnesses in each set of works in `results_sets`, using the labels in `labels`. Note that this is not the same as the symmetric difference of these sets, except in the case where there are only two ...
5.520849
5.523767
0.999472
self._logger.info('Dropping database indices') self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL) self._logger.info('Finished dropping database indices')
def _drop_indices(self)
Drops the database indices relating to n-grams.
6.148652
4.086169
1.504747
name, siglum = witness.get_names() text_record = self._conn.execute(constants.SELECT_TEXT_SQL, [name, siglum]).fetchone() if text_record is None: text_id = self._add_text_record(witness) else: text_id = text_record...
def _get_text_id(self, witness)
Returns the database ID of the Text record for `witness`. This may require creating such a record. If `text`\'s checksum does not match an existing record's checksum, the record's checksum is updated and all associated TextNGram and TextHasNGram records are deleted. :param wit...
3.540039
3.056592
1.158165
if self._conn.execute(constants.SELECT_HAS_NGRAMS_SQL, [text_id, size]).fetchone() is None: return False return True
def _has_ngrams(self, text_id, size)
Returns True if a text has existing records for n-grams of size `size`. :param text_id: database ID of text to check :type text_id: `int` :param size: size of n-grams :type size: `int` :rtype: `bool`
5.128483
5.078987
1.009745
self._logger.info('Creating database schema, if necessary') self._conn.execute(constants.CREATE_TABLE_TEXT_SQL) self._conn.execute(constants.CREATE_TABLE_TEXTNGRAM_SQL) self._conn.execute(constants.CREATE_TABLE_TEXTHASNGRAM_SQL) self._conn.execute(constants.CREATE_INDEX_...
def _initialise_database(self)
Creates the database schema. This will not create tables or indices that already exist and is safe to be called on an existing database.
2.942222
2.797553
1.051713
labels = self._sort_labels(self._set_labels(catalogue)) if len(labels) < 2: raise MalformedQueryError( constants.INSUFFICIENT_LABELS_QUERY_ERROR) label_placeholders = self._get_placeholders(labels) subquery = self._get_intersection_subquery(labels) ...
def intersection(self, catalogue, output_fh)
Returns `output_fh` populated with CSV results giving the intersection in n-grams of the witnesses of labelled sets of works in `catalogue`. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogue` :param output_fh: object to output results to ...
4.336921
4.436561
0.977541
self._add_temporary_results_sets(results_filenames, labels) query = constants.SELECT_INTERSECT_SUPPLIED_SQL parameters = [len(labels)] self._logger.info('Running supplied intersect query') self._logger.debug('Query: {}\nNumber of labels: {}'.format( query, pa...
def intersection_supplied(self, results_filenames, labels, output_fh)
Returns `output_fh` populated with CSV results giving the n-grams that are common to witnesses in every set of works in `results_sets`, using the labels in `labels`. :param results_filenames: list of results to be diffed :type results_filenames: `list` of `str` :param labels: la...
5.846199
5.72827
1.020587
self._logger.info('Removing filler results') # For performance, perform the attribute accesses once. tokenize = tokenizer.tokenize join = tokenizer.joiner.join results = [] previous_witness = (None, None) previous_data = {} # Calculate the index o...
def _reduce_diff_results(self, matches_path, tokenizer, output_fh)
Returns `output_fh` populated with a reduced set of data from `matches_fh`. Diff results typically contain a lot of filler results that serve only to hide real differences. If one text has a single extra token than another, the diff between them will have results for every n-gra...
4.050202
3.787131
1.069464
labels = list(self._set_labels(catalogue)) label_placeholders = self._get_placeholders(labels) if ngrams: self._add_temporary_ngrams(ngrams) query = constants.SELECT_SEARCH_SQL.format(label_placeholders) else: query = constants.SELECT_SEARCH_A...
def search(self, catalogue, ngrams, output_fh)
Returns `output_fh` populated with CSV results for each n-gram in `ngrams` that occurs within labelled witnesses in `catalogue`. If `ngrams` is empty, include all n-grams. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogue` :param ngrams: n-gra...
4.212687
4.265351
0.987653
with self._conn: self._conn.execute(constants.UPDATE_LABELS_SQL, ['']) labels = {} for work, label in catalogue.items(): self._conn.execute(constants.UPDATE_LABEL_SQL, [label, work]) cursor = self._conn.execute( con...
def _set_labels(self, catalogue)
Returns a dictionary of the unique labels in `catalogue` and the count of all tokens associated with each, and sets the record of each Text to its corresponding label. Texts that do not have a label specified are set to the empty string. Token counts are included in the results...
3.609505
3.75209
0.961998
labels = list(label_data) labels.sort(key=label_data.get, reverse=True) return labels
def _sort_labels(label_data)
Returns the labels in `label_data` sorted in descending order according to the 'size' (total token count) of their referent corpora. :param label_data: labels (with their token counts) to sort :type: `dict` :rtype: `list`
3.334968
4.206618
0.792791
checksum = witness.get_checksum() token_count = len(witness.get_tokens()) with self._conn: self._conn.execute(constants.UPDATE_TEXT_SQL, [checksum, token_count, text_id])
def _update_text_record(self, witness, text_id)
Updates the record with `text_id` with `witness`\'s checksum and token count. :param withness: witness to update from :type witness: `WitnessText` :param text_id: database ID of Text record :type text_id: `int`
5.220283
3.752461
1.391162
is_valid = True for name in catalogue: count = 0 # It is unfortunate that this creates WitnessText objects # for each work, since that involves reading the file. for witness in corpus.get_witnesses(name): count += 1 ...
def validate(self, corpus, catalogue)
Returns True if all of the files labelled in `catalogue` are up-to-date in the database. :param corpus: corpus of works :type corpus: `Corpus` :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogue` :rtype: `bool`
4.959586
4.697544
1.055783
html = [] for index, char in enumerate(a1): output = self._substitutes.get(char, char) if a2[index] == char: html.append('<span class="match">{}</span>'.format(output)) elif char != '-': html.append(output) return ''.jo...
def _format_alignment(self, a1, a2)
Returns `a1` marked up with HTML spans around characters that are also at the same index in `a2`. :param a1: text sequence from one witness :type a1: `str` :param a2: text sequence from another witness :type a2: `str` :rtype: `str`
3.702808
3.370951
1.098446
f1 = self._format_alignment(self._alignment[0], self._alignment[1]) f2 = self._format_alignment(self._alignment[1], self._alignment[0]) return f1, f2
def render(self)
Returns a tuple of HTML fragments rendering each element of the sequence.
3.887202
3.537497
1.098856
self._output_dir = output_dir # Get a list of the files in the matches, grouped by label # (ordered by number of works). labels = list(self._matches.groupby([constants.LABEL_FIELDNAME])[ constants.WORK_FIELDNAME].nunique().index) original_ngrams = self._match...
def generate(self, output_dir, minimum_size)
Generates sequence reports and writes them to the output directory. :param output_dir: directory to output reports to :type output_dir: `str` :param minimum_size: minimum size of n-grams to create sequences for :type minimum_size: `int`
5.053306
4.912654
1.02863
old_length = 0 self._logger.debug('Match found; generating new sequence') while True: s1, span1 = self._get_text_sequence(t1, t1_span, context_length) s2, span2 = self._get_text_sequence(t2, t2_span, context_length) length = len(s1) alignm...
def _generate_sequence(self, t1, t1_span, t2, t2_span, context_length, covered_spans)
Returns an aligned sequence (or None) between extract `t1_span` of witness text `t1` and extract `t2_span` of witness text `t2`. Adds the span of the aligned sequence, if any, to `covered_spans` (which, being mutable, is modified in place without needing to be returned). This m...
3.553367
3.494213
1.016929
cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME] primary_works = self._matches[self._matches[ constants.LABEL_FIELDNAME] == primary_label][ cols].drop_duplicates() secondary_works = self._matches[self._matches[ constants.LABEL_FIELDNA...
def _generate_sequences(self, primary_label, secondary_label, ngrams)
Generates aligned sequences between each witness labelled `primary_label` and each witness labelled `secondary_label`, based around `ngrams`. :param primary_label: label for one side of the pairs of witnesses to align :type primary_label: `str` :par...
2.81194
2.74424
1.02467
self._logger.debug('Generating sequences for n-gram "{}"'.format( ngram)) pattern = re.compile(re.escape(ngram)) context_length = len(ngram) t1_spans = [match.span() for match in pattern.finditer(t1)] t2_spans = [match.span() for match in pattern.finditer(t2)...
def _generate_sequences_for_ngram(self, t1, t2, ngram, covered_spans)
Generates aligned sequences for the texts `t1` and `t2`, based around `ngram`. Does not generate sequences that occur within `covered_spans`. :param t1: text content of first witness :type t1: `str` :param t2: text content of second witness :type t2: `str` :para...
2.253351
2.188099
1.029821
# self._subsitutes is gradually populated as each text is # processed, so this needs to be regenerated each time. self._reverse_substitutes = dict((v, k) for k, v in self._substitutes.items()) sequences = [] # Keep track of spans ...
def _generate_sequences_for_texts(self, l1, t1, l2, t2, ngrams)
Generates and outputs aligned sequences for the texts `t1` and `t2` from `ngrams`. :param l1: label of first witness :type l1: `str` :param t1: text content of first witness :type t1: `str` :param l2: label of second witness :type l2: `str` :param t2: tex...
4.33505
4.14407
1.046085
tokens = text.get_tokens() for i, token in enumerate(tokens): if len(token) > 1: char = chr(self._char_code) substitute = self._substitutes.setdefault(token, char) if substitute == char: self._char_code += 1 ...
def _get_text(self, text)
Returns the text content of `text`, with all multi-character tokens replaced with a single character. Substitutions are recorded in self._substitutes. :param text: text to get content from :type text: `Text` :rtype: `str`
4.178316
3.610326
1.157324
start = max(0, span[0] - context_length) end = min(len(text), span[1] + context_length) return text[start:end], (start, end)
def _get_text_sequence(self, text, span, context_length)
Returns the subset of `text` encompassed by `span`, plus `context_length` characters before and after. :param text: text to extract the sequence from :type text: `str` :param span: start and end indices within `text` :type span: 2-`tuple` of `int` :param context_length: ...
2.092682
2.468545
0.847739
if self._is_span_inside(span1, covered_spans[0]) and \ self._is_span_inside(span2, covered_spans[1]): return True return False
def _is_inside(self, span1, span2, covered_spans)
Returns True if both `span1` and `span2` fall within `covered_spans`. :param span1: start and end indices of a span :type span1: 2-`tuple` of `int` :param span2: start and end indices of a span :type span2: 2-`tuple` of `int` :param covered_spans: lists of start and end ...
2.384096
2.790845
0.854256
start = span[0] end = span[1] for c_start, c_end in covered_spans: if start >= c_start and end <= c_end: return True return False
def _is_span_inside(self, span, covered_spans)
Returns True if `span` falls within `covered_spans`. :param span: start and end indices of a span :type span: 2-`tuple` of `int` :param covered_spans: list of start and end indices for parts of the text already covered by a sequence :type covered_spans: `li...
2.230603
2.365934
0.942801
add_tokenizer_argument(parser) parser.add_argument('corpus', help=constants.DB_CORPUS_HELP, metavar='CORPUS')
def add_corpus_arguments(parser)
Adds common arguments for commands making use of a corpus to `parser`.
6.827239
7.40813
0.921587
parser.add_argument('-m', '--memory', action='store_true', help=constants.DB_MEMORY_HELP) parser.add_argument('-r', '--ram', default=3, help=constants.DB_RAM_HELP, type=int) if db_option: parser.add_argument('-d', '--db', help=constants.DB_DATABAS...
def add_db_arguments(parser, db_option=False)
Adds common arguments for the database sub-commands to `parser`. `db_option` provides a means to work around https://bugs.python.org/issue9338 whereby a positional argument that follows an optional argument with nargs='+' will not be recognised. When `db_optional` is True, create the database a...
2.249825
2.37983
0.945372
parser.add_argument('-l', '--labels', help=constants.SUPPLIED_LABELS_HELP, nargs='+', required=True) parser.add_argument('-s', '--supplied', help=constants.SUPPLIED_RESULTS_HELP, metavar='RESULTS', nargs='+', required=True)
def add_supplied_query_arguments(parser)
Adds common arguments for supplied query sub-commands to `parser`.
3.250687
3.308069
0.982654
if not verbose: log_level = logging.WARNING elif verbose == 1: log_level = logging.INFO else: log_level = logging.DEBUG logger.setLevel(log_level) ch = colorlog.StreamHandler() ch.setLevel(log_level) formatter = colorlog.ColoredFormatter( '%(log_color)s%(...
def configure_logging(verbose, logger)
Configures the logging used.
1.607435
1.59288
1.009137
catalogue = tacl.Catalogue() catalogue.load(args.catalogue) return catalogue
def get_catalogue(args)
Returns a `tacl.Catalogue`.
6.494517
2.824252
2.299553
tokenizer = get_tokenizer(args) return tacl.Corpus(args.corpus, tokenizer)
def get_corpus(args)
Returns a `tacl.Corpus`.
9.145681
3.707698
2.466674
return tacl.DataStore(args.db, args.memory, args.ram)
def get_data_store(args)
Returns a `tacl.DataStore`.
28.417051
8.853348
3.209752
with open(path, encoding='utf-8') as fh: ngrams = [ngram.strip() for ngram in fh.readlines()] return ngrams
def get_ngrams(path)
Returns a list of n-grams read from the file at `path`.
2.525577
2.423226
1.042237
content = self.get_token_content() ngrams.sort(key=len, reverse=True) for ngram in ngrams: content = content.replace(ngram, replacement) return content
def excise(self, ngrams, replacement)
Returns the token content of this text with every occurrence of each n-gram in `ngrams` replaced with `replacement`. The replacing is performed on each n-gram by descending order of length. :param ngrams: n-grams to be replaced :type ngrams: `list` of `str` :param repla...
3.354004
2.756553
1.216738
skip_sizes = skip_sizes or [] tokens = self.get_tokens() for size in range(minimum, maximum + 1): if size not in skip_sizes: ngrams = collections.Counter(self._ngrams(tokens, size)) yield (size, ngrams)
def get_ngrams(self, minimum, maximum, skip_sizes=None)
Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `...
2.660425
2.939304
0.905121
count = max(0, len(sequence) - degree + 1) # The extra split and join are due to having to handle # whitespace within a CBETA token (eg, [(禾*尤)\n/上/日]). return [self._tokenizer.joiner.join( self._tokenizer.joiner.join(sequence[i:i+degree]).split()) fo...
def _ngrams(self, sequence, degree)
Returns the n-grams generated from `sequence`. Based on the ngrams function from the Natural Language Toolkit. Each n-gram in the returned list is a string with whitespace removed. :param sequence: the source data to be converted into n-grams :type sequence: sequence ...
16.457569
16.865265
0.975826
return re.compile('|'.join([re.escape(ngram) for ngram in filter_ngrams]))
def get_filter_ngrams_pattern(filter_ngrams)
Returns a compiled regular expression matching on any of the n-grams in `filter_ngrams`. :param filter_ngrams: n-grams to use in regular expression :type filter_ngrams: `list` of `str` :rtype: `_sre.SRE_Pattern`
4.434367
4.724836
0.938523
tokens = self.get_tokens() filter_pattern = self.get_filter_ngrams_pattern(filter_ngrams) for size in range(minimum, maximum + 1): ngrams = collections.Counter( self._ngrams(tokens, size, filter_pattern)) yield (size, ngrams)
def get_ngrams(self, minimum, maximum, filter_ngrams)
Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `...
3.378846
3.425723
0.986316
"Set a many-to-many field on an object" relation = getattr(obj, field_name) if hasattr(relation, 'set'): relation.set(objs) # Django 2.x else: setattr(obj, field_name, objs)
def set_relation_many_to_many(self, obj, field_name, objs)
Set a many-to-many field on an object
3.690535
3.357056
1.099337
missing = defaultdict(set) for name, err in exc.error_dict.items(): # check if it was a relationship that doesnt exist locally pattern = r".+ with id (\d+) does not exist.+" m = re.match(pattern, str(err)) if m: field = obj._meta.g...
def detect_missing_relations(self, obj, exc)
Parse error messages and collect the missing-relationship errors as a dict of Resource -> {id set}
4.288648
3.560236
1.204596
pattern = r"(\w+) with this (\w+) already exists" fields = [] if isinstance(exc, IntegrityError): return self._detect_integrity_error(exc) assert isinstance(exc, ValidationError), TypeError for name, err in exc.error_dict.items(): if re.search(p...
def detect_uniqueness_error(self, exc)
Parse error, and if it describes any violations of a uniqueness constraint, return the corresponding fields, else None
5.015265
4.506888
1.1128
# For each flow process the contents for flow in self.input_stream: # Just TCP for now if flow['protocol'] != 'TCP': continue # Client to Server if flow['direction'] == 'CTS': # Try to process the payload as a s...
def tls_meta_data(self)
Pull out the TLS metadata for each flow in the input_stream
2.958695
2.714936
1.089785
# Recursion base case if is_builtin(obj) or isinstance(obj, OrderedDict): return obj output_dict = {} for key in dir(obj): if not key.startswith('__') and not callable(getattr(obj, key)): attr = getattr(obj, key) if isinstance(attr, list): o...
def make_dict(obj)
This method creates a dictionary out of a non-builtin object
2.319219
2.220072
1.044659
ref = data try: for subkey in key.split('.'): if isinstance(ref, dict): ref = ref[subkey] else: print('CRITICAL: Cannot use subkey %s on non-dictionary element' % subkey) return None return ref # In general KeyErro...
def get_value(data, key)
Follow the dot notation to get the proper field, then perform the action Args: data: the data as a dictionary (required to be a dictionary) key: the key (as dot notation) into the data that gives the field (IP.src) Returns: the value of the field(subfield) if it exist, ...
5.107275
6.255292
0.816473
self._stats.to_csv(fh, encoding='utf-8', index=False) return fh
def csv(self, fh)
Writes the report data to `fh` in CSV format and returns it. :param fh: file to write data to :type fh: file object :rtype: file object
5.443301
7.020761
0.775315
matches = self._matches witness_fields = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.LABEL_FIELDNAME] witnesses = matches[witness_fields].drop_duplicates() rows = [] for index, (work, siglum, label) in witnesses.iterrows(): ...
def generate_statistics(self)
Replaces result rows with summary statistics about the results. These statistics give the filename, total matching tokens, percentage of matching tokens and label for each witness in the results.
2.597813
2.300981
1.129002
sliced_text = [] for start, end in slices: sliced_text.append(full_text[start:end]) return self._tokenizer.joiner.join(sliced_text)
def _generate_text_from_slices(self, full_text, slices)
Return a single string consisting of the parts specified in `slices` joined together by the tokenizer's joining string. :param full_text: the text to be sliced :type full_text: `str` :param slices: list of slice indices to apply to `full_text` :type slices: `list` of `list`\s ...
3.332899
2.97531
1.120185
# Sort by earliest range, then by largest range. match_slices.sort(key=lambda x: (x[0], -x[1])) merged_slices = [match_slices.pop(0)] for slice_indices in match_slices: last_end = merged_slices[-1][1] if slice_indices[0] <= last_end: if sl...
def _merge_slices(match_slices)
Return a list of slice indices lists derived from `match_slices` with no overlaps.
2.152625
2.015513
1.068028
# In order to provide a correct count of matched tokens, # avoiding the twin dangers of counting the same token # multiple times due to being part of multiple n-grams (which # can happen even in reduced results) and not counting tokens # due to an n-gram overlapping with...
def _process_witness(self, witness, matches)
Return the counts of total tokens and matching tokens in `witness`. :param witness: witness text :type witness: `tacl.WitnessText` :param matches: n-gram matches :type matches: `pandas.DataFrame` :rtype: `tuple` of `int`
6.382349
6.069409
1.05156
witnesses = [] witness_elements = source_tree.xpath( '/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/' 'tei:listWit/tei:witness', namespaces=constants.NAMESPACES) for witness_element in witness_elements: witnesses.append((witness_element.text, ...
def get_witnesses(self, source_tree)
Returns a list of all witnesses of variant readings in `source_tree` along with their XML ids. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `list` of `tuple`
3.021941
2.765664
1.092664
# Create the classes streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets) meta = packet_meta.PacketMeta() rdns = reverse_dns.ReverseDNS() tags = packet_tags.PacketTags() tmeta = transport_meta.TransportMeta() printer = packet_summary.Packet...
def run(iface_name=None, bpf=None, summary=None, max_packets=50)
Run the Simple Packet Printer Example
3.782767
3.871176
0.977162
data = results.get_raw_data() labels = catalogue.ordered_labels ngrams = self._generate_results(output_dir, labels, data) ngram_table = self._generate_ngram_table(output_dir, labels, data) corpus_table = self._generate_corpus_table(labels, ngrams) context = {'cor...
def generate(self, output_dir, catalogue, results, label)
Generates the report, writing it to `output_dir`.
4.040334
3.856926
1.047553
html = [] for label in labels: html.append(self._render_corpus_row(label, ngrams)) return '\n'.join(html)
def _generate_corpus_table(self, labels, ngrams)
Returns an HTML table containing data on each corpus' n-grams.
3.533023
2.935674
1.203479