signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def extract_from_html(msg_body):
if isinstance(msg_body, six.text_type):<EOL><INDENT>msg_body = msg_body.encode('<STR_LIT:utf8>')<EOL><DEDENT>elif not isinstance(msg_body, bytes):<EOL><INDENT>msg_body = msg_body.encode('<STR_LIT:ascii>')<EOL><DEDENT>result = _extract_from_html(msg_body)<EOL>if isinstance(result, bytes):<EOL><INDENT>result = result.decode('<STR_LIT:utf8>')<EOL><DEDENT>return result<EOL>
Extract not quoted message from provided html message body using tags and plain text algorithm. Cut out the 'blockquote', 'gmail_quote' tags. Cut Microsoft quotations. Then use plain text algorithm to cut out splitter or leftover quotation. This works by adding checkpoint text to all html tags, then converting html to text, then extracting quotations from text, then checking deleted checkpoints, then deleting necessary tags. Returns a unicode string.
f10787:m9
def _extract_from_html(msg_body):
if msg_body.strip() == b'<STR_LIT>':<EOL><INDENT>return msg_body<EOL><DEDENT>msg_body = msg_body.replace(b'<STR_LIT:\r\n>', b'<STR_LIT:\n>')<EOL>msg_body = re.sub(r"<STR_LIT>", "<STR_LIT>", msg_body)<EOL>html_tree = html_document_fromstring(msg_body)<EOL>if html_tree is None:<EOL><INDENT>return msg_body<EOL><DEDENT>cut_quotations = (html_quotations.cut_gmail_quote(html_tree) or<EOL>html_quotations.cut_zimbra_quote(html_tree) or<EOL>html_quotations.cut_blockquote(html_tree) or<EOL>html_quotations.cut_microsoft_quote(html_tree) or<EOL>html_quotations.cut_by_id(html_tree) or<EOL>html_quotations.cut_from_block(html_tree)<EOL>)<EOL>html_tree_copy = deepcopy(html_tree)<EOL>number_of_checkpoints = html_quotations.add_checkpoint(html_tree, <NUM_LIT:0>)<EOL>quotation_checkpoints = [False] * number_of_checkpoints<EOL>plain_text = html_tree_to_text(html_tree)<EOL>plain_text = preprocess(plain_text, '<STR_LIT:\n>', content_type='<STR_LIT>')<EOL>lines = plain_text.splitlines()<EOL>if len(lines) > MAX_LINES_COUNT:<EOL><INDENT>return msg_body<EOL><DEDENT>line_checkpoints = [<EOL>[int(i[<NUM_LIT:4>:-<NUM_LIT:4>]) <EOL>for i in re.findall(html_quotations.CHECKPOINT_PATTERN, line)]<EOL>for line in lines]<EOL>lines = [re.sub(html_quotations.CHECKPOINT_PATTERN, '<STR_LIT>', line)<EOL>for line in lines]<EOL>markers = mark_message_lines(lines)<EOL>return_flags = []<EOL>process_marked_lines(lines, markers, return_flags)<EOL>lines_were_deleted, first_deleted, last_deleted = return_flags<EOL>if not lines_were_deleted and not cut_quotations:<EOL><INDENT>return msg_body<EOL><DEDENT>if lines_were_deleted:<EOL><INDENT>for i in range(first_deleted, last_deleted):<EOL><INDENT>for checkpoint in line_checkpoints[i]:<EOL><INDENT>quotation_checkpoints[checkpoint] = True<EOL><DEDENT><DEDENT>html_quotations.delete_quotation_tags(<EOL>html_tree_copy, <NUM_LIT:0>, quotation_checkpoints<EOL>)<EOL><DEDENT>if _readable_text_empty(html_tree_copy):<EOL><INDENT>return msg_body<EOL><DEDENT>return html.tostring(html_tree_copy)<EOL>
Extract not quoted message from provided html message body using tags and plain text algorithm. Cut out first some encoding html tags such as xml and doctype for avoiding conflict with unicode decoding Cut out the 'blockquote', 'gmail_quote' tags. Cut Microsoft quotations. Then use plain text algorithm to cut out splitter or leftover quotation. This works by adding checkpoint text to all html tags, then converting html to text, then extracting quotations from text, then checking deleted checkpoints, then deleting necessary tags.
f10787:m10
def split_emails(msg):
msg_body = _replace_link_brackets(msg)<EOL>lines = msg_body.splitlines()[:MAX_LINES_COUNT]<EOL>markers = remove_initial_spaces_and_mark_message_lines(lines)<EOL>markers = _mark_quoted_email_splitlines(markers, lines)<EOL>markers = _correct_splitlines_in_headers(markers, lines)<EOL>return markers<EOL>
Given a message (which may consist of an email conversation thread with multiple emails), mark the lines to identify split lines, content lines and empty lines. Correct the split line markers inside header blocks. Header blocks are identified by the regular expression RE_HEADER. Return the corrected markers
f10787:m11
def _mark_quoted_email_splitlines(markers, lines):
<EOL>markerlist = list(markers)<EOL>for i, line in enumerate(lines):<EOL><INDENT>if markerlist[i] != '<STR_LIT:m>':<EOL><INDENT>continue<EOL><DEDENT>for pattern in SPLITTER_PATTERNS:<EOL><INDENT>matcher = re.search(pattern, line)<EOL>if matcher:<EOL><INDENT>markerlist[i] = '<STR_LIT:s>'<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return "<STR_LIT>".join(markerlist)<EOL>
When there are headers indented with '>' characters, this method will attempt to identify if the header is a splitline header. If it is, then we mark it with 's' instead of leaving it as 'm' and return the new markers.
f10787:m12
def _correct_splitlines_in_headers(markers, lines):
updated_markers = "<STR_LIT>"<EOL>i = <NUM_LIT:0><EOL>in_header_block = False<EOL>for m in markers:<EOL><INDENT>if m == '<STR_LIT:s>':<EOL><INDENT>if not in_header_block:<EOL><INDENT>if bool(re.search(RE_HEADER, lines[i])):<EOL><INDENT>in_header_block = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if QUOT_PATTERN.match(lines[i]):<EOL><INDENT>m = '<STR_LIT:m>'<EOL><DEDENT>else:<EOL><INDENT>m = '<STR_LIT:t>'<EOL><DEDENT><DEDENT><DEDENT>if not bool(re.search(RE_HEADER, lines[i])):<EOL><INDENT>in_header_block = False<EOL><DEDENT>updated_markers += m<EOL>i += <NUM_LIT:1><EOL><DEDENT>return updated_markers<EOL>
Corrects markers by removing splitlines deemed to be inside header blocks.
f10787:m13
def is_splitter(line):
for pattern in SPLITTER_PATTERNS:<EOL><INDENT>matcher = re.match(pattern, line)<EOL>if matcher:<EOL><INDENT>return matcher<EOL><DEDENT><DEDENT>
Returns Matcher object if provided string is a splitter and None otherwise.
f10787:m15
def text_content(context):
return context.context_node.xpath("<STR_LIT>").strip()<EOL>
XPath Extension function to return a node text content.
f10787:m16
def tail(context):
return context.context_node.tail or '<STR_LIT>'<EOL>
XPath Extension function to return a node tail text.
f10787:m17
def safe_format(format_string, *args, **kwargs):
try:<EOL><INDENT>if not args and not kwargs:<EOL><INDENT>return format_string<EOL><DEDENT>else:<EOL><INDENT>return format_string.format(*args, **kwargs)<EOL><DEDENT><DEDENT>except (UnicodeEncodeError, UnicodeDecodeError):<EOL><INDENT>format_string = to_utf8(format_string)<EOL>args = [to_utf8(p) for p in args]<EOL>kwargs = {k: to_utf8(v) for k, v in six.iteritems(kwargs)}<EOL>return format_string.format(*args, **kwargs)<EOL><DEDENT>except:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT>
Helper: formats string with any combination of bytestrings/unicode strings without raising exceptions
f10788:m0
def to_unicode(str_or_unicode, precise=False):
if not isinstance(str_or_unicode, six.text_type):<EOL><INDENT>encoding = quick_detect_encoding(str_or_unicode) if precise else '<STR_LIT:utf-8>'<EOL>return six.text_type(str_or_unicode, encoding, '<STR_LIT:replace>')<EOL><DEDENT>return str_or_unicode<EOL>
Safely returns a unicode version of a given string >>> utils.to_unicode('привет') u'привет' >>> utils.to_unicode(u'привет') u'привет' If `precise` flag is True, tries to guess the correct encoding first.
f10788:m1
def detect_encoding(string):
assert isinstance(string, bytes)<EOL>try:<EOL><INDENT>detected = chardet.detect(string)<EOL>if detected:<EOL><INDENT>return detected.get('<STR_LIT>') or '<STR_LIT:utf-8>'<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT>return '<STR_LIT:utf-8>'<EOL>
Tries to detect the encoding of the passed string. Defaults to UTF-8.
f10788:m2
def quick_detect_encoding(string):
assert isinstance(string, bytes)<EOL>try:<EOL><INDENT>detected = cchardet.detect(string)<EOL>if detected:<EOL><INDENT>return detected.get('<STR_LIT>') or detect_encoding(string)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT>return detect_encoding(string)<EOL>
Tries to detect the encoding of the passed string. Uses cchardet. Fallbacks to detect_encoding.
f10788:m3
def to_utf8(str_or_unicode):
if not isinstance(str_or_unicode, six.text_type):<EOL><INDENT>return str_or_unicode.encode("<STR_LIT:utf-8>", "<STR_LIT:ignore>")<EOL><DEDENT>return str(str_or_unicode)<EOL>
Safely returns a UTF-8 version of a given string >>> utils.to_utf8(u'hi') 'hi'
f10788:m4
def html_to_text(string):
if isinstance(string, six.text_type):<EOL><INDENT>string = string.encode('<STR_LIT:utf8>')<EOL><DEDENT>s = _prepend_utf8_declaration(string)<EOL>s = s.replace(b"<STR_LIT:\n>", b"<STR_LIT>")<EOL>tree = html_fromstring(s)<EOL>if tree is None:<EOL><INDENT>return None<EOL><DEDENT>return html_tree_to_text(tree)<EOL>
Dead-simple HTML-to-text converter: >>> html_to_text("one<br>two<br>three") >>> "one\ntwo\nthree" NOTES: 1. the string is expected to contain UTF-8 encoded HTML! 2. returns utf-8 encoded str (not unicode) 3. if html can't be parsed returns None
f10788:m8
def html_fromstring(s):
if isinstance(s, six.text_type):<EOL><INDENT>s = s.encode('<STR_LIT:utf8>')<EOL><DEDENT>try:<EOL><INDENT>if html_too_big(s):<EOL><INDENT>return None<EOL><DEDENT>return html5parser.fromstring(s, parser=_html5lib_parser())<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>
Parse html tree from string. Return None if the string can't be parsed.
f10788:m9
def html_document_fromstring(s):
if isinstance(s, six.text_type):<EOL><INDENT>s = s.encode('<STR_LIT:utf8>')<EOL><DEDENT>try:<EOL><INDENT>if html_too_big(s):<EOL><INDENT>return None<EOL><DEDENT>return html5parser.document_fromstring(s, parser=_html5lib_parser())<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>
Parse html tree from string. Return None if the string can't be parsed.
f10788:m10
def _contains_charset_spec(s):
return s.lower().find(b'<STR_LIT>', <NUM_LIT:0>, <NUM_LIT>) != -<NUM_LIT:1><EOL>
Return True if the first 4KB contain charset spec
f10788:m13
def _prepend_utf8_declaration(s):
return s if _contains_charset_spec(s) else _UTF8_DECLARATION + s<EOL>
Prepend 'utf-8' encoding declaration if the first 4KB don't have any
f10788:m14
def _rm_excessive_newlines(s):
return _RE_EXCESSIVE_NEWLINES.sub("<STR_LIT>", s).strip()<EOL>
Remove excessive newlines that often happen due to tons of divs
f10788:m15
def _encode_utf8(s):
return s.encode('<STR_LIT:utf-8>') if isinstance(s, six.text_type) else s<EOL>
Encode in 'utf-8' if unicode
f10788:m16
def _html5lib_parser():
return html5lib.HTMLParser(<EOL>html5lib.treebuilders.getTreeBuilder("<STR_LIT>"),<EOL>namespaceHTMLElements=False<EOL>)<EOL>
html5lib is a pure-python library that conforms to the WHATWG HTML spec and is not vulnarable to certain attacks common for XML libraries
f10788:m17
def is_signature_line(line, sender, classifier):
data = numpy.array(build_pattern(line, features(sender))).reshape(<NUM_LIT:1>, -<NUM_LIT:1>)<EOL>return classifier.predict(data) > <NUM_LIT:0><EOL>
Checks if the line belongs to signature. Returns True or False.
f10790:m0
def extract(body, sender):
try:<EOL><INDENT>delimiter = get_delimiter(body)<EOL>body = body.strip()<EOL>if has_signature(body, sender):<EOL><INDENT>lines = body.splitlines()<EOL>markers = _mark_lines(lines, sender)<EOL>text, signature = _process_marked_lines(lines, markers)<EOL>if signature:<EOL><INDENT>text = delimiter.join(text)<EOL>if text.strip():<EOL><INDENT>return (text, delimiter.join(signature))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>log.exception('<STR_LIT>')<EOL><DEDENT>return (body, None)<EOL>
Strips signature from the body of the message. Returns stripped body and signature as a tuple. If no signature is found the corresponding returned value is None.
f10790:m1
def _mark_lines(lines, sender):
global EXTRACTOR<EOL>candidate = get_signature_candidate(lines)<EOL>markers = list('<STR_LIT:t>' * len(lines))<EOL>for i, line in reversed(list(enumerate(candidate))):<EOL><INDENT>j = len(lines) - len(candidate) + i<EOL>if not line.strip():<EOL><INDENT>markers[j] = '<STR_LIT:e>'<EOL><DEDENT>elif is_signature_line(line, sender, EXTRACTOR):<EOL><INDENT>markers[j] = '<STR_LIT:s>'<EOL><DEDENT><DEDENT>return "<STR_LIT>".join(markers)<EOL>
Mark message lines with markers to distinguish signature lines. Markers: * e - empty line * s - line identified as signature * t - other i.e. ordinary text line >>> mark_message_lines(['Some text', '', 'Bob'], 'Bob') 'tes'
f10790:m2
def _process_marked_lines(lines, markers):
<EOL>signature = RE_REVERSE_SIGNATURE.match(markers[::-<NUM_LIT:1>])<EOL>if signature:<EOL><INDENT>return (lines[:-signature.end()], lines[-signature.end():])<EOL><DEDENT>return (lines, None)<EOL>
Run regexes against message's marked lines to strip signature. >>> _process_marked_lines(['Some text', '', 'Bob'], 'tes') (['Some text', ''], ['Bob'])
f10790:m3
def extract_signature(msg_body):
try:<EOL><INDENT>delimiter = get_delimiter(msg_body)<EOL>stripped_body = msg_body.strip()<EOL>phone_signature = None<EOL>phone_signature = RE_PHONE_SIGNATURE.search(msg_body)<EOL>if phone_signature:<EOL><INDENT>stripped_body = stripped_body[:phone_signature.start()]<EOL>phone_signature = phone_signature.group()<EOL><DEDENT>lines = stripped_body.splitlines()<EOL>candidate = get_signature_candidate(lines)<EOL>candidate = delimiter.join(candidate)<EOL>signature = RE_SIGNATURE.search(candidate)<EOL>if not signature:<EOL><INDENT>return (stripped_body.strip(), phone_signature)<EOL><DEDENT>else:<EOL><INDENT>signature = signature.group()<EOL>stripped_body = delimiter.join(lines)<EOL>stripped_body = stripped_body[:-len(signature)]<EOL>if phone_signature:<EOL><INDENT>signature = delimiter.join([signature, phone_signature])<EOL><DEDENT>return (stripped_body.strip(),<EOL>signature.strip())<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>log.exception('<STR_LIT>')<EOL>return (msg_body, None)<EOL><DEDENT>
Analyzes message for a presence of signature block (by common patterns) and returns tuple with two elements: message text without signature block and the signature itself. >>> extract_signature('Hey man! How r u?\n\n--\nRegards,\nRoman') ('Hey man! How r u?', '--\nRegards,\nRoman') >>> extract_signature('Hey man!') ('Hey man!', None)
f10792:m0
def get_signature_candidate(lines):
<EOL>non_empty = [i for i, line in enumerate(lines) if line.strip()]<EOL>if len(non_empty) <= <NUM_LIT:1>:<EOL><INDENT>return []<EOL><DEDENT>candidate = non_empty[<NUM_LIT:1>:]<EOL>candidate = candidate[-SIGNATURE_MAX_LINES:]<EOL>markers = _mark_candidate_indexes(lines, candidate)<EOL>candidate = _process_marked_candidate_indexes(candidate, markers)<EOL>if candidate:<EOL><INDENT>candidate = lines[candidate[<NUM_LIT:0>]:]<EOL>return candidate<EOL><DEDENT>return []<EOL>
Return lines that could hold signature The lines should: * be among last SIGNATURE_MAX_LINES non-empty lines. * not include first line * be shorter than TOO_LONG_SIGNATURE_LINE * not include more than one line that starts with dashes
f10792:m1
def _mark_candidate_indexes(lines, candidate):
<EOL>markers = list('<STR_LIT:c>' * len(candidate))<EOL>for i, line_idx in reversed(list(enumerate(candidate))):<EOL><INDENT>if len(lines[line_idx].strip()) > TOO_LONG_SIGNATURE_LINE:<EOL><INDENT>markers[i] = '<STR_LIT:l>'<EOL><DEDENT>else:<EOL><INDENT>line = lines[line_idx].strip()<EOL>if line.startswith('<STR_LIT:->') and line.strip("<STR_LIT:->"):<EOL><INDENT>markers[i] = '<STR_LIT:d>'<EOL><DEDENT><DEDENT><DEDENT>return "<STR_LIT>".join(markers)<EOL>
Mark candidate indexes with markers Markers: * c - line that could be a signature line * l - long line * d - line that starts with dashes but has other chars as well >>> _mark_candidate_lines(['Some text', '', '-', 'Bob'], [0, 2, 3]) 'cdc'
f10792:m2
def _process_marked_candidate_indexes(candidate, markers):
match = RE_SIGNATURE_CANDIDATE.match(markers[::-<NUM_LIT:1>])<EOL>return candidate[-match.end('<STR_LIT>'):] if match else []<EOL>
Run regexes against candidate's marked indexes to strip signature candidate. >>> _process_marked_candidate_indexes([9, 12, 14, 15, 17], 'clddc') [15, 17]
f10792:m3
def init():
return LinearSVC(C=<NUM_LIT>)<EOL>
Inits classifier with optimal options.
f10793:m0
def train(classifier, train_data_filename, save_classifier_filename=None):
file_data = genfromtxt(train_data_filename, delimiter="<STR_LIT:U+002C>")<EOL>train_data, labels = file_data[:, :-<NUM_LIT:1>], file_data[:, -<NUM_LIT:1>]<EOL>classifier.fit(train_data, labels)<EOL>if save_classifier_filename:<EOL><INDENT>joblib.dump(classifier, save_classifier_filename)<EOL><DEDENT>return classifier<EOL>
Trains and saves classifier so that it could be easily loaded later.
f10793:m1
def load(saved_classifier_filename, train_data_filename):
try:<EOL><INDENT>return joblib.load(saved_classifier_filename)<EOL><DEDENT>except Exception:<EOL><INDENT>import sys<EOL>if sys.version_info > (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>return load_compat(saved_classifier_filename)<EOL><DEDENT>raise<EOL><DEDENT>
Loads saved classifier.
f10793:m2
def features(sender='<STR_LIT>'):
return [<EOL>many_capitalized_words,<EOL>lambda line: <NUM_LIT:1> if len(line) > TOO_LONG_SIGNATURE_LINE else <NUM_LIT:0>,<EOL>binary_regex_search(RE_EMAIL),<EOL>binary_regex_search(RE_URL),<EOL>binary_regex_search(RE_RELAX_PHONE),<EOL>binary_regex_match(RE_SEPARATOR),<EOL>binary_regex_search(RE_SPECIAL_CHARS),<EOL>binary_regex_search(RE_SIGNATURE_WORDS),<EOL>binary_regex_search(RE_NAME),<EOL>lambda line: <NUM_LIT:1> if punctuation_percent(line) > <NUM_LIT:50> else <NUM_LIT:0>,<EOL>lambda line: <NUM_LIT:1> if punctuation_percent(line) > <NUM_LIT> else <NUM_LIT:0>,<EOL>contains_sender_names(sender)<EOL>]<EOL>
Returns a list of signature features.
f10794:m0
def apply_features(body, features):
<EOL>lines = [line for line in body.splitlines() if line.strip()]<EOL>last_lines = lines[-SIGNATURE_MAX_LINES:]<EOL>return ([[f(line) for f in features] for line in last_lines] or<EOL>[[<NUM_LIT:0> for f in features]])<EOL>
Applies features to message body lines. Returns list of lists. Each of the lists corresponds to the body line and is constituted by the numbers of features occurrences (0 or 1). E.g. if element j of list i equals 1 this means that feature j occurred in line i (counting from the last line of the body).
f10794:m1
def build_pattern(body, features):
line_patterns = apply_features(body, features)<EOL>return reduce(lambda x, y: [i + j for i, j in zip(x, y)], line_patterns)<EOL>
Converts body into a pattern i.e. a point in the features space. Applies features to the body lines and sums up the results. Elements of the pattern indicate how many times a certain feature occurred in the last lines of the body.
f10794:m2
def is_sender_filename(filename):
return filename.endswith(SENDER_SUFFIX)<EOL>
Checks if the file could contain message sender's name.
f10795:m0
def build_sender_filename(msg_filename):
return msg_filename[:-len(BODY_SUFFIX)] + SENDER_SUFFIX<EOL>
By the message filename gives expected sender's filename.
f10795:m1
def parse_msg_sender(filename, sender_known=True):
import sys<EOL>kwargs = {}<EOL>if sys.version_info > (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>kwargs["<STR_LIT>"] = "<STR_LIT:utf8>"<EOL><DEDENT>sender, msg = None, None<EOL>if os.path.isfile(filename) and not is_sender_filename(filename):<EOL><INDENT>with open(filename, **kwargs) as f:<EOL><INDENT>msg = f.read()<EOL>sender = u'<STR_LIT>'<EOL>if sender_known:<EOL><INDENT>sender_filename = build_sender_filename(filename)<EOL>if os.path.exists(sender_filename):<EOL><INDENT>with open(sender_filename) as sender_file:<EOL><INDENT>sender = sender_file.read().strip()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>lines = msg.splitlines()<EOL>for line in lines:<EOL><INDENT>match = re.match('<STR_LIT>', line)<EOL>if match:<EOL><INDENT>sender = match.group(<NUM_LIT:1>)<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return (sender, msg)<EOL>
Given a filename returns the sender and the message. Here the message is assumed to be a whole MIME message or just message body. >>> sender, msg = parse_msg_sender('msg.eml') >>> sender, msg = parse_msg_sender('msg_body') If you don't want to consider the sender's name in your classification algorithm: >>> parse_msg_sender(filename, False)
f10795:m2
def build_detection_class(folder, dataset_filename,<EOL>label, sender_known=True):
with open(dataset_filename, '<STR_LIT:a>') as dataset:<EOL><INDENT>for filename in os.listdir(folder):<EOL><INDENT>filename = os.path.join(folder, filename)<EOL>sender, msg = parse_msg_sender(filename, sender_known)<EOL>if sender is None or msg is None:<EOL><INDENT>continue<EOL><DEDENT>msg = re.sub('<STR_LIT:|>'.join(ANNOTATIONS), '<STR_LIT>', msg)<EOL>X = build_pattern(msg, features(sender))<EOL>X.append(label)<EOL>labeled_pattern = '<STR_LIT:U+002C>'.join([str(e) for e in X])<EOL>dataset.write(labeled_pattern + '<STR_LIT:\n>')<EOL><DEDENT><DEDENT>
Builds signature detection class. Signature detection dataset includes patterns for two classes: * class for positive patterns (goes with label 1) * class for negative patterns (goes with label -1) The patterns are build of emails from `folder` and appended to dataset file. >>> build_signature_detection_class('emails/P', 'train.data', 1)
f10795:m3
def build_detection_dataset(folder, dataset_filename,<EOL>sender_known=True):
if os.path.exists(dataset_filename):<EOL><INDENT>os.remove(dataset_filename)<EOL><DEDENT>build_detection_class(os.path.join(folder, u'<STR_LIT:P>'),<EOL>dataset_filename, <NUM_LIT:1>)<EOL>build_detection_class(os.path.join(folder, u'<STR_LIT:N>'),<EOL>dataset_filename, -<NUM_LIT:1>)<EOL>
Builds signature detection dataset using emails from folder. folder should have the following structure: x-- folder | x-- P | | | -- positive sample email 1 | | | -- positive sample email 2 | | | -- ... | x-- N | | | -- negative sample email 1 | | | -- negative sample email 2 | | | -- ... If the dataset file already exist it is rewritten.
f10795:m4
def build_extraction_dataset(folder, dataset_filename,<EOL>sender_known=True):
if os.path.exists(dataset_filename):<EOL><INDENT>os.remove(dataset_filename)<EOL><DEDENT>with open(dataset_filename, '<STR_LIT:a>') as dataset:<EOL><INDENT>for filename in os.listdir(folder):<EOL><INDENT>filename = os.path.join(folder, filename)<EOL>sender, msg = parse_msg_sender(filename, sender_known)<EOL>if not sender or not msg:<EOL><INDENT>continue<EOL><DEDENT>lines = msg.splitlines()<EOL>for i in range(<NUM_LIT:1>, min(SIGNATURE_MAX_LINES,<EOL>len(lines)) + <NUM_LIT:1>):<EOL><INDENT>line = lines[-i]<EOL>label = -<NUM_LIT:1><EOL>if line[:len(SIGNATURE_ANNOTATION)] ==SIGNATURE_ANNOTATION:<EOL><INDENT>label = <NUM_LIT:1><EOL>line = line[len(SIGNATURE_ANNOTATION):]<EOL><DEDENT>elif line[:len(REPLY_ANNOTATION)] == REPLY_ANNOTATION:<EOL><INDENT>line = line[len(REPLY_ANNOTATION):]<EOL><DEDENT>X = build_pattern(line, features(sender))<EOL>X.append(label)<EOL>labeled_pattern = '<STR_LIT:U+002C>'.join([str(e) for e in X])<EOL>dataset.write(labeled_pattern + '<STR_LIT:\n>')<EOL><DEDENT><DEDENT><DEDENT>
Builds signature extraction dataset using emails in the `folder`. The emails in the `folder` should be annotated i.e. signature lines should be marked with `#sig#`.
f10795:m5
def binary_regex_search(prog):
return lambda s: <NUM_LIT:1> if prog.search(s) else <NUM_LIT:0><EOL>
Returns a function that returns 1 or 0 depending on regex search result. If regular expression compiled into prog is present in a string the result of calling the returned function with the string will be 1 and 0 otherwise. >>> import regex as re >>> binary_regex_search(re.compile("12"))("12") 1 >>> binary_regex_search(re.compile("12"))("34") 0
f10796:m0
def binary_regex_match(prog):
return lambda s: <NUM_LIT:1> if prog.match(s) else <NUM_LIT:0><EOL>
Returns a function that returns 1 or 0 depending on regex match result. If a string matches regular expression compiled into prog the result of calling the returned function with the string will be 1 and 0 otherwise. >>> import regex as re >>> binary_regex_match(re.compile("12"))("12 3") 1 >>> binary_regex_match(re.compile("12"))("3 12") 0
f10796:m1
def flatten_list(list_to_flatten):
return [e for sublist in list_to_flatten for e in sublist]<EOL>
Simple list comprehension to flatten list. >>> flatten_list([[1, 2], [3, 4, 5]]) [1, 2, 3, 4, 5] >>> flatten_list([[1], [[2]]]) [1, [2]] >>> flatten_list([1, [2]]) Traceback (most recent call last): ... TypeError: 'int' object is not iterable
f10796:m2
def contains_sender_names(sender):
names = '<STR_LIT>'.join(flatten_list([[e, e.capitalize()]<EOL>for e in extract_names(sender)]))<EOL>names = names or sender<EOL>if names != '<STR_LIT>':<EOL><INDENT>return binary_regex_search(re.compile(names))<EOL><DEDENT>return lambda s: <NUM_LIT:0><EOL>
Returns a functions to search sender\'s name or it\'s part. >>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>") >>> feature("Sergey Obukhov") 1 >>> feature("BR, Sergey N.") 1 >>> feature("Sergey") 1 >>> contains_sender_names("<serobnic@mail.ru>")("Serobnic") 1 >>> contains_sender_names("<serobnic@mail.ru>")("serobnic") 1
f10796:m3
def extract_names(sender):
sender = to_unicode(sender, precise=True)<EOL>sender = "<STR_LIT>".join([char if char.isalpha() else '<STR_LIT:U+0020>' for char in sender])<EOL>sender = [word for word in sender.split() if len(word) > <NUM_LIT:1> and<EOL>not word in BAD_SENDER_NAMES]<EOL>names = list(set(sender))<EOL>return names<EOL>
Tries to extract sender's names from `From:` header. It could extract not only the actual names but e.g. the name of the company, parts of email, etc. >>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>') ['Sergey', 'Obukhov', 'serobnic'] >>> extract_names('') []
f10796:m4
def categories_percent(s, categories):
count = <NUM_LIT:0><EOL>s = to_unicode(s, precise=True)<EOL>for c in s:<EOL><INDENT>if unicodedata.category(c) in categories:<EOL><INDENT>count += <NUM_LIT:1><EOL><DEDENT><DEDENT>return <NUM_LIT:100> * float(count) / len(s) if len(s) else <NUM_LIT:0><EOL>
Returns category characters percent. >>> categories_percent("qqq ggg hhh", ["Po"]) 0.0 >>> categories_percent("q,w.", ["Po"]) 50.0 >>> categories_percent("qqq ggg hhh", ["Nd"]) 0.0 >>> categories_percent("q5", ["Nd"]) 50.0 >>> categories_percent("s.s,5s", ["Po", "Nd"]) 50.0
f10796:m5
def punctuation_percent(s):
return categories_percent(s, ['<STR_LIT>'])<EOL>
Returns punctuation percent. >>> punctuation_percent("qqq ggg hhh") 0.0 >>> punctuation_percent("q,w.") 50.0
f10796:m6
def capitalized_words_percent(s):
s = to_unicode(s, precise=True)<EOL>words = re.split('<STR_LIT>', s)<EOL>words = [w for w in words if w.strip()]<EOL>words = [w for w in words if len(w) > <NUM_LIT:2>] <EOL>capitalized_words_counter = <NUM_LIT:0><EOL>valid_words_counter = <NUM_LIT:0><EOL>for word in words:<EOL><INDENT>if not INVALID_WORD_START.match(word):<EOL><INDENT>valid_words_counter += <NUM_LIT:1><EOL>if word[<NUM_LIT:0>].isupper() and not word[<NUM_LIT:1>].isupper():<EOL><INDENT>capitalized_words_counter += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>if valid_words_counter > <NUM_LIT:0> and len(words) > <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:100> * float(capitalized_words_counter) / valid_words_counter<EOL><DEDENT>return <NUM_LIT:0><EOL>
Returns capitalized words percent.
f10796:m7
def many_capitalized_words(s):
return <NUM_LIT:1> if capitalized_words_percent(s) > <NUM_LIT> else <NUM_LIT:0><EOL>
Returns a function to check percentage of capitalized words. The function returns 1 if percentage greater then 65% and 0 otherwise.
f10796:m8
def has_signature(body, sender):
non_empty = [line for line in body.splitlines() if line.strip()]<EOL>candidate = non_empty[-SIGNATURE_MAX_LINES:]<EOL>upvotes = <NUM_LIT:0><EOL>for line in candidate:<EOL><INDENT>if len(line.strip()) > <NUM_LIT>:<EOL><INDENT>continue<EOL><DEDENT>elif contains_sender_names(sender)(line):<EOL><INDENT>return True<EOL><DEDENT>elif (binary_regex_search(RE_RELAX_PHONE)(line) +<EOL>binary_regex_search(RE_EMAIL)(line) +<EOL>binary_regex_search(RE_URL)(line) == <NUM_LIT:1>):<EOL><INDENT>upvotes += <NUM_LIT:1><EOL><DEDENT><DEDENT>if upvotes > <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>
Checks if the body has signature. Returns True or False.
f10796:m9
def train_model():
train(init(), EXTRACTOR_DATA, EXTRACTOR_FILENAME)<EOL>
retrain model and persist
f10797:m0
def _send_and_consume(self, channel, data):
self.client.send_and_consume(force_text(channel), data)<EOL>return self._get_next_message()<EOL>
Helper that sends and consumes message and returns the next message.
f10803:c2:m1
def detail_action(**kwargs):
def decorator(func):<EOL><INDENT>func.action = True<EOL>func.detail = True<EOL>func.kwargs = kwargs<EOL>return func<EOL><DEDENT>return decorator<EOL>
Used to mark a method on a ResourceBinding that should be routed for detail actions.
f10810:m0
def list_action(**kwargs):
def decorator(func):<EOL><INDENT>func.action = True<EOL>func.detail = False<EOL>func.kwargs = kwargs<EOL>return func<EOL><DEDENT>return decorator<EOL>
Used to mark a method on a ResourceBinding that should be routed for list actions.
f10810:m1
@classmethod<EOL><INDENT>def pre_change_receiver(cls, instance, action):<DEDENT>
if action == CREATE:<EOL><INDENT>group_names = set()<EOL><DEDENT>else:<EOL><INDENT>group_names = set(cls.group_names(instance, action))<EOL><DEDENT>if not hasattr(instance, '<STR_LIT>'):<EOL><INDENT>instance._binding_group_names = {}<EOL><DEDENT>instance._binding_group_names[cls] = group_names<EOL>
Entry point for triggering the binding from save signals.
f10812:c1:m1
@classmethod<EOL><INDENT>def post_change_receiver(cls, instance, action, **kwargs):<DEDENT>
old_group_names = instance._binding_group_names[cls]<EOL>if action == DELETE:<EOL><INDENT>new_group_names = set()<EOL><DEDENT>else:<EOL><INDENT>new_group_names = set(cls.group_names(instance, action))<EOL><DEDENT>self = cls()<EOL>self.instance = instance<EOL>self.send_messages(instance, old_group_names - new_group_names, DELETE, **kwargs)<EOL>self.send_messages(instance, old_group_names & new_group_names, UPDATE, **kwargs)<EOL>self.send_messages(instance, new_group_names - old_group_names, CREATE, **kwargs)<EOL>
Triggers the binding to possibly send to its group.
f10812:c1:m2
def _group_name(self, action, id=None):
if id:<EOL><INDENT>return "<STR_LIT>".format(self.model_label, action, id)<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>".format(self.model_label, action)<EOL><DEDENT>
Formatting helper for group names.
f10812:c1:m4
def reply(self, action, data=None, errors=[], status=<NUM_LIT:200>, request_id=None):
payload = {<EOL>'<STR_LIT>': errors,<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT:action>': action,<EOL>'<STR_LIT>': status,<EOL>'<STR_LIT>': request_id<EOL>}<EOL>return self.message.reply_channel.send(self.encode(self.stream, payload))<EOL>
Helper method to send a encoded response to the message's reply_channel.
f10812:c1:m11
def _get_version():
with open('<STR_LIT>', '<STR_LIT:r>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith(u'<STR_LIT>'):<EOL><INDENT>return ast.parse(line).body[<NUM_LIT:0>].value.s<EOL><DEDENT><DEDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>
Fetches the version number from the package's __init__.py file
f10813:m1
def bumpversion(self, part, **kwargs):
import bumpversion<EOL>args = ['<STR_LIT>'] if self.verbose > <NUM_LIT:1> else []<EOL>for k, v in kwargs.items():<EOL><INDENT>arg = "<STR_LIT>".format(k.replace("<STR_LIT:_>", "<STR_LIT:->"))<EOL>if isinstance(v, bool):<EOL><INDENT>if v is False:<EOL><INDENT>continue<EOL><DEDENT>args.append(arg)<EOL><DEDENT>else:<EOL><INDENT>args.extend([arg, str(v)])<EOL><DEDENT><DEDENT>args.append(part)<EOL>log.debug(<EOL>"<STR_LIT>" % "<STR_LIT:U+0020>".join(a.replace("<STR_LIT:U+0020>", "<STR_LIT>") for a in args))<EOL>bumpversion.main(args)<EOL>
Run bump2version.main() with the specified arguments.
f10813:c0:m2
@staticmethod<EOL><INDENT>def edit_release_notes():<DEDENT>
from tempfile import mkstemp<EOL>import os<EOL>import shlex<EOL>import subprocess<EOL>text_editor = shlex.split(os.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>fd, tmp = mkstemp(prefix='<STR_LIT>')<EOL>try:<EOL><INDENT>os.close(fd)<EOL>with open(tmp, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(u"<STR_LIT>"<EOL>u"<STR_LIT>")<EOL><DEDENT>subprocess.check_call(text_editor + [tmp])<EOL>with open(tmp, '<STR_LIT:r>') as f:<EOL><INDENT>changes = "<STR_LIT>".join(<EOL>l for l in f.readlines() if not l.startswith('<STR_LIT:#>'))<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>os.remove(tmp)<EOL><DEDENT>return changes<EOL>
Use the default text $EDITOR to write release notes. If $EDITOR is not set, use 'nano'.
f10813:c2:m2
def compileSass(sassPath):
cssPath = os.path.splitext(sassPath)[<NUM_LIT:0>] + "<STR_LIT>"<EOL>print("<STR_LIT>")<EOL>process = subprocess.Popen(["<STR_LIT>", sassPath, cssPath])<EOL>process.wait()<EOL>
Compile a sass file (and dependencies) into a single css file.
f10814:m0
def autoprefixCSS(sassPath):
print("<STR_LIT>")<EOL>cssPath = os.path.splitext(sassPath)[<NUM_LIT:0>] + "<STR_LIT>"<EOL>command = "<STR_LIT>" + cssPath + "<STR_LIT:U+0020>" + cssPath<EOL>subprocess.call(command, shell=True)<EOL>
Take CSS file and automatically add browser prefixes with postCSS autoprefixer
f10814:m1
def get_items(self, names):
env = self.state.document.settings.env<EOL>prefixes = get_import_prefixes_from_env(env)<EOL>methodNames = []<EOL>for name in names:<EOL><INDENT>methodNames.append(name)<EOL>_, obj, _, _ = import_by_name(name, prefixes=prefixes)<EOL>methodNames.extend(["<STR_LIT>" % (name, method) for method in dir(obj) if not method.startswith("<STR_LIT:_>")])<EOL><DEDENT>return super(AutosummaryMethodList, self).get_items(methodNames)<EOL>
Subclass get items to get support for all methods in an given object
f10815:c0:m0
def get_table(self, items):
hidesummary = '<STR_LIT>' in self.options<EOL>table_spec = addnodes.tabular_col_spec()<EOL>table_spec['<STR_LIT>'] = '<STR_LIT>'<EOL>table = autosummary_table('<STR_LIT>')<EOL>real_table = nodes.table('<STR_LIT>', classes=['<STR_LIT>'])<EOL>table.append(real_table)<EOL>group = nodes.tgroup('<STR_LIT>', cols=<NUM_LIT:2>)<EOL>real_table.append(group)<EOL>group.append(nodes.colspec('<STR_LIT>', colwidth=<NUM_LIT:10>))<EOL>group.append(nodes.colspec('<STR_LIT>', colwidth=<NUM_LIT>))<EOL>body = nodes.tbody('<STR_LIT>')<EOL>group.append(body)<EOL>def append_row(*column_texts):<EOL><INDENT>row = nodes.row('<STR_LIT>')<EOL>for text in column_texts:<EOL><INDENT>node = nodes.paragraph('<STR_LIT>')<EOL>vl = ViewList()<EOL>vl.append(text, '<STR_LIT>')<EOL>self.state.nested_parse(vl, <NUM_LIT:0>, node)<EOL>try:<EOL><INDENT>if isinstance(node[<NUM_LIT:0>], nodes.paragraph):<EOL><INDENT>node = node[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>row.append(nodes.entry('<STR_LIT>', node))<EOL><DEDENT>body.append(row)<EOL><DEDENT>for name, sig, summary, real_name in items:<EOL><INDENT>qualifier = '<STR_LIT>'<EOL>if '<STR_LIT>' not in self.options:<EOL><INDENT>col1 = '<STR_LIT>' % (qualifier, name, real_name, rst.escape(sig))<EOL><DEDENT>else:<EOL><INDENT>col1 = '<STR_LIT>' % (qualifier, name, real_name)<EOL><DEDENT>col2 = summary<EOL>if hidesummary:<EOL><INDENT>append_row(col1)<EOL><DEDENT>else:<EOL><INDENT>append_row(col1, col2)<EOL><DEDENT><DEDENT>return [table_spec, table]<EOL>
Subclass to get support for `hidesummary` as options to enable displaying the short summary in the table
f10815:c0:m1
def OpenFont(path, showInterface=True):
return dispatcher["<STR_LIT>"](pathOrObject=path, showInterface=showInterface)<EOL>
Open font located at **path**. If **showInterface** is ``False``, the font should be opened without graphical interface. The default for **showInterface** is ``True``. :: from fontParts.world import * font = OpenFont("/path/to/my/font.ufo") font = OpenFont("/path/to/my/font.ufo", showInterface=False)
f10816:m0
def NewFont(familyName=None, styleName=None, showInterface=True):
return dispatcher["<STR_LIT>"](familyName=familyName, styleName=styleName,<EOL>showInterface=showInterface)<EOL>
Create a new font. **familyName** will be assigned to ``font.info.familyName`` and **styleName** will be assigned to ``font.info.styleName``. These are optional and default to ``None``. If **showInterface** is ``False``, the font should be created without graphical interface. The default for **showInterface** is ``True``. :: from fontParts.world import * font = NewFont() font = NewFont(familyName="My Family", styleName="My Style") font = NewFont(showInterface=False)
f10816:m1
def CurrentFont():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "current" font.
f10816:m2
def CurrentGlyph():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "current" glyph from :func:`CurrentFont`. :: from fontParts.world import * glyph = CurrentGlyph()
f10816:m3
def CurrentLayer():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "current" layer from :func:`CurrentGlyph`. :: from fontParts.world import * layer = CurrentLayer()
f10816:m4
def CurrentContours():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "currently" selected contours from :func:`CurrentGlyph`. :: from fontParts.world import * contours = CurrentContours() This returns an immutable list, even when nothing is selected.
f10816:m5
def CurrentSegments():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "currently" selected segments from :func:`CurrentContours`. :: from fontParts.world import * segments = CurrentSegments() This returns an immutable list, even when nothing is selected.
f10816:m7
def CurrentPoints():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "currently" selected points from :func:`CurrentContours`. :: from fontParts.world import * points = CurrentPoints() This returns an immutable list, even when nothing is selected.
f10816:m9
def CurrentComponents():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "currently" selected components from :func:`CurrentGlyph`. :: from fontParts.world import * components = CurrentComponents() This returns an immutable list, even when nothing is selected.
f10816:m11
def CurrentAnchors():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "currently" selected anchors from :func:`CurrentGlyph`. :: from fontParts.world import * anchors = CurrentAnchors() This returns an immutable list, even when nothing is selected.
f10816:m13
def CurrentGuidelines():
return dispatcher["<STR_LIT>"]()<EOL>
Get the "currently" selected guidelines from :func:`CurrentGlyph`. This will include both font level and glyph level guidelines. :: from fontParts.world import * guidelines = CurrentGuidelines() This returns an immutable list, even when nothing is selected.
f10816:m15
def AllFonts(sortOptions=None):
fontList = FontList(dispatcher["<STR_LIT>"]())<EOL>if sortOptions is not None:<EOL><INDENT>fontList.sortBy(sortOptions)<EOL><DEDENT>return fontList<EOL>
Get a list of all open fonts. Optionally, provide a value for ``sortOptions`` to sort the fonts. See :meth:`world.FontList.sortBy` for options. :: from fontParts.world import * fonts = AllFonts() for font in fonts: # do something fonts = AllFonts("magic") for font in fonts: # do something fonts = AllFonts(["familyName", "styleName"]) for font in fonts: # do something
f10816:m17
def FontList(fonts=None):
l = dispatcher["<STR_LIT>"]()<EOL>if fonts:<EOL><INDENT>l.extend(fonts)<EOL><DEDENT>return l<EOL>
Get a list with font specific methods. :: from fontParts.world import * fonts = FontList() Refer to :class:`BaseFontList` for full documentation.
f10816:m20
def _sortValue_familyName(font):
value = font.info.familyName<EOL>if value is None:<EOL><INDENT>value = "<STR_LIT>"<EOL><DEDENT>return value<EOL>
Returns font.info.familyName.
f10816:m21
def _sortValue_styleName(font):
value = font.info.styleName<EOL>if value is None:<EOL><INDENT>value = "<STR_LIT>"<EOL><DEDENT>return value<EOL>
Returns font.info.styleName.
f10816:m22
def _sortValue_isRoman(font):
italic = _sortValue_isItalic(font)<EOL>if italic == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return <NUM_LIT:1><EOL>
Returns 0 if the font is roman. Returns 1 if the font is not roman.
f10816:m23
def _sortValue_isItalic(font):
info = font.info<EOL>styleMapStyleName = info.styleMapStyleName<EOL>if styleMapStyleName is not None and "<STR_LIT>" in styleMapStyleName:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if info.italicAngle not in (None, <NUM_LIT:0>):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return <NUM_LIT:1><EOL>
Returns 0 if the font is italic. Returns 1 if the font is not italic.
f10816:m24
def _sortValue_widthValue(font):
value = font.info.openTypeOS2WidthClass<EOL>if value is None:<EOL><INDENT>value = -<NUM_LIT:1><EOL><DEDENT>return value<EOL>
Returns font.info.openTypeOS2WidthClass.
f10816:m25
def _sortValue_weightValue(font):
value = font.info.openTypeOS2WeightClass<EOL>if value is None:<EOL><INDENT>value = -<NUM_LIT:1><EOL><DEDENT>return value<EOL>
Returns font.info.openTypeOS2WeightClass.
f10816:m26
def _sortValue_isProportional(font):
monospace = _sortValue_isMonospace(font)<EOL>if monospace == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return <NUM_LIT:1><EOL>
Returns 0 if the font is proportional. Returns 1 if the font is not proportional.
f10816:m27
def _sortValue_isMonospace(font):
if font.info.postscriptIsFixedPitch:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if not len(font):<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>testWidth = None<EOL>for glyph in font:<EOL><INDENT>if testWidth is None:<EOL><INDENT>testWidth = glyph.width<EOL><DEDENT>else:<EOL><INDENT>if testWidth != glyph.width:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return <NUM_LIT:0><EOL>
Returns 0 if the font is monospace. Returns 1 if the font is not monospace.
f10816:m28
def sortBy(self, sortOptions, reverse=False):
from types import FunctionType<EOL>from fontTools.misc.py23 import basestring<EOL>valueGetters = dict(<EOL>familyName=_sortValue_familyName,<EOL>styleName=_sortValue_styleName,<EOL>isRoman=_sortValue_isRoman,<EOL>isItalic=_sortValue_isItalic,<EOL>widthValue=_sortValue_widthValue,<EOL>weightValue=_sortValue_weightValue,<EOL>isProportional=_sortValue_isProportional,<EOL>isMonospace=_sortValue_isMonospace<EOL>)<EOL>if isinstance(sortOptions, basestring) or isinstance(sortOptions, FunctionType):<EOL><INDENT>sortOptions = [sortOptions]<EOL><DEDENT>if not isinstance(sortOptions, (list, tuple)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not sortOptions:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if sortOptions == ["<STR_LIT>"]:<EOL><INDENT>sortOptions = [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>]<EOL><DEDENT>sorter = []<EOL>for originalIndex, font in enumerate(self):<EOL><INDENT>sortable = []<EOL>for valueName in sortOptions:<EOL><INDENT>if isinstance(valueName, FunctionType):<EOL><INDENT>value = valueName(font)<EOL><DEDENT>elif valueName in valueGetters:<EOL><INDENT>value = valueGetters[valueName](font)<EOL><DEDENT>elif hasattr(font.info, valueName):<EOL><INDENT>value = getattr(font.info, valueName)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % repr(valueGetter))<EOL><DEDENT>sortable.append(value)<EOL><DEDENT>sortable.append(originalIndex)<EOL>sortable.append(font)<EOL>sorter.append(tuple(sortable))<EOL><DEDENT>sorter.sort()<EOL>fonts = [i[-<NUM_LIT:1>] for i in sorter]<EOL>del self[:]<EOL>self.extend(fonts)<EOL>if reverse:<EOL><INDENT>self.reverse()<EOL><DEDENT>
Sort ``fonts`` with the ordering preferences defined by ``sortBy``. ``sortBy`` must be one of the following: * sort description string * :class:`BaseInfo` attribute name * sort value function * list/tuple containing sort description strings, :class:`BaseInfo` attribute names and/or sort value functions * ``"magic"`` Sort Description Strings ------------------------ The sort description strings, and how they modify the sort, are: +--------------------+--------------------------------------+ | ``"familyName"`` | Family names by alphabetical order. | +--------------------+--------------------------------------+ | ``"styleName"`` | Style names by alphabetical order. | +--------------------+--------------------------------------+ | ``"isItalic"`` | Italics before romans. | +--------------------+--------------------------------------+ | ``"isRoman"`` | Romans before italics. | +--------------------+--------------------------------------+ | ``"widthValue"`` | Width values by numerical order. | +--------------------+--------------------------------------+ | ``"weightValue"`` | Weight values by numerical order. | +--------------------+--------------------------------------+ | ``"monospace"`` | Monospaced before proportional. | +--------------------+--------------------------------------+ | ``"proportional"`` | Proportional before monospaced. | +--------------------+--------------------------------------+ :: >>> fonts.sortBy("familyName", "styleName") Font Info Attribute Names ------------------------- Any :class:`BaseFont` attribute name may be included as a sort option. For example, to sort by x-height value, you'd use the ``"xHeight"`` attribute name. :: >>> fonts.sortBy("xHeight") Sort Value Function ------------------- A sort value function must be a function that accepts one argument, ``font``. This function must return a sortable value for the given font. For example: :: def glyphCountSortValue(font): return len(font) >>> fonts.sortBy(glyphCountSortValue) A list of sort description strings and/or sort functions may also be provided. This should be in order of most to least important. For example, to sort by family name and then style name, do this: "magic" ------- If "magic" is given for ``sortBy``, the fonts will be sorted based on this sort description sequence: * ``"familyName"`` * ``"isProportional"`` * ``"widthValue"`` * ``"weightValue"`` * ``"styleName"`` * ``"isRoman"`` :: >>> fonts.sortBy("magic")
f10816:c0:m0
def getFontsByFontInfoAttribute(self, *attributeValuePairs):
found = self<EOL>for attr, value in attributeValuePairs:<EOL><INDENT>found = self._matchFontInfoAttributes(found, (attr, value))<EOL><DEDENT>return found<EOL>
Get a list of fonts that match the (attribute, value) combinations in ``attributeValuePairs``. :: >>> subFonts = fonts.getFontsByFontInfoAttribute(("xHeight", 20)) >>> subFonts = fonts.getFontsByFontInfoAttribute(("xHeight", 20), ("descender", -150)) This will return an instance of :class:`BaseFontList`.
f10816:c0:m1
def getFontsByFamilyName(self, familyName):
return self.getFontsByFontInfoAttribute(("<STR_LIT>", familyName))<EOL>
Get a list of fonts that match ``familyName``. This will return an instance of :class:`BaseFontList`.
f10816:c0:m3
def getFontsByStyleName(self, styleName):
return self.getFontsByFontInfoAttribute(("<STR_LIT>", styleName))<EOL>
Get a list of fonts that match ``styleName``. This will return an instance of :class:`BaseFontList`.
f10816:c0:m4
def getFontsByFamilyNameStyleName(self, familyName, styleName):
return self.getFontsByFontInfoAttribute(("<STR_LIT>", familyName), ("<STR_LIT>", styleName))<EOL>
Get a list of fonts that match ``familyName`` and ``styleName``. This will return an instance of :class:`BaseFontList`.
f10816:c0:m5
def findGlyph(self, glyphName):
glyphName = normalizers.normalizeGlyphName(glyphName)<EOL>groupNames = self._findGlyph(glyphName)<EOL>groupNames = [self.keyNormalizer.__func__(<EOL>groupName) for groupName in groupNames]<EOL>return groupNames<EOL>
Returns a ``list`` of the group or groups associated with **glyphName**. **glyphName** will be an :ref:`type-string`. If no group is found to contain **glyphName** an empty ``list`` will be returned. :: >>> font.groups.findGlyph("A") ["A_accented"]
f10839:c0:m3
def _findGlyph(self, glyphName):
found = []<EOL>for key, groupList in self.items():<EOL><INDENT>if glyphName in groupList:<EOL><INDENT>found.append(key)<EOL><DEDENT><DEDENT>return found<EOL>
This is the environment implementation of :meth:`BaseGroups.findGlyph`. **glyphName** will be an :ref:`type-string`. Subclasses may override this method.
f10839:c0:m4
def _get_side1KerningGroups(self):
found = {}<EOL>for name, contents in self.items():<EOL><INDENT>if name.startswith("<STR_LIT>"):<EOL><INDENT>found[name] = contents<EOL><DEDENT><DEDENT>return found<EOL>
Subclasses may override this method.
f10839:c0:m6
def _get_side2KerningGroups(self):
found = {}<EOL>for name, contents in self.items():<EOL><INDENT>if name.startswith("<STR_LIT>"):<EOL><INDENT>found[name] = contents<EOL><DEDENT><DEDENT>return found<EOL>
Subclasses may override this method.
f10839:c0:m8
def remove(self, groupName):
del self[groupName]<EOL>
Removes a group from the Groups. **groupName** will be a :ref:`type-string` that is the group name to be removed. This is a backwards compatibility method.
f10839:c0:m9
def asDict(self):
d = {}<EOL>for k, v in self.items():<EOL><INDENT>d[k] = v<EOL><DEDENT>return d<EOL>
Return the Groups as a ``dict``. This is a backwards compatibility method.
f10839:c0:m10
def __contains__(self, groupName):
return super(BaseGroups, self).__contains__(groupName)<EOL>
Tests to see if a group name is in the Groups. **groupName** will be a :ref:`type-string`. This returns a ``bool`` indicating if the **groupName** is in the Groups. :: >>> "myGroup" in font.groups True
f10839:c0:m11
def __delitem__(self, groupName):
super(BaseGroups, self).__delitem__(groupName)<EOL>
Removes **groupName** from the Groups. **groupName** is a :ref:`type-string`.:: >>> del font.groups["myGroup"]
f10839:c0:m12