slopometer 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
slopometer/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """Score prose for simplicity and precision against plain-English reference rules
2
+
3
+ Modules:
4
+
5
+ - `slopometer.cli`: The command line: score a file or stdin, warm
6
+ - `slopometer.core`: Tells, findings, the rule registry, and what the meter cannot see
7
+ - `slopometer.features`: Continuous measurements for learned scoring
8
+ - `slopometer.lexicon`: Word and phrase rules: banned vocabulary, hedges, fillers, and splices
9
+ - `slopometer.para`: Paragraph rules: restatement, elegant variation, forced symmetry, and coinage
10
+ - `slopometer.score`: Run every rule, weigh the findings, and report worst first
11
+ - `slopometer.segment`: Markdown becomes typed blocks that keep their file positions
12
+ - `slopometer.syntax`: The spaCy rules: sentences, clauses, passives, and the patterns anchored to them"""
13
+
14
+ __version__ = "0.0.1"
slopometer/_modidx.py ADDED
@@ -0,0 +1,64 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/slopometer',
5
+ 'doc_host': 'https://AnswerDotAI.github.io',
6
+ 'git_url': 'https://github.com/AnswerDotAI/slopometer',
7
+ 'lib_path': 'slopometer'},
8
+ 'syms': { 'slopometer.cli': {'slopometer.cli.main': ('cli.html#main', 'slopometer/cli.py')},
9
+ 'slopometer.core': { 'slopometer.core.Finding': ('core.html#finding', 'slopometer/core.py'),
10
+ 'slopometer.core.Finding.__init__': ('core.html#finding.__init__', 'slopometer/core.py'),
11
+ 'slopometer.core.Finding.__repr__': ('core.html#finding.__repr__', 'slopometer/core.py'),
12
+ 'slopometer.core.find_decoration': ('core.html#find_decoration', 'slopometer/core.py'),
13
+ 'slopometer.core.rule': ('core.html#rule', 'slopometer/core.py')},
14
+ 'slopometer.features': { 'slopometer.features.burstiness': ('features.html#burstiness', 'slopometer/features.py'),
15
+ 'slopometer.features.features': ('features.html#features', 'slopometer/features.py'),
16
+ 'slopometer.features.flattest_window': ('features.html#flattest_window', 'slopometer/features.py')},
17
+ 'slopometer.lexicon': { 'slopometer.lexicon.find_conseq': ('lexicon.html#find_conseq', 'slopometer/lexicon.py'),
18
+ 'slopometer.lexicon.find_emphasis': ('lexicon.html#find_emphasis', 'slopometer/lexicon.py'),
19
+ 'slopometer.lexicon.find_splice': ('lexicon.html#find_splice', 'slopometer/lexicon.py'),
20
+ 'slopometer.lexicon.lex_rule': ('lexicon.html#lex_rule', 'slopometer/lexicon.py')},
21
+ 'slopometer.para': { 'slopometer.para._content': ('para.html#_content', 'slopometer/para.py'),
22
+ 'slopometer.para.find_bullet_mold': ('para.html#find_bullet_mold', 'slopometer/para.py'),
23
+ 'slopometer.para.find_coinage': ('para.html#find_coinage', 'slopometer/para.py'),
24
+ 'slopometer.para.find_heading_echo': ('para.html#find_heading_echo', 'slopometer/para.py'),
25
+ 'slopometer.para.find_para_cap': ('para.html#find_para_cap', 'slopometer/para.py'),
26
+ 'slopometer.para.find_triad': ('para.html#find_triad', 'slopometer/para.py'),
27
+ 'slopometer.para.find_variation': ('para.html#find_variation', 'slopometer/para.py'),
28
+ 'slopometer.para.parse_blocks': ('para.html#parse_blocks', 'slopometer/para.py')},
29
+ 'slopometer.score': { 'slopometer.score.Result': ('score.html#result', 'slopometer/score.py'),
30
+ 'slopometer.score.Result.__init__': ('score.html#result.__init__', 'slopometer/score.py'),
31
+ 'slopometer.score.Result.__repr__': ('score.html#result.__repr__', 'slopometer/score.py'),
32
+ 'slopometer.score.Result._addr': ('score.html#result._addr', 'slopometer/score.py'),
33
+ 'slopometer.score.Result.density': ('score.html#result.density', 'slopometer/score.py'),
34
+ 'slopometer.score.Result.total': ('score.html#result.total', 'slopometer/score.py'),
35
+ 'slopometer.score.Result.worst': ('score.html#result.worst', 'slopometer/score.py'),
36
+ 'slopometer.score._rebase': ('score.html#_rebase', 'slopometer/score.py'),
37
+ 'slopometer.score.find_overstructure': ('score.html#find_overstructure', 'slopometer/score.py'),
38
+ 'slopometer.score.run_rules': ('score.html#run_rules', 'slopometer/score.py'),
39
+ 'slopometer.score.score_many': ('score.html#score_many', 'slopometer/score.py'),
40
+ 'slopometer.score.score_path': ('score.html#score_path', 'slopometer/score.py'),
41
+ 'slopometer.score.score_text': ('score.html#score_text', 'slopometer/score.py')},
42
+ 'slopometer.segment': { 'slopometer.segment.Block': ('segment.html#block', 'slopometer/segment.py'),
43
+ 'slopometer.segment.Block.__init__': ('segment.html#block.__init__', 'slopometer/segment.py'),
44
+ 'slopometer.segment.Block.__repr__': ('segment.html#block.__repr__', 'slopometer/segment.py'),
45
+ 'slopometer.segment.n_headings': ('segment.html#n_headings', 'slopometer/segment.py'),
46
+ 'slopometer.segment.prose_words': ('segment.html#prose_words', 'slopometer/segment.py'),
47
+ 'slopometer.segment.scrub': ('segment.html#scrub', 'slopometer/segment.py'),
48
+ 'slopometer.segment.segment': ('segment.html#segment', 'slopometer/segment.py')},
49
+ 'slopometer.syntax': { 'slopometer.syntax._own_subj': ('syntax.html#_own_subj', 'slopometer/syntax.py'),
50
+ 'slopometer.syntax._tok_find': ('syntax.html#_tok_find', 'slopometer/syntax.py'),
51
+ 'slopometer.syntax.find_artifact_agent': ('syntax.html#find_artifact_agent', 'slopometer/syntax.py'),
52
+ 'slopometer.syntax.find_clauses': ('syntax.html#find_clauses', 'slopometer/syntax.py'),
53
+ 'slopometer.syntax.find_intensifiers': ('syntax.html#find_intensifiers', 'slopometer/syntax.py'),
54
+ 'slopometer.syntax.find_nominalization': ('syntax.html#find_nominalization', 'slopometer/syntax.py'),
55
+ 'slopometer.syntax.find_noun_cluster': ('syntax.html#find_noun_cluster', 'slopometer/syntax.py'),
56
+ 'slopometer.syntax.find_passive': ('syntax.html#find_passive', 'slopometer/syntax.py'),
57
+ 'slopometer.syntax.find_recipient_subject': ( 'syntax.html#find_recipient_subject',
58
+ 'slopometer/syntax.py'),
59
+ 'slopometer.syntax.find_rhetorical': ('syntax.html#find_rhetorical', 'slopometer/syntax.py'),
60
+ 'slopometer.syntax.find_sent_len': ('syntax.html#find_sent_len', 'slopometer/syntax.py'),
61
+ 'slopometer.syntax.find_verb_banned': ('syntax.html#find_verb_banned', 'slopometer/syntax.py'),
62
+ 'slopometer.syntax.get_nlp': ('syntax.html#get_nlp', 'slopometer/syntax.py'),
63
+ 'slopometer.syntax.model_path': ('syntax.html#model_path', 'slopometer/syntax.py'),
64
+ 'slopometer.syntax.sent_rule': ('syntax.html#sent_rule', 'slopometer/syntax.py')}}}
slopometer/cli.py ADDED
@@ -0,0 +1,31 @@
1
+ """The command line: score a file or stdin, warm
2
+
3
+ `slopometer <file>` prints the worst-first report, `slopometer` alone reads stdin, and `--threshold` turns the density into an exit code for CI and hooks. Loading the model takes about a second and scoring takes milliseconds, so the command runs through [warmpy](https://github.com/AnswerDotAI/warmpy): the first call starts a background process that loads the model, later calls reuse it, and it exits after thirty idle minutes. The Claude Code stop hook runs this same command with the response text on stdin.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/cli.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/06_cli.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['main']
11
+
12
+ # %% ../nbs/06_cli.ipynb #01e3be12
13
+ import sys
14
+ from warmpy import warm_parse
15
+
16
+ # %% ../nbs/06_cli.ipynb #d21704e3
17
+ @warm_parse
18
+ def main(
19
+ path:str=None, # File to score; stdin when omitted
20
+ threshold:float=None, # Exit code 1 when density exceeds this
21
+ json:bool=False, # Emit the result as JSON instead of the report
22
+ ):
23
+ "Score markdown against the aai reference-prose rules"
24
+ from json import dumps
25
+ from slopometer.score import score_path, score_text
26
+ res = score_path(path) if path else score_text(sys.stdin.read())
27
+ if json: print(dumps(dict(density=res.density, worst=res.worst, words=res.words,
28
+ findings=[{k: getattr(f, k) for k in ('rule', 'tell', 'start', 'end', 'text', 'weight', 'suggestion')} for f in res.findings])))
29
+ else: print(res)
30
+ if threshold is not None and res.density > threshold: return 1
31
+
slopometer/core.py ADDED
@@ -0,0 +1,80 @@
1
+ """Tells, findings, the rule registry, and what the meter cannot see
2
+
3
+ slopometer measures prose against the reference-prose rules in `aai_coding.write_docs`: 26 numbered tells, the named ways reference prose goes wrong. This module defines what every rule shares: the table of tells, the `Finding` record every detector returns, the registry that rules join at import time, and the registry of tells no deterministic rule can detect.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/core.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['tells', 'KILL', 'SMELL', 'PRESSURE', 'rules', 'unscoreable', 'Finding', 'rule', 'find_decoration']
11
+
12
+ # %% ../nbs/00_core.ipynb #fa403df1
13
+ from fastcore.utils import *
14
+
15
+ # %% ../nbs/00_core.ipynb #5fecc627
16
+ tells = {
17
+ 1: 'splices', 2: 'contract by aside', 3: 'emphasis devices',
18
+ 4: 'elegant variation', 5: 'flourish over identifier', 6: 'consequence glue',
19
+ 7: 'hedging', 8: 'noting fillers', 9: 'restatement',
20
+ 10: 'justification rider', 11: 'decorative verbs', 12: 'audience misjudged',
21
+ 13: 'throat-clearing', 14: "today's-world opener", 15: 'announce-then-deliver',
22
+ 16: 'not-X-but-Y', 17: 'teaser pivot', 18: 'rhetorical questions',
23
+ 19: 'filler transitions', 20: 'forced symmetry', 21: 'appraisal preamble',
24
+ 22: 'artifact-as-agent', 23: 'recipient-as-subject', 24: 'decoration',
25
+ 25: 'over-structuring', 26: 'false depth'}
26
+
27
+ # %% ../nbs/00_core.ipynb #94d1c18f
28
+ KILL,SMELL,PRESSURE = 10,3,1
29
+
30
+ # %% ../nbs/00_core.ipynb #705a0d27
31
+ class Finding:
32
+ def __init__(self,
33
+ rule, # Name of the rule that fired
34
+ tell, # `write_docs` tell number the rule detects
35
+ start, # Character offset where the span starts, within the text the detector received
36
+ end, # Character offset one past the span's end
37
+ text, # The offending span itself
38
+ weight, # The rule's tier, escalated where the rule escalates
39
+ suggestion=None, # A mechanical replacement, when one exists
40
+ ): store_attr()
41
+ def __repr__(self):
42
+ sug = f' -> {self.suggestion!r}' if self.suggestion else ''
43
+ tl = '' if self.tell is None else f' (tell {self.tell}, {tells[self.tell]})'
44
+ return f'[{self.weight}] {self.rule}{tl}: {self.text!r}{sug}'
45
+
46
+ # %% ../nbs/00_core.ipynb #50e848c5
47
+ rules = {}
48
+
49
+ def rule(
50
+ name, # Rule name, unique within slopometer
51
+ tell, # `write_docs` tell number the rule detects
52
+ weight, # Tier the rule's findings carry
53
+ level, # The unit the detector reads: 'phrase', 'sentence', 'para', or 'doc'
54
+ ):
55
+ "Register a detector, a function from its unit's text to the list of `Finding`s in it"
56
+ def _f(f):
57
+ f.tell,f.weight,f.level = tell,weight,level
58
+ rules[name] = f
59
+ return f
60
+ return _f
61
+
62
+ # %% ../nbs/00_core.ipynb #d45bdd74
63
+ _ornament = re.compile(r'[\u2190-\u2bff\ufe0f\U0001f000-\U0001faff]+')
64
+ _arrows = {'→':'->', '⇒':'=>', '←':'<-', '↔':'<->'}
65
+
66
+ @rule('decoration', tell=24, weight=KILL, level='phrase')
67
+ def find_decoration(txt):
68
+ "Flag emoji and ornamental unicode, suggesting ASCII for arrows"
69
+ return [Finding('decoration', 24, m.start(), m.end(), m.group(), KILL, _arrows.get(m.group()))
70
+ for m in _ornament.finditer(txt)]
71
+
72
+ # %% ../nbs/00_core.ipynb #1af3670a
73
+ unscoreable = {
74
+ 2: 'knowing which fact is the contract takes judgment',
75
+ 5: "telling a flourish from a real identifier takes the project's vocabulary",
76
+ 9: 'lead-sentence restatement defeats averaged sentence vectors, and only the heading echo is detectable (measured in the para notebook)',
77
+ 10: 'a justification rider reads like a stated consequence, and only the domain says which it is',
78
+ 11: 'verb texture beyond the banned-verb lexicon is a whiteboard judgment',
79
+ 12: 'matching prose to its audience takes the audience, and the coinage rule covers only the definable half',
80
+ 26: 'depth is judged against what the reader already knows',}
slopometer/features.py ADDED
@@ -0,0 +1,83 @@
1
+ """Continuous measurements for learned scoring
2
+
3
+ The rules keep only what crosses a bar, and a learned scorer wants the bar removed. This module measures prose as continuous numbers: every rule's findings as a rate, the sentence and paragraph distributions the thresholds truncate, the parts-of-speech profile, specifics density, referential load, and burstiness. Three of these measures failed earlier as threshold rules, and the para and score notebooks record why. As features they need no threshold, because a learned combiner such as a random forest weighs them against labeled examples. The score stays rule-based and explainable. The feature vector exists for calibration experiments, and anything the experiments validate can graduate into a rule.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/features.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/07_features.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['burstiness', 'flattest_window', 'features']
11
+
12
+ # %% ../nbs/07_features.ipynb #e0f7d103
13
+ import statistics
14
+ from collections import Counter
15
+ from fastcore.utils import *
16
+ from .core import *
17
+ from .segment import *
18
+ from .lexicon import *
19
+ from .syntax import *
20
+ from .para import *
21
+ from .score import run_rules
22
+
23
+ # %% ../nbs/07_features.ipynb #bc8d7df9
24
+ def burstiness(xs):
25
+ "Goh-Barabasi B over `xs`: -1 uniform, 0 random, positive bursty"
26
+ if len(xs) < 2: return 0.0
27
+ m, s = statistics.mean(xs), statistics.stdev(xs)
28
+ return 0.0 if m + s == 0 else round((s - m) / (s + m), 3)
29
+
30
+ def flattest_window(
31
+ xs, # Sentence lengths, in document order
32
+ k=5, # Window size in sentences
33
+ ):
34
+ "`(start, spread)` of the length-`k` run with the lowest variation, for localizing monotone stretches"
35
+ if len(xs) <= k: return 0, round(statistics.stdev(xs), 2) if len(xs) > 1 else 0.0
36
+ spans = [(i, round(statistics.stdev(xs[i:i+k]), 2)) for i in range(len(xs) - k + 1)]
37
+ return min(spans, key=lambda t: t[1])
38
+
39
+ # %% ../nbs/07_features.ipynb #b422bd19
40
+ _conn = dict(add={'also', 'furthermore', 'moreover', 'additionally'}, causal={'because', 'therefore', 'thus', 'hence'},
41
+ advers={'but', 'however', 'although', 'though', 'yet'})
42
+
43
+ def features(txt):
44
+ "Continuous measurements of markdown `txt`, one flat dict"
45
+ blocks = segment(txt)
46
+ docs = parse_blocks(blocks)
47
+ prose = [d for d in docs if d is not None]
48
+ sents = [s for d in prose for s in d.sents]
49
+ toks = [t for d in prose for t in d]
50
+ nw = max(sum(1 for t in toks if t.is_alpha), 1)
51
+ res = dict(words=nw, sents=len(sents), headings=n_headings(blocks))
52
+ agg = Counter()
53
+ for f in run_rules(txt): agg[f.rule] += f.weight
54
+ res |= {f'r_{k}': round(100*v/nw, 2) for k, v in agg.items()}
55
+ res['density'] = round(100*sum(agg.values())/nw, 1)
56
+ slens = [sum(1 for t in s if not t.is_punct) for s in sents]
57
+ if len(slens) > 1:
58
+ res |= dict(slen_mean=round(statistics.mean(slens), 1), slen_max=max(slens), slen_burst=burstiness(slens))
59
+ starts = [next((t.lemma_.lower() for t in s if t.is_alpha), '') for s in sents]
60
+ res['start_div'] = round(len(set(starts))/len(starts), 2)
61
+ plens = [sum(1 for _ in d.sents) for d in prose]
62
+ if plens: res |= dict(psents_mean=round(statistics.mean(plens), 1), psents_max=max(plens))
63
+ pos = Counter(t.pos_ for t in toks)
64
+ res |= dict(adv=round(100*pos['ADV']/nw, 1), adj=round(100*pos['ADJ']/nw, 1),
65
+ noun_verb=round(pos['NOUN']/max(pos['VERB'], 1), 2),
66
+ cop=round(sum(1 for s in sents if s.root.lemma_ == 'be')/max(len(sents), 1), 2))
67
+ ncode = sum(len(re.findall(r'X{2,}', scrub(b.txt))) for b in blocks)
68
+ res['specifics'] = round(100*(pos['NUM'] + pos['PROPN'] + ncode)/nw, 1)
69
+ res['pron_subj'] = round(sum(1 for s in sents if any(t.dep_ in ('nsubj', 'nsubjpass') and t.pos_ == 'PRON'
70
+ and t.head.dep_ == 'ROOT' for t in s))/max(len(sents), 1), 2)
71
+ seen, ndef, ncold = set(), 0, 0
72
+ for d in prose:
73
+ for t in d:
74
+ if t.pos_ not in ('NOUN', 'PROPN') or len(set(t.lower_)) == 1: continue
75
+ lem = t.lemma_.lower()
76
+ kids = [c.lower_ for c in t.children]
77
+ if 'the' in kids and 'same' not in kids:
78
+ ndef += 1
79
+ if lem not in seen: ncold += 1
80
+ seen.add(lem)
81
+ res |= dict(defs=ndef, cold=round(ncold/max(ndef, 1), 2))
82
+ res |= {f'conn_{k}': round(100*sum(1 for t in toks if t.lemma_.lower() in v)/nw, 2) for k, v in _conn.items()}
83
+ return res
slopometer/lexicon.py ADDED
@@ -0,0 +1,93 @@
1
+ """Word and phrase rules: banned vocabulary, hedges, fillers, and splices
2
+
3
+ The phrase-level rules: banned vocabulary with plain replacements, hedge phrases, noting fillers, filler transitions, splice punctuation, consequence glue, and markdown emphasis. Each is a regex over a block's scrubbed text, needs no linguistic analysis, and runs in microseconds.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/lexicon.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_lexicon.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['banned', 'find_banned', 'hedges', 'noting', 'transitions', 'find_hedges', 'find_noting', 'find_transitions', 'wordy',
11
+ 'find_wordy', 'lex_rule', 'find_splice', 'find_conseq', 'find_emphasis']
12
+
13
+ # %% ../nbs/02_lexicon.ipynb #23bc602c
14
+ from fastcore.utils import *
15
+ from .core import *
16
+ from .segment import *
17
+
18
+
19
+ # %% ../nbs/02_lexicon.ipynb #449d550b
20
+ def lex_rule(
21
+ name, # Rule name, as in `core.rule`
22
+ tell, # `write_docs` tell number
23
+ weight, # Tier the findings carry
24
+ lex, # Vocabulary: word or phrase -> plain replacement, or None where deletion is the fix
25
+ suffix=False, # Also match inflected forms of each key?
26
+ ):
27
+ "Build and register a phrase rule that scans for `lex` entries case-insensitively"
28
+ tail = r'\w*' if suffix else ''
29
+ pat = re.compile(r'\b(' + '|'.join(re.escape(k) for k in sorted(lex, key=len, reverse=True)) + r')' + tail + r'\b', re.I)
30
+ def _f(txt): return [Finding(name, tell, m.start(), m.end(), m.group(), weight, lex.get(m.group(1).lower())) for m in pat.finditer(txt)]
31
+ _f.__name__,_f.__doc__ = f'find_{name}',f'Scan for the {name} vocabulary'
32
+ return rule(name, tell=tell, weight=weight, level='phrase')(_f)
33
+
34
+ # %% ../nbs/02_lexicon.ipynb #e9411861
35
+ banned = {'utilize': 'use', 'utilise': 'use', 'leverage': 'use', 'facilitate': 'help', 'robust': 'strong',
36
+ 'comprehensive': 'complete', 'seamless': 'smooth', 'enhance': 'improve', 'streamline': None,
37
+ 'empower': None, 'foster': 'encourage', 'pivotal': None, 'a testament to': None, 'realm': None,
38
+ 'landscape': None, 'delve': None, 'myriad': None, 'plethora': None, 'paradigm': None,
39
+ 'synergy': None, 'holistic': None, 'catalyze': None, 'catalyse': None, 'juxtapose': None,
40
+ 'tapestry': None, 'embark': None, 'endeavor': None, 'endeavour': None, 'encompass': None,
41
+ 'multifaceted': None, 'elucidate': 'explain', 'nuanced': None, 'liaise': None, 'overarching': None,
42
+ 'countless': 'many', 'incentivize': None, 'incentivise': None, 'game-changer': None,
43
+ 'cutting-edge': None, 'best-in-class': None, 'deliver results': None,
44
+ # adopted from the GOV.UK words-to-avoid list (OGL v3) and no-cliches (MIT); evidence below
45
+ 'initiate': 'start', 'tackle': 'solve', 'a clean slate': None, 'in a nutshell': None}
46
+
47
+ find_banned = lex_rule('banned', tell=None, weight=KILL, lex=banned, suffix=True)
48
+
49
+ # %% ../nbs/02_lexicon.ipynb #ef8d80e3
50
+ hedges = {'potentially': None, 'in some cases': None, 'should generally': None, 'may or may not': None,
51
+ 'one might argue': None, 'it could be argued': None, 'arguably': None, 'more or less': None,
52
+ # weasel words adopted from write-good's weasel-words (MIT); evidence below
53
+ 'very': None, 'quite': None, 'extremely': None, 'fairly': None, 'exceedingly': None, 'remarkably': None,
54
+ 'surprisingly': None, 'interestingly': None, 'clearly': None, 'completely': None, 'largely': None,
55
+ 'mostly': None, 'relatively': None, 'usually': None, 'significantly': None, 'substantially': None,
56
+ 'huge': None, 'tiny': None, 'vast': None, 'few': None, 'several': None, 'excellent': None}
57
+ noting = {'note that': None, "it's worth noting": None, 'it is worth noting': None, 'worth mentioning': None,
58
+ 'importantly': None, 'notably': None, 'keep in mind': None, 'bear in mind': None, 'it should be noted': None}
59
+ transitions = {'furthermore': 'and', 'moreover': 'and', 'additionally': 'also', 'in conclusion': None,
60
+ 'when it comes to': None, 'in the realm of': None}
61
+
62
+ find_hedges = lex_rule('hedges', tell=7, weight=SMELL, lex=hedges)
63
+ find_noting = lex_rule('noting', tell=8, weight=SMELL, lex=noting)
64
+ find_transitions = lex_rule('transitions', tell=19, weight=SMELL, lex=transitions)
65
+
66
+ # %% ../nbs/02_lexicon.ipynb #79549961
67
+ _splice = re.compile(r'—|(?<=\w) -- (?=\w)|(?<=\w); (?=\w)|(?<=\w) - (?=\w)')
68
+ _conseq = re.compile(r', so\b')
69
+
70
+ @rule('splice', tell=1, weight=KILL, level='phrase')
71
+ def find_splice(txt):
72
+ "Em dashes, two-hyphen dashes, semicolon joins, and spaced-hyphen joins"
73
+ return [Finding('splice', 1, m.start(), m.end(), m.group(), KILL) for m in _splice.finditer(txt)]
74
+
75
+ @rule('conseq', tell=6, weight=SMELL, level='phrase')
76
+ def find_conseq(txt):
77
+ "The ', so' consequence join"
78
+ return [Finding('conseq', 6, m.start(), m.end(), m.group(), SMELL) for m in _conseq.finditer(txt)]
79
+
80
+ # %% ../nbs/02_lexicon.ipynb #8daaf936
81
+ _emph = re.compile(r'\*\*[^*\n]+\*\*|(?<![\w*])\*[^*\s][^*\n]*\*(?![\w*])|(?<![\w_])__[^_\n]+__(?![\w_])')
82
+
83
+ @rule('emphasis', tell=3, weight=SMELL, level='phrase')
84
+ def find_emphasis(txt):
85
+ "Bold and italic markers in running prose"
86
+ return [Finding('emphasis', 3, m.start(), m.end(), m.group(), SMELL) for m in _emph.finditer(txt)]
87
+
88
+ # %% ../nbs/02_lexicon.ipynb #cdb0967f
89
+ wordy = {'all of': 'all', 'additional': 'more', 'a number of': 'some', 'along the lines of': 'like',
90
+ 'already existing': 'existing', 'adjacent to': 'next to', 'anticipate': 'expect',
91
+ 'in order to': 'to', 'going forward': 'from now on'}
92
+
93
+ find_wordy = lex_rule('wordy', tell=None, weight=SMELL, lex=wordy)
slopometer/para.py ADDED
@@ -0,0 +1,115 @@
1
+ """Paragraph rules: restatement, elegant variation, forced symmetry, and coinage
2
+
3
+ The rules that read a whole paragraph: restatement, elegant variation, forced symmetry, and coinage. The first two need a way to measure whether two different word sequences say the same thing, and word vectors provide it. The paragraph is the largest unit any of these rules analyzes, and coinage, which counts across paragraphs, does so with arithmetic alone.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/para.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_para.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['find_heading_echo', 'parse_blocks', 'find_variation', 'find_triad', 'find_bullet_mold', 'find_para_cap',
11
+ 'find_coinage']
12
+
13
+ # %% ../nbs/04_para.ipynb #adcc3c9f
14
+ from collections import Counter
15
+ from fastcore.utils import *
16
+ from .core import *
17
+ from .segment import *
18
+ from .syntax import *
19
+
20
+ # %% ../nbs/04_para.ipynb #625319b7
21
+ def _content(toks): return {t.lemma_.lower() for t in toks if t.is_alpha and not t.is_stop}
22
+
23
+ @rule('heading_echo', tell=9, weight=SMELL, level='doc')
24
+ def find_heading_echo(blocks, docs):
25
+ "A section's first sentence repeating its heading's words"
26
+ res = []
27
+ for b,nxt,d in zip(blocks, blocks[1:], docs[1:]):
28
+ if b.kind != 'heading' or nxt.kind != 'prose' or d is None: continue
29
+ hw = _content(get_nlp()(scrub(b.txt.lstrip('# '))))
30
+ if not hw: continue
31
+ s1 = list(d.sents)[0]
32
+ lead = first((t.lemma_.lower() for t in s1 if t.is_alpha and not t.is_stop), None)
33
+ if lead in hw and hw <= _content(s1): res.append(Finding('heading_echo', 9, nxt.start, nxt.start+len(s1.text), s1.text, SMELL))
34
+ return res
35
+
36
+ # %% ../nbs/04_para.ipynb #a2dbc1cf
37
+ def parse_blocks(blocks):
38
+ "The spaCy `Doc` for each prose block, aligned with `blocks`, None elsewhere"
39
+ prose = [b for b in blocks if b.kind=='prose']
40
+ parsed = iter(get_nlp().pipe([scrub(b.txt) for b in prose]))
41
+ return [next(parsed) if b.kind=='prose' else None for b in blocks]
42
+
43
+ # %% ../nbs/04_para.ipynb #16ad69f8
44
+ _variant_pairs = [{'folder', 'directory'}, {'method', 'function'}, {'parameter', 'argument'}, {'error', 'exception'}, {'docstring', 'documentation'}]
45
+
46
+ @rule('variation', tell=4, weight=SMELL, level='para')
47
+ def find_variation(doc):
48
+ "Two names for one concept within a paragraph, by curated pair or shared stem"
49
+ seen,res,done = {},[],set()
50
+ for t in doc:
51
+ if t.pos_ not in ('NOUN', 'PROPN') or not t.is_alpha or len(set(t.lower_)) == 1: continue
52
+ lem = t.lemma_.lower()
53
+ for prev in seen:
54
+ if prev == lem: continue
55
+ pair = any(prev in s and lem in s for s in _variant_pairs)
56
+ stem = (len(min(lem, prev, key=len)) >= 4 and (lem in prev or prev in lem)
57
+ and not doc.vocab[lem].is_oov and not doc.vocab[prev].is_oov)
58
+ if (pair or stem) and frozenset((prev, lem)) not in done:
59
+ done.add(frozenset((prev, lem)))
60
+ res.append(Finding('variation', 4, t.idx, t.idx+len(t.text), f'{seen[prev].text} ... {t.text}', SMELL))
61
+ break
62
+ seen[lem] = t
63
+ return res
64
+
65
+ # %% ../nbs/04_para.ipynb #5ce63501
66
+ @rule('triad', tell=20, weight=SMELL, level='para')
67
+ def find_triad(doc):
68
+ "Three or more coordinated nouns sharing one modifier lemma"
69
+ res = []
70
+ for t in doc:
71
+ if t.pos_ != 'NOUN': continue
72
+ group = [t] + [c for c in t.conjuncts if c.pos_ == 'NOUN']
73
+ if len(group) < 3 or any(g.i < t.i for g in group): continue
74
+ mods = [{m.lemma_ for m in g.children if m.dep_ == 'amod'} for g in group]
75
+ shared = set.intersection(*mods) if all(mods) else set()
76
+ if shared:
77
+ span = doc.text[group[0].idx:group[-1].idx+len(group[-1].text)]
78
+ res.append(Finding('triad', 20, group[0].idx, group[-1].idx+len(group[-1].text), span, SMELL))
79
+ return res
80
+
81
+ @rule('bullet_mold', tell=20, weight=SMELL, level='doc')
82
+ def find_bullet_mold(blocks, docs):
83
+ "Three or more consecutive list items opening with the same word"
84
+ res,run = [],[]
85
+ def word(b): return re.sub(r'^\s*(?:[-*+]|\d+[.)]) +', '', b.txt).split(' ')[0].lower() if b.txt else ''
86
+ for b in list(blocks) + [None]:
87
+ if b is not None and b.kind == 'item':
88
+ run.append(b)
89
+ continue
90
+ if len(run) >= 3 and len({word(x) for x in run}) == 1:
91
+ res.append(Finding('bullet_mold', 20, run[0].start, run[-1].start+len(run[-1].txt), '\n'.join(x.txt for x in run), SMELL))
92
+ run = []
93
+ return res
94
+
95
+ # %% ../nbs/04_para.ipynb #ddc5a702
96
+ @rule('para_cap', tell=None, weight=PRESSURE, level='para')
97
+ def find_para_cap(doc):
98
+ "Paragraphs past 150 words, escalating per extra 25"
99
+ n = sum(1 for t in doc if t.is_alpha)
100
+ if n <= 150: return []
101
+ return [Finding('para_cap', None, 0, len(doc.text), f'{n}-word paragraph', PRESSURE*((n-150)//25 + 1))]
102
+
103
+
104
+ # %% ../nbs/04_para.ipynb #236fd005
105
+ @rule('coinage', tell=12, weight=SMELL, level='doc')
106
+ def find_coinage(blocks, docs):
107
+ "A recurring out-of-vocabulary term outside backticks"
108
+ cnt,firsts = Counter(),{}
109
+ for b,d in zip(blocks, docs):
110
+ if d is None: continue
111
+ for t in d:
112
+ if not t.is_alpha or len(t.text) < 4 or not t.text.islower() or not t.is_oov: continue
113
+ cnt[t.text] += 1
114
+ if t.text not in firsts: firsts[t.text] = (b.start+t.idx, b.start+t.idx+len(t.text))
115
+ return [Finding('coinage', 12, *firsts[w], w, SMELL) for w,c in cnt.items() if c >= 2]
slopometer/score.py ADDED
@@ -0,0 +1,93 @@
1
+ """Run every rule, weigh the findings, and report worst first
2
+
3
+ The meter assembled: one pass that segments a document, runs every registered rule at its level, rebases every finding onto document offsets, and reduces the findings to two numbers. Density is weighted findings per 100 prose words, and the max is the single worst finding. A clean document scores near zero on both. One kill-on-sight finding pushes the max to 10 alone, which is the tiers doing their job.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/score.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/05_score.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['find_overstructure', 'run_rules', 'Result', 'score_text', 'score_path', 'score_many']
11
+
12
+ # %% ../nbs/05_score.ipynb #68d2aa09
13
+ from fastcore.utils import *
14
+ from fastcore.tools import lnhash_at
15
+ from .core import *
16
+ from .segment import *
17
+ from .lexicon import *
18
+ from .syntax import *
19
+ from .para import *
20
+
21
+ # %% ../nbs/05_score.ipynb #d2f5895b
22
+ @rule('overstructure', tell=25, weight=SMELL, level='doc')
23
+ def find_overstructure(blocks, docs):
24
+ "More headings than the prose beneath them justifies"
25
+ nh,nw = n_headings(blocks), prose_words(blocks)
26
+ if nh < 2 or nw/nh >= 40: return []
27
+ hs = [b for b in blocks if b.kind == 'heading']
28
+ return [Finding('overstructure', 25, hs[0].start, hs[0].start+len(hs[0].txt),
29
+ f'{nh} headings on {nw} words of prose', SMELL)]
30
+
31
+ # %% ../nbs/05_score.ipynb #3d4515d6
32
+ def _rebase(fs, off):
33
+ for f in fs:
34
+ f.start += off
35
+ f.end += off
36
+ return fs
37
+
38
+ def run_rules(txt):
39
+ "Every registered rule's findings for markdown `txt`, rebased to document offsets"
40
+ blocks = segment(txt)
41
+ docs = parse_blocks(blocks)
42
+ out = []
43
+ for b,d in zip(blocks, docs):
44
+ sc = scrub(b.txt)
45
+ for r in rules.values():
46
+ if r.level == 'phrase': out += _rebase(r(sc), b.start)
47
+ elif d is None: continue
48
+ elif r.level == 'sentence':
49
+ for s in d.sents: out += _rebase(r(s), b.start+s.start_char)
50
+ elif r.level == 'para': out += _rebase(r(d), b.start)
51
+ for r in rules.values():
52
+ if r.level == 'doc': out += r(blocks, docs)
53
+ return sorted(out, key=lambda f: (-f.weight, f.start))
54
+
55
+
56
+ # %% ../nbs/05_score.ipynb #829de200
57
+ class Result:
58
+ def __init__(self,
59
+ txt, # The scored document
60
+ findings, # `Finding`s, worst first
61
+ words, # Prose word count
62
+ path=None, # Source file, when scoring a file
63
+ ):
64
+ store_attr()
65
+ for f in findings:
66
+ if len(f.text) == f.end-f.start and '\n' not in txt[f.start:f.end]: f.text = txt[f.start:f.end]
67
+ @property
68
+ def total(self): return sum(f.weight for f in self.findings)
69
+ @property
70
+ def density(self): return round(100*self.total/max(self.words, 1), 1)
71
+ @property
72
+ def worst(self): return max((f.weight for f in self.findings), default=0)
73
+ def _addr(self, f):
74
+ ln = self.txt[:f.start].count('\n')+1
75
+ return lnhash_at(self.txt, ln) if self.path else f'{ln}:'
76
+ def __repr__(self):
77
+ hdr = f'density {self.density} (weight {self.total} on {self.words} prose words), worst {self.worst}'
78
+ if self.path: hdr = f'{self.path}: {hdr}'
79
+ return '\n'.join([hdr] + [f'{self._addr(f)} {f!r}' for f in self.findings])
80
+
81
+ def score_text(txt):
82
+ "Score markdown `txt`, returning a `Result`"
83
+ return Result(txt, run_rules(txt), prose_words(segment(txt)))
84
+
85
+ def score_path(p):
86
+ "Score the file at `p`; report rows carry exhash addresses"
87
+ txt = Path(p).read_text()
88
+ return Result(txt, run_rules(txt), prose_words(segment(txt)), path=Path(p))
89
+
90
+ # %% ../nbs/05_score.ipynb #0e3b855b
91
+ def score_many(txts, n_workers=8):
92
+ "Score texts in parallel threads, returning a `Result` per text"
93
+ return parallel(score_text, txts, n_workers=n_workers, threadpool=True)
slopometer/segment.py ADDED
@@ -0,0 +1,60 @@
1
+ """Markdown becomes typed blocks that keep their file positions
2
+
3
+ Rules read prose, but slopometer's input is markdown: READMEs, docstrings rendered from notebooks, PR text, chat responses. Segmentation turns a markdown document into typed blocks (heading, list item, prose paragraph) that remember where they came from, discards fenced code entirely, and blanks inline code so that lexical rules never fire on identifiers. Every downstream stage depends on the position bookkeeping here: a finding is only useful if it can point back at the exact file offset it came from.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/segment.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_segment.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['Block', 'segment', 'scrub', 'n_headings', 'prose_words']
11
+
12
+ # %% ../nbs/01_segment.ipynb #694196b8
13
+ from fastcore.utils import *
14
+ import mdhtml
15
+ from .core import *
16
+
17
+ # %% ../nbs/01_segment.ipynb #8e3a315e
18
+ class Block:
19
+ def __init__(self,
20
+ kind, # 'heading', 'item', or 'prose'
21
+ txt, # The block's text, sliced verbatim from the document after iframe blanking
22
+ start, # Character offset of the block in the document
23
+ ): store_attr()
24
+ def __repr__(self): return f'<{self.kind} @{self.start}: {self.txt[:48]!r}>'
25
+
26
+ _iframe = re.compile(r'<iframe\b.*?</iframe\s*>', re.S | re.I)
27
+ _item = re.compile(r'^\s*(?:[-*+]|\d+[.)]) ')
28
+ _KINDS = dict(paragraph='prose', heading='heading')
29
+
30
+ def segment(doc):
31
+ "Split markdown `doc` into typed `Block`s that keep their character offsets"
32
+ doc = _iframe.sub(lambda m: re.sub(r'[^\n]', ' ', m.group()), doc)
33
+ lines = doc.split('\n')
34
+ offs, n = [], 0
35
+ for l in lines:
36
+ offs.append(n)
37
+ n += len(l) + 1
38
+ out = []
39
+ for b in mdhtml.blocks(doc):
40
+ seg = lines[b['start']:b['end']]
41
+ if b['type'] == 'list':
42
+ out += [Block('item', l, offs[b['start']+i]) for i,l in enumerate(seg) if _item.match(l)]
43
+ elif b['type'] in _KINDS:
44
+ txt = '\n'.join(seg).strip('\n')
45
+ if txt.strip(): out.append(Block(_KINDS[b['type']], txt, offs[b['start']]))
46
+ return L(out)
47
+
48
+ # %% ../nbs/01_segment.ipynb #6c25fbfe
49
+ _icode = re.compile(r'`[^`\n]+`')
50
+ _ltarget = re.compile(r'\]\([^)\n]+\)')
51
+
52
+ def scrub(txt):
53
+ "Replace inline code with X-fill and link targets with spaces, keeping every offset unchanged"
54
+ txt = _icode.sub(lambda m: 'X'*len(m.group()), txt)
55
+ return _ltarget.sub(lambda m: ' '*len(m.group()), txt)
56
+
57
+
58
+ # %% ../nbs/01_segment.ipynb #6052473a
59
+ def n_headings(blocks): return sum(1 for b in blocks if b.kind=='heading')
60
+ def prose_words(blocks): return sum(len(b.txt.split()) for b in blocks if b.kind=='prose')
slopometer/syntax.py ADDED
@@ -0,0 +1,192 @@
1
+ """The spaCy rules: sentences, clauses, passives, and the patterns anchored to them
2
+
3
+ The rules that need to know what a sentence is and how its words relate: sentence length, clause count, passive voice, part-of-speech-dependent vocabulary, noun clusters, nominalizations, agent defocusing, and the slop patterns that anchor to sentence starts. [spaCy](https://spacy.io) provides the linguistic analysis, and this module also owns getting spaCy's model onto the machine.
4
+
5
+ Docs: https://AnswerDotAI.github.io/slopometer/syntax.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_syntax.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['MODEL', 'MODEL_PKG', 'MODEL_URL', 'find_throat', 'find_todays', 'find_announce', 'find_notxbuty', 'find_teaser',
11
+ 'find_appraisal', 'model_path', 'get_nlp', 'find_sent_len', 'find_clauses', 'find_passive',
12
+ 'find_verb_banned', 'find_intensifiers', 'find_noun_cluster', 'find_nominalization', 'find_artifact_agent',
13
+ 'find_recipient_subject', 'sent_rule', 'find_rhetorical']
14
+
15
+ # %% ../nbs/03_syntax.ipynb #e2b9a004
16
+ import spacy, zipfile, shutil, importlib
17
+ from fastcore.utils import *
18
+ from fastcore.net import urlsave
19
+ from fastcore.xdg import xdg_cache_home
20
+ from .core import *
21
+ from .segment import *
22
+
23
+ # %% ../nbs/03_syntax.ipynb #4e72a817
24
+ MODEL = 'en_core_web_md-3.8.0'
25
+ MODEL_PKG = MODEL.rsplit('-', 1)[0]
26
+ MODEL_URL = f'https://github.com/explosion/spacy-models/releases/download/{MODEL}/{MODEL}-py3-none-any.whl'
27
+
28
+ def model_path():
29
+ "Path of the model data directory: the installed package if present, else the cache, downloading on first call"
30
+ try: return Path(importlib.import_module(MODEL_PKG).__file__).parent/MODEL
31
+ except ImportError: pass
32
+ dest = xdg_cache_home()/'slopometer'
33
+ p = dest/MODEL
34
+ if p.exists(): return p
35
+ print(f'slopometer: downloading {MODEL} (~40MB, once per machine) to {p}')
36
+ dest.mkdir(parents=True, exist_ok=True)
37
+ whl = urlsave(MODEL_URL, dest/f'{MODEL}.whl')
38
+ with zipfile.ZipFile(whl) as z:
39
+ pfx = f'{MODEL_PKG}/{MODEL}/'
40
+ for n in z.namelist():
41
+ if n.startswith(pfx): z.extract(n, dest/'tmp')
42
+ shutil.move(dest/'tmp'/MODEL_PKG/MODEL, p)
43
+ shutil.rmtree(dest/'tmp')
44
+ Path(whl).unlink()
45
+ return p
46
+
47
+ _nlp = None
48
+ def get_nlp():
49
+ "The loaded pipeline, one per process"
50
+ global _nlp
51
+ if _nlp is None: _nlp = spacy.load(model_path())
52
+ return _nlp
53
+
54
+ # %% ../nbs/03_syntax.ipynb #d8078a42
55
+ @rule('sent_len', tell=1, weight=PRESSURE, level='sentence')
56
+ def find_sent_len(sent):
57
+ "Sentences past 25 words, escalating one weight point per extra word"
58
+ n = sum(1 for t in sent if not t.is_punct)
59
+ if n <= 25: return []
60
+ return [Finding('sent_len', 1, 0, len(sent.text), sent.text, PRESSURE*(n-25))]
61
+
62
+ _clausy = {'advcl', 'ccomp'}
63
+
64
+ def _own_subj(t): return any(c.dep_ in ('nsubj', 'nsubjpass', 'expl') for c in t.children)
65
+
66
+ @rule('clauses', tell=1, weight=PRESSURE, level='sentence')
67
+ def find_clauses(sent):
68
+ "Sentences stacking four or more idea-bearing clauses, escalating per extra clause"
69
+ n = 1 + sum(1 for t in sent if t.pos_ in ('VERB', 'AUX')
70
+ and (t.dep_ in _clausy or (t.dep_ == 'conj' and _own_subj(t))))
71
+ if n < 4: return []
72
+ return [Finding('clauses', 1, 0, len(sent.text), sent.text, PRESSURE*(n-3))]
73
+
74
+ # %% ../nbs/03_syntax.ipynb #9431332d
75
+ @rule('passive', tell=None, weight=SMELL, level='sentence')
76
+ def find_passive(sent):
77
+ "Passive constructions, weighted higher when no agent survives"
78
+ res = []
79
+ for t in sent:
80
+ if t.dep_ != 'nsubjpass': continue
81
+ v = t.head
82
+ agented = any(c.dep_ == 'agent' for c in v.children)
83
+ span = sent.text[t.idx-sent.start_char:v.idx-sent.start_char+len(v.text)]
84
+ res.append(Finding('passive', None, t.idx-sent.start_char, v.idx-sent.start_char+len(v.text), span, PRESSURE if agented else SMELL))
85
+ return res
86
+
87
+ # %% ../nbs/03_syntax.ipynb #6db9f87a
88
+ _verb_banned = dict(impact='affect', land=None, shape=None, ride=None)
89
+ _intens = {'simply', 'merely', 'effortlessly'}
90
+
91
+ def _tok_find(name, tell, weight, sent, pred, lex=None):
92
+ "Findings for tokens of `sent` passing `pred`, with optional suggestions from `lex`"
93
+ return [Finding(name, tell, t.idx-sent.start_char, t.idx-sent.start_char+len(t.text), t.text, weight,
94
+ lex.get(t.lemma_) if lex else None) for t in sent if pred(t)]
95
+
96
+ @rule('verb_banned', tell=None, weight=KILL, level='sentence')
97
+ def find_verb_banned(sent):
98
+ "Words banned as verbs, caught by lemma and POS"
99
+ return _tok_find('verb_banned', None, KILL, sent, lambda t: t.pos_ == 'VERB' and t.lemma_ in _verb_banned
100
+ and not (t.i > 0 and t.nbor(-1).text == '-'), _verb_banned)
101
+
102
+ @rule('intensifiers', tell=3, weight=SMELL, level='sentence')
103
+ def find_intensifiers(sent):
104
+ "Ease-claiming adverbs"
105
+ return _tok_find('intensifiers', 3, SMELL, sent, lambda t: t.pos_ == 'ADV' and t.lemma_ in _intens)
106
+
107
+ # %% ../nbs/03_syntax.ipynb #0442a84f
108
+ _light = {'make', 'take', 'perform', 'conduct', 'do', 'carry'}
109
+ _denoun = dict(decision='decide', assessment='assess', improvement='improve', comparison='compare',
110
+ configuration='configure', modification='modify', evaluation='evaluate', determination='determine',
111
+ implementation='implement', investigation='investigate', selection='select', validation='validate')
112
+
113
+ @rule('noun_cluster', tell=None, weight=PRESSURE, level='sentence')
114
+ def find_noun_cluster(sent):
115
+ "Runs of three or more nouns, escalating per extra noun"
116
+ res,run = [],[]
117
+ for t in list(sent) + [None]:
118
+ if t is not None and t.pos_ in ('NOUN', 'PROPN'):
119
+ run.append(t)
120
+ continue
121
+ n = sum(x.pos_ == 'NOUN' for x in run)
122
+ if n >= 3:
123
+ span = sent.text[run[0].idx-sent.start_char:run[-1].idx-sent.start_char+len(run[-1].text)]
124
+ res.append(Finding('noun_cluster', None, run[0].idx-sent.start_char, run[-1].idx-sent.start_char+len(run[-1].text), span, PRESSURE*(n-2)))
125
+ run = []
126
+ return res
127
+
128
+ @rule('nominalization', tell=None, weight=SMELL, level='sentence')
129
+ def find_nominalization(sent):
130
+ "Light verbs carrying a nominalized object"
131
+ res = []
132
+ for t in sent:
133
+ if t.pos_ == 'VERB' and t.lemma_ in _light:
134
+ for c in t.children:
135
+ if c.dep_ == 'dobj' and c.lemma_ in _denoun:
136
+ span = sent.text[t.idx-sent.start_char:c.idx-sent.start_char+len(c.text)]
137
+ res.append(Finding('nominalization', None, t.idx-sent.start_char, c.idx-sent.start_char+len(c.text), span, SMELL, _denoun[c.lemma_]))
138
+ return res
139
+
140
+ # %% ../nbs/03_syntax.ipynb #7b3c63b5
141
+ _artifacts = {'pr', 'commit', 'change', 'patch', 'release', 'update', 'design', 'proposal', 'document', 'doc', 'readme', 'section', 'paragraph', 'refactor'}
142
+ _credit_verbs = {'introduce', 'enable', 'allow', 'let', 'add', 'improve', 'fix', 'ensure', 'provide', 'bring', 'unlock'}
143
+
144
+ @rule('artifact_agent', tell=22, weight=SMELL, level='sentence')
145
+ def find_artifact_agent(sent):
146
+ "Authored artifacts credited with their author's deed"
147
+ res = []
148
+ for t in sent:
149
+ if t.dep_ == 'nsubj' and t.lemma_.lower() in _artifacts and t.head.lemma_ in _credit_verbs:
150
+ span = sent.text[t.idx-sent.start_char:t.head.idx-sent.start_char+len(t.head.text)]
151
+ res.append(Finding('artifact_agent', 22, t.idx-sent.start_char, t.head.idx-sent.start_char+len(t.head.text), span, SMELL))
152
+ return res
153
+
154
+ @rule('recipient_subject', tell=23, weight=SMELL, level='sentence')
155
+ def find_recipient_subject(sent):
156
+ "Beneficiaries promoted to subject with gain/receive, or get with a via phrase"
157
+ res = []
158
+ for t in sent:
159
+ if t.pos_ != 'VERB' or t.lemma_ not in ('gain', 'receive', 'get'): continue
160
+ if not any(c.dep_ == 'nsubj' for c in t.children): continue
161
+ demoted = any(c.lemma_ in ('via', 'through') for c in t.subtree if c.pos_ == 'ADP')
162
+ if t.lemma_ == 'get' and not demoted: continue
163
+ res.append(Finding('recipient_subject', 23, t.idx-sent.start_char, t.idx-sent.start_char+len(t.text), t.text, SMELL))
164
+ return res
165
+
166
+ # %% ../nbs/03_syntax.ipynb #69415f9a
167
+ def sent_rule(
168
+ name, # Rule name, as in `core.rule`
169
+ tell, # `write_docs` tell number
170
+ weight, # Tier the findings carry
171
+ pats, # Phrase list; each becomes a case-insensitive regex alternative
172
+ anchored=False, # Match only at the sentence start?
173
+ ):
174
+ "Build and register a sentence rule that scans `pats` in the sentence text"
175
+ pat = re.compile(('^' if anchored else '') + '(' + '|'.join(pats) + ')', re.I)
176
+ def _f(sent): return [Finding(name, tell, m.start(), m.end(), m.group(), weight) for m in pat.finditer(sent.text)]
177
+ _f.__name__,_f.__doc__ = f'find_{name}',f'Scan for {name} phrases'
178
+ return rule(name, tell=tell, weight=weight, level='sentence')(_f)
179
+
180
+ find_throat = sent_rule('throat_clearing', 13, SMELL, [r"this (?:section|document|readme|page|guide|module|doc|notebook) (?:describes|covers|explains|documents|provides|outlines|introduces)", r'the purpose of this'], anchored=True)
181
+ find_todays = sent_rule('todays_world', 14, SMELL, [r"in today's"], anchored=True)
182
+ find_announce = sent_rule('announce', 15, SMELL, [r"(?:the (?:fix|answer|solution|key|result|takeaway|core \w+)|here's the thing|bottom line): "], anchored=True)
183
+ find_notxbuty = sent_rule('notxbuty', 16, KILL, [r"\bis(?:n't| not) (?:just|merely|simply|only) (?:a|an|the|about)\b", r"\baren't (?:just|merely|simply|only)\b", r"\bit's not about\b", r"\bnot (?:just|merely) about\b"])
184
+ find_teaser = sent_rule('teaser', 17, SMELL, [r"here's where it gets", r'\bthe real story\b', r'\bgets (?:really )?interesting\b', r'\bthe main event\b'])
185
+ find_appraisal = sent_rule('appraisal', 21, SMELL, [r'\bworth being precise\b', r"\bthe key (?:point|insight|thing) is\b", r"\bwhat's interesting is\b", r'\bcrucially\b', r'\bthe important thing is\b'])
186
+
187
+ @rule('rhetorical', tell=18, weight=SMELL, level='sentence')
188
+ def find_rhetorical(sent):
189
+ "Sentences that ask the reader a question"
190
+ t = sent.text.rstrip()
191
+ if not t.endswith('?'): return []
192
+ return [Finding('rhetorical', 18, 0, len(t), t, SMELL)]
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: slopometer
3
+ Version: 0.0.1
4
+ Summary: Score prose for simplicity and precision against plain-English reference rules
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/slopometer
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/slopometer/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore
16
+ Requires-Dist: spacy
17
+ Requires-Dist: mdhtml
18
+ Requires-Dist: warmpy>=0.1.0
19
+ Dynamic: license-file
20
+
21
+ # slopometer
22
+
23
+
24
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
25
+
26
+ `slopometer` measures prose against the aai reference-prose rules defined in `aai_coding.write_docs`. The rules merge GOV.UK/GDS house style with the discipline of ASD-STE100. It covers 26 numbered tells, banned-word lists, and the reference register itself. The meter is for anyone shipping READMEs, docstrings, PR text, or agent responses. It catches slop mechanically, in milliseconds, with no LLM in the loop. Every finding cites a rule, quotes a span, and carries a weight. A document reduces to two numbers: density, the weighted findings per 100 prose words, and the single worst finding.
27
+
28
+ ## Install
29
+
30
+ pip install slopometer
31
+
32
+ The first score on a machine downloads spaCy’s `en_core_web_md` model (about 40MB, once) into `~/.cache/slopometer` and loads it by path. The model never enters a virtual environment. One copy serves every project. Environment syncs cannot remove it.
33
+
34
+ ## Use
35
+
36
+ ``` python
37
+ from slopometer.score import score_text, score_path
38
+ ```
39
+
40
+ ``` python
41
+ score_text("This section describes our approach. It isn't just a linter - it's a comprehensive paradigm for quality.")
42
+ ```
43
+
44
+ density 252.9 (weight 43 on 17 prose words), worst 10
45
+ 1: [10] notxbuty (tell 16, not-X-but-Y): "isn't just a"
46
+ 1: [10] splice (tell 1, splices): ' - '
47
+ 1: [10] banned: 'comprehensive' -> 'complete'
48
+ 1: [10] banned: 'paradigm'
49
+ 1: [3] throat_clearing (tell 13, throat-clearing): 'This section describes'
50
+
51
+ [`score_path`](https://AnswerDotAI.github.io/slopometer/score.html#score_path) does the same for a file, and its rows carry `lineno|hash|` addresses in the exhash format, ready for hash-verified editors. The command line wraps both:
52
+
53
+ slopometer README.md
54
+ git log -1 --format=%B | slopometer
55
+ slopometer draft.md --threshold 10
56
+
57
+ The threshold turns the density into an exit code for CI. The command runs warm through `warmpy`. The first call loads the model in a background process. Later calls answer in milliseconds. After thirty idle minutes the process exits.
58
+
59
+ ## What it checks, and what it cannot
60
+
61
+ The rules live in notebooks that teach each family beside its code. Each rule states its tell, shows a violating example, and shows the plain rewrite. The [lexicon notebook](https://AnswerDotAI.github.io/slopometer/lexicon.html) holds the word and phrase rules. The [syntax notebook](https://AnswerDotAI.github.io/slopometer/syntax.html) builds sentence rules on spaCy’s parse. The [para notebook](https://AnswerDotAI.github.io/slopometer/para.html) builds its rules on word vectors. The [score notebook](https://AnswerDotAI.github.io/slopometer/score.html) assembles the pipeline. A drift test asserts that every `write_docs` tell maps to a rule or to an explicit unscoreable registry. The meter and the style guide cannot drift apart silently.
62
+
63
+ A rule ships only when its false-positive rate on clean reference prose is near zero. The meter scores the style guide’s own clean passage at exactly 0.0. The score notebook measures the blind spot instead of hiding it: mechanically chopped prose passes every surface rule while staying opaque. Agent review (`check_docs`) and an optional, explicitly invoked [Pangram](https://www.pangram.com) check cover that residue. Vale, write-good, and proselint solve neighboring problems. The [lexicon notebook](https://AnswerDotAI.github.io/slopometer/lexicon.html) records what came from them. It also credits the [GOV.UK words-to-avoid list](https://www.gov.uk/guidance/style-guide/a-to-z-of-gov-uk-style#words-to-avoid) (OGL v3).
@@ -0,0 +1,16 @@
1
+ slopometer/__init__.py,sha256=uOgR0YFyu43_aXCkjPbB0f3CMKPmRZz04KIpCTz3bmQ,805
2
+ slopometer/_modidx.py,sha256=BYdxgADPvPdbC_P4T4n0uiwP1-hgBISV5X02TMd73gI,7144
3
+ slopometer/cli.py,sha256=q2PvZ65KhonxXs82Gb1KOneMH3PcW36VB4vx_JGKoJ0,1574
4
+ slopometer/core.py,sha256=SCzwgDO7H_XANelyykyf8OdvcvMIvej9_sx8mZN2BoY,4043
5
+ slopometer/features.py,sha256=VmLrJDngOK7ky01GWtw8Vp-76tB67DMmq_ILqdj_QOk,4442
6
+ slopometer/lexicon.py,sha256=U8ujIWnsi5T0JcqyNNmjdjT_mz1hEgBOP8TUo41q7cA,5537
7
+ slopometer/para.py,sha256=vdqZFGLnV41qOktLK9ygtViMkOSgenuNvMmsr_RITuk,5512
8
+ slopometer/score.py,sha256=_x7hVMr5WeDMYFBFcoiL7C-OzlNP_Zwsx9y4dTo-wc8,3855
9
+ slopometer/segment.py,sha256=iXbQfsnW4xpAqNgH6zsClFFcRyHOEOK5y4TKnw_O5ZI,2677
10
+ slopometer/syntax.py,sha256=PXsusjUvAkwbja4diZMLmMDNggoq05o0wGuMWZxSF54,10133
11
+ slopometer-0.0.1.dist-info/licenses/LICENSE,sha256=xV8xoN4VOL0uw9X8RSs2IMuD_Ss_a9yAbtGNeBWZwnw,11337
12
+ slopometer-0.0.1.dist-info/METADATA,sha256=wUfR4P81odAtXG-1CHrAA98wyJ8oIoLVXPlhVeWFYjY,4273
13
+ slopometer-0.0.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
14
+ slopometer-0.0.1.dist-info/entry_points.txt,sha256=YNtgGk2GVrE0ZbpDDSA5O32lp0KCKe2UlJOadgDQHgE,94
15
+ slopometer-0.0.1.dist-info/top_level.txt,sha256=WFrHEDtWEPAN3UeQa3QJo4nqbnx5-bjeiZmxd8Od7ZA,11
16
+ slopometer-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ slopometer = slopometer.cli:main
3
+
4
+ [nbdev]
5
+ slopometer = slopometer._modidx:d
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022, fastai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ slopometer