"""Check an article draft before an expert reviews it, and before it becomes a podcast. python3 check_article.py draft.json [rules.json] python3 check_article.py selftest draft.json (what the writer skill saves): {"id", "title", "description", "status": "draft", "sources": [{"id", "title", "organization", "url"}], "sections": [{"heading", "paragraphs": ["... [1]"], "bullets": [...]}], "review_notes": [...]} rules.json (optional, your business's own limits): {"never_say": ["guaranteed", "cure"], "must_say": ["988"], "words": [400, 750]} It reports, in plain words: - shape: title and description lengths, 5-8 sections, word count, status still "draft" - sources: every [n] points to a source, every source is cited, every link is https - sentences with a number, percent or "study" but no [n] on them (likely unsourced claims) - listening: web addresses, symbols, tables or "see above"; very long sentences; abbreviations used before they are spelled out once - your rules: phrases you never allow, lines that must appear - review notes present, and saying it has not been reviewed yet Exit code 0 = ready for the expert; 1 = fix the listed items first. Free to use (MIT). Built for the Her Mind & Wellness guides by Shahrouz Ghadimi. """ import json import re import sys DEFAULT = {'never_say': ['guaranteed', 'cure', 'miracle', 'risk-free', '100% safe'], 'must_say': [], 'words': [400, 750]} CITE = re.compile(r'\[(\d+(?:\s*[,–-]\s*\d+)*)\]') ABBR = re.compile(r'\b([A-Z]{2,6})s?\b') COMMON = {'US', 'USA', 'OK', 'TV', 'AM', 'PM', 'ID', 'FAQ', 'AI'} def sentences(text): return [s for s in re.split(r'(?<=[.!?])\s+(?=[A-Z0-9“"(])', text) if s.strip()] def numbers(ref): out = set() for part in re.split(r'\s*,\s*', ref): if re.search(r'[–-]', part): a, b = [int(x) for x in re.split(r'\s*[–-]\s*', part)] out |= set(range(a, b + 1)) else: out.add(int(part)) return out def check(draft, rules=None): rules = {**DEFAULT, **(rules or {})} fix, note = [], [] title, desc = draft.get('title', ''), draft.get('description', '') if not 10 <= len(title) <= 110: fix.append(f'Title is {len(title)} characters; keep it 10 to 110.') if not 40 <= len(desc) <= 210: fix.append(f'Description is {len(desc)} characters; keep it 40 to 210.') if draft.get('status') != 'draft': fix.append('Status must stay "draft" until the expert approves it.') sections = draft.get('sections') or [] if not 5 <= len(sections) <= 8: note.append(f'{len(sections)} sections; 5 to 8 usually reads best.') body = [] for s in sections: if not s.get('heading', '').strip(): fix.append('A section has no heading.') elif len(s['heading']) > 80: note.append(f'Long heading (spoken by the co-host): "{s["heading"][:60]}…"') if not s.get('paragraphs') and not s.get('bullets'): fix.append(f'Section "{s.get("heading", "?")}" is empty.') body += s.get('paragraphs', []) + s.get('bullets', []) text = ' '.join(body) words = len(CITE.sub('', text).split()) lo, hi = rules['words'] if not lo <= words <= hi: note.append(f'{words} words; aim for {lo} to {hi} (about 3 to 6 minutes as a podcast).') sources = draft.get('sources') or [] cited = set() for ref in CITE.findall(text): cited |= numbers(ref) for n in sorted(cited): if not 1 <= n <= len(sources): fix.append(f'[{n}] points to no source (there are {len(sources)}).') for i, s in enumerate(sources, 1): if i not in cited: fix.append(f'Source {i} ("{s.get("title", "?")}") is never cited.') if not str(s.get('url', '')).startswith('https://'): fix.append(f'Source {i} needs an https link.') if not sources: fix.append('No sources. Every factual claim needs one.') for p in body: for s in sentences(p): plain = re.sub(r'\b(911|988)\b|\b\d{1,2}:\d{2}\b|\b(19|20)\d{2}\b', '', s) if re.search(r'\d|percent|%|\bstud(?:y|ies)\b|\bresearch\b|\bapproved\b', plain, re.I) and not CITE.search(s): note.append(f'Claim with no [n]: "{s[:90]}"') if len(s.split()) > 35: note.append(f'Long sentence ({len(s.split())} words) is hard to follow out loud: "{s[:70]}…"') if re.search(r'https?://|www\.', text): fix.append('A web address is in the text; it would be read aloud. Put links in the sources.') if re.search(r'see (above|below)|click|\|', text, re.I): fix.append('"See above", "click" or a table does not work when heard.') if re.search(r'[≥≤/&]', CITE.sub('', text)): note.append('Symbols (≥, ≤, /, &) read badly aloud; use words.') seen = set() full = title + ' ' + desc + ' ' + text for m in ABBR.finditer(full): ab = m.group(1) if ab in COMMON or ab in seen: continue seen.add(ab) before = full[:m.start()] if not re.search(r'\(\s*' + ab + r'[\w-]*\s*\)', full[:m.end() + 6]) and ab not in before: note.append(f'"{ab}": spell it out the first time, e.g. "full name ({ab})".') low = full.lower() for phrase in rules['never_say']: for m in re.finditer(re.escape(phrase.lower()), low): if re.search(r"\b(not|no|never|isn't|aren't)\b(\s+\S+){0,3}\s*$", low[max(0, m.start() - 40):m.start()]): note.append(f'"{phrase}" appears in a negative ("not a {phrase}…"); fine, but check the tone.') else: fix.append(f'Uses "{phrase}", which your rules never allow.') break for phrase in rules['must_say']: if phrase.lower() not in low: fix.append(f'Missing "{phrase}", which your rules require.') notes = draft.get('review_notes') or [] if not notes: fix.append('Add review notes for the expert: topic origin, invented examples, claims to check hardest.') elif not any('not yet reviewed' in n.lower() or 'no review' in n.lower() for n in notes): note.append('Say in the review notes that it has not been reviewed yet.') return {'ready_for_review': not fix, 'words': words, 'sources': len(sources), 'fix': fix, 'notes': note} def selftest(): good = {'id': 'x', 'title': 'Rest stopped helping. Now what?', 'status': 'draft', 'description': 'When a long weekend no longer resets you, here is what to notice and what to ask.', 'sources': [{'title': 'Fact page', 'url': 'https://example.org/a'}, {'title': 'Guide', 'url': 'https://example.org/b'}], 'sections': [{'heading': f'Part {i}', 'paragraphs': ['Sleep that never feels restful is worth a conversation. [1]', 'Write down when it started and what makes it better or worse. [2]']} for i in range(5)], 'review_notes': ['Invented example in part 1.', 'Not yet reviewed by the clinician.']} r = check(good, {'words': [20, 750]}) assert r['ready_for_review'], r bad = json.loads(json.dumps(good)) bad['sections'][0]['paragraphs'].append('See https://example.org for the guaranteed fix [3].') bad['status'] = 'live' r = check(bad, {'words': [20, 750]}) for want in ('points to no source', 'web address', 'guaranteed', 'Status'): assert any(want in f for f in r['fix']), (want, r['fix']) unsourced = json.loads(json.dumps(good)) unsourced['sections'][1]['paragraphs'].append('About 40 percent of adults report this.') assert any('no [n]' in n for n in check(unsourced, {'words': [20, 750]})['notes']) print('selftest passed') if __name__ == '__main__': if sys.argv[1:] == ['selftest']: selftest() elif len(sys.argv) in (2, 3): result = check(json.load(open(sys.argv[1])), json.load(open(sys.argv[2])) if len(sys.argv) == 3 else None) print(json.dumps(result, indent=2, ensure_ascii=False)) sys.exit(0 if result['ready_for_review'] else 1) else: sys.exit(__doc__)