"""NLL V7.2 serialized engine source."""
# ===== SOURCE: runtime/cell3.py =====
#@title 3. Contracts, resources, disciplines, and document protection
from __future__ import annotations
import os,re,json,html,time,traceback,statistics
from pathlib import Path
import uuid
from dataclasses import dataclass,field,asdict
from collections import Counter
from difflib import SequenceMatcher
import numpy as np,pandas as pd,spacy
from nltk.corpus import wordnet as wn
from lemminflect import getInflection
DISCLAIMER="Observable style-pattern index only; not proof/probability of AI authorship and no detector-bypass guarantee."
CODES={"NO_PATTERN_COVERAGE","PARSE_FAILURE","CANDIDATE_GENERATION_FAILURE","REALIZATION_FAILURE","SEMANTIC_REJECTION","TERMINOLOGY_REJECTION","POLARITY_REJECTION","MODALITY_REJECTION","QUANTITY_REJECTION","ENUMERATION_REJECTION","GRAMMAR_REJECTION","RANKING_EMPTY","INSUFFICIENT_REWRITE","SUCCESS","NOT_TARGETED"}
@dataclass
class Config:
stanza:bool=False;sts:bool=True;nli:bool=True;mlm:bool=False;lt:bool=False;online:bool=False;batch:int=20;near_copy:float=.965;min_sts:float=.72;min_nli:float=.58;out:str="/content/nll_outputs";cache:str="/content/nll_cache"
@dataclass
class Profile:name:str;keywords:set[str];phrases:set[str];immutable:set[str]=field(default_factory=set);concepts:set[str]=field(default_factory=set)
@dataclass
class Prop:predicate:str;subject:str="";objects:list=field(default_factory=list);complements:list=field(default_factory=list);polarity:str="positive";modals:list=field(default_factory=list);voice:str="active"
@dataclass
class Analysis:text:str;families:list;props:list;relations:list;enumerations:list;protected:list;notes:list=field(default_factory=list);constituency:str|None=None
@dataclass
class Finding:category:str;passage:str;start:int;end:int;sentence:int;severity:float;explanation:str
@dataclass
class Candidate:text:str;lane:str;family:str;reason:str;priority:float=.5;checks:dict=field(default_factory=dict);score:float=-999
@dataclass
class SentenceResult:original:str;revised:str;status:str;families:list;family:str|None;reason:str;alternatives:list;validation:dict;diagnostics:dict
@dataclass
class DocumentResult:original:str;revised:str;workflow:str;mode:str;discipline:str;routing:list;pattern_score:float;band:str;findings:list;sentences:list;warnings:list;runtime:dict
CFG=Config();CFG.out='/tmp/nll_outputs';CFG.cache='/tmp/nll_cache';MODELS={};STATE={};Path(CFG.out).mkdir(parents=True,exist_ok=True);Path(CFG.cache).mkdir(parents=True,exist_ok=True)
def S(x):return {z.strip() for z in x.split("|") if z.strip()}
PROFILES={
"General Academic":Profile("General Academic",S("study|research|analysis|result|method|evidence|sample|finding"),S("this study|the findings")),
"Computing / Cybersecurity":Profile("Computing / Cybersecurity",S("algorithm|classifier|malware|adversarial|dataset|network|feature|robustness|encryption|cloud"),S("machine learning|feature space|problem space|threat model|static analysis"),S("XGBoost|Linear SVM|DNN|Windows PE|Android|APK|API"),S("adversarial robustness|perturbation constraint")),
"Engineering":Profile("Engineering",S("design|system|load|stress|material|control|circuit|failure|efficiency"),S("finite element|control system"),S("CAD|FEA|HVAC")),
"Medicine / Health":Profile("Medicine / Health",S("patient|clinical|treatment|diagnosis|disease|therapy|trial|cohort|outcome"),S("randomized controlled trial|adverse event"),S("DNA|RNA|MRI|CT|ICD")),
"Biology":Profile("Biology",S("cell|gene|protein|organism|species|genome|enzyme|tissue|mutation"),S("gene expression|cell signaling"),S("DNA|RNA|PCR")),
"Chemistry":Profile("Chemistry",S("compound|reaction|molecule|catalyst|solvent|synthesis|concentration|ion"),S("reaction rate|chemical equilibrium"),S("pH|NMR|HPLC")),
"Physics":Profile("Physics",S("energy|force|particle|field|wave|quantum|velocity|mass|gravity"),S("boundary condition|quantum state")),
"Mathematics / Statistics":Profile("Mathematics / Statistics",S("theorem|proof|equation|distribution|variance|regression|probability|estimator|matrix"),S("null hypothesis|confidence interval"),S("ANOVA|OLS|MSE")),
"Social Sciences":Profile("Social Sciences",S("society|community|policy|culture|institution|inequality|survey|interview|qualitative"),S("social context|thematic analysis")),
"Psychology":Profile("Psychology",S("behavior|cognition|emotion|participant|memory|attention|motivation|construct"),S("cognitive load|self efficacy"),S("DSM")),
"Education":Profile("Education",S("student|teacher|learning|curriculum|instruction|classroom|assessment|school"),S("learning outcome|instructional strategy")),
"Business / Economics":Profile("Business / Economics",S("market|firm|revenue|cost|consumer|economy|finance|investment|management"),S("return on investment|market share"),S("ROI|GDP")),
"Law / Policy":Profile("Law / Policy",S("law|legal|court|statute|regulation|policy|rights|liability|compliance"),S("case law|due process"),S("FAR|CFR")),
"Humanities":Profile("Humanities",S("text|narrative|history|philosophy|literature|discourse|interpretation|rhetoric"),S("historical context|critical theory")),
"Environmental Science":Profile("Environmental Science",S("climate|ecosystem|pollution|emission|biodiversity|habitat|sustainability|carbon"),S("climate change|greenhouse gas"),S("CO2|LCA"))}
def nlp():
if "spacy" not in MODELS:
try:MODELS["spacy"]=spacy.load("en_core_web_sm")
except Exception:MODELS["spacy"]=spacy.blank("en");MODELS["spacy"].add_pipe("sentencizer")
return MODELS["spacy"]
def optional(kind):
if kind=="sts" and CFG.sts:
try:
if kind not in MODELS:
from sentence_transformers import SentenceTransformer
MODELS[kind]=SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
except Exception as e:STATE["warnings"].append(f"STS unavailable: {e}");MODELS[kind]=None
if kind=="nli" and CFG.nli:
try:
if kind not in MODELS:
from transformers import AutoTokenizer,AutoModelForSequenceClassification
mid="cross-encoder/nli-deberta-v3-small";m=AutoModelForSequenceClassification.from_pretrained(mid);m.eval();MODELS[kind]=(AutoTokenizer.from_pretrained(mid),m)
except Exception as e:STATE["warnings"].append(f"NLI unavailable: {e}");MODELS[kind]=None
if kind=="mlm" and CFG.mlm:
try:
if kind not in MODELS:
import torch
from transformers import pipeline
MODELS[kind]=pipeline("fill-mask",model="distilroberta-base",device=0 if torch.cuda.is_available() else -1)
except Exception as e:STATE["warnings"].append(f"MLM unavailable: {e}");MODELS[kind]=None
if kind=="lt" and CFG.lt:
try:
if kind not in MODELS:
import language_tool_python
MODELS[kind]=language_tool_python.LanguageTool("en-US")
except Exception as e:STATE["warnings"].append(f"LanguageTool unavailable: {e}");MODELS[kind]=None
return MODELS.get(kind)
PATS={
"citation":re.compile(r"\([^()\n]{0,90}(?:19|20)\d{2}[a-z]?[^()\n]{0,50}\)|\[[0-9,;\-\s]+\]|[A-Z][A-Za-z'\-]+ et al\. \((?:19|20)\d{2}[a-z]?\)"),
"url":re.compile(r"https?://\S+|doi:\s*\S+|10\.\d{4,9}/\S+",re.I),
"equation":re.compile(r"\$[^$]+\$"),
"code":re.compile(r"`[^`]+`|```[\s\S]+?```"),
"quantity":re.compile(r"(?≈~±]?\s*\d+(?:\.\d+)?(?:\s*[-–]\s*\d+(?:\.\d+)?)?\s*(?:%|mg|kg|mL|mm|cm|km|Hz|GHz|°C|MPa|kW|days?|years?)?\b",re.I)
}
def protect(text,terms):
out=[]
for k,p in PATS.items():out += [(k,m.group(),m.start(),m.end()) for m in p.finditer(text)]
for t in terms:out += [("term",m.group(),m.start(),m.end()) for m in re.finditer(r"(?=3 and t.i not in seen:enums.append([sub(x) for x in xs]);seen|={x.i for x in xs}
const=None
if CFG.stanza:
try:
if "stanza" not in MODELS:
import stanza
MODELS["stanza"]=stanza.Pipeline("en",processors="tokenize,pos,lemma,depparse,constituency",use_gpu=False,verbose=False)
const=str(MODELS["stanza"](s).sentences[0].constituency)
except Exception as e:STATE["warnings"].append(f"Stanza unavailable: {e}")
return Analysis(s,sorted(fam),props,rels,enums,protect(s,terms),[],const)
FORMULAIC=[r"it is important to note that",r"in today's rapidly evolving",r"delve(?:s|d)? into",r"multifaceted",r"pivotal role",r"seamlessly",r"in conclusion",r"furthermore",r"moreover",r"this highlights"]
class Scanner:
def scan(self,text):
ss=sent_split(text);fs=[];off=0;lens=[];starts=[]
for i,s in enumerate(ss):
st=max(off,text.find(s,off));off=st+len(s);d=nlp()(s);w=[t for t in d if t.is_alpha];lens.append(len(w));starts.append(" ".join(t.lemma_.lower() for t in w[:3]))
for p in FORMULAIC:
for z in re.finditer(p,s,re.I):fs.append(Finding("formulaic wording",z.group(),st+z.start(),st+z.end(),i,.65,"Formulaic academic wording; context may still justify it."))
if len(w)>38:fs.append(Finding("sentence complexity",s,st,st+len(s),i,.6,"Long multi-clause sentence may be dense."))
rep={x for x,n in Counter(starts).items() if x and n>=3}
for i,(s,o) in enumerate(zip(ss,starts)):
if o in rep:fs.append(Finding("repetitive opening",s[:80],text.find(s),text.find(s)+min(80,len(s)),i,.55,"Repeated sentence opening."))
mean=statistics.mean(lens) if lens else 0;cv=statistics.pstdev(lens)/mean if len(lens)>1 and mean else 0;score=min(100,len(fs)*7+max(0,.28-cv)*40);return fs,float(score),"Low" if score<30 else "Moderate" if score<60 else "High",{"sentence_length_cv":cv,"findings":len(fs)}
# ===== SOURCE: runtime/cell4b.py =====
#@title 4B. Universal academic pattern taxonomy and naturalness analyzer
from dataclasses import dataclass, field
from collections import Counter
import re
# ============================================================
# 1. TAXONOMY
# ============================================================
PATTERN_TAXONOMY = {
"VOICE": {
"PASSIVE", "AGENTLESS_PASSIVE", "AGENTIVE_PASSIVE",
"MODAL_PASSIVE", "STACKED_PASSIVE",
"PASSIVE_EVALUATION_CONTEXT", "PASSIVE_PROCESS_CONTEXT",
"NEGATED_CLASSIFICATION_PASSIVE",
"COORDINATED_PASSIVE_PREDICATES", "PASSIVE_BASIS_FRAME",
},
"CLAUSE_STRUCTURE": {
"WHEREBY_CLAUSE", "SO_THAT_CLAUSE", "PURPOSE_RESULT_CLAUSE",
"FINITE_WHILE_CLAUSE", "WHILE_PARTICIPIAL",
"PARTICIPIAL_RESULT_CLAUSE", "WHEN_CLAUSE", "WHEREAS_CLAUSE",
"ALTHOUGH_CLAUSE", "BECAUSE_CLAUSE", "IF_CLAUSE",
"CONTENT_COMPLEMENT", "RELATIVE_CLAUSE",
"MULTI_EMBEDDED_CLAUSES", "CONTRASTIVE_COORDINATED_CLAUSES",
"SEMICOLON_NEGATED_ASSUMPTION",
},
"NOMINALIZATION": {
"GERUND_SUBJECT", "NOMINALIZATION", "ABSTRACT_NOUN_STACK",
"NOUN_HEAVY_PREDICATE", "NOMINALIZED_PROCESS",
"NOMINALIZED_EVALUATION",
},
"CONTRAST": {
"CONTRAST", "NEGATED_PURPOSE_CONTRAST", "NOT_X_BUT_Y",
"RATHER_THAN_CONTRAST", "HOWEVER_CONTRAST", "WHEREAS_CONTRAST",
"CONTRASTIVE_COORDINATED_CLAUSES",
"SEMICOLON_NEGATED_ASSUMPTION",
},
"REPORTING_EVIDENCE": {
"REPORTING_FRAME", "EVIDENTIAL_COMPLEMENT", "ATTRIBUTION_FRAME",
"RESULT_REPORTING_FRAME", "INDEPENDENT_REPORTING",
},
"EVALUATION_METHOD": {
"EVALUATION_FRAME", "PASSIVE_EVALUATION_CONTEXT",
"PASSIVE_PROCESS_CONTEXT", "PASSIVE_BASIS_FRAME",
"METHOD_RELATION", "COMPARATIVE_FRAME", "METHOD_APPLICATION_FRAME",
"EVALUATION_CONDITION_FRAME",
},
"COORDINATION": {
"COORDINATED_PREDICATES", "COORDINATED_OBJECTS_OR_ENUMERATION",
"COORDINATED_PROPOSITIONS", "LONG_ENUMERATION",
"PARALLEL_ENUMERATION", "COORDINATED_PASSIVE_PREDICATES",
"CONTRASTIVE_COORDINATED_CLAUSES",
},
"DISCOURSE": {
"DISCOURSE_MARKER", "CONSEQUENCE", "RESULT_CLAUSE",
"REPETITIVE_TRANSITION", "FORMULAIC_TRANSITION",
"OVEREXPLICIT_LOGIC", "SEMICOLON_NEGATED_ASSUMPTION",
},
"COMPLEXITY": {
"LONG_SENTENCE", "VERY_LONG_SENTENCE", "MULTI_EMBEDDED_CLAUSES",
"CLAUSE_OVERLOADING", "LONG_PREPOSITIONAL_CHAIN",
"HEAVY_POSTMODIFICATION", "EXCESSIVE_COORDINATION",
},
"FORMULAIC_ACADEMIC": {
"FORMULAIC_PURPOSE", "FORMULAIC_RESULT", "FORMULAIC_COMPARISON",
"FORMULAIC_EVALUATION", "FORMULAIC_METHOD",
"FORMULAIC_CONCLUSION", "FORMULAIC_TRANSITION",
"OVEREXPLICIT_LOGIC", "REPETITIVE_SENTENCE_FRAME",
},
"NATURALNESS": {
"AWKWARD_PASSIVE", "UNNATURAL_NOMINALIZATION",
"EXCESSIVE_SYMMETRY", "CLAUSE_OVERLOADING", "REPETITIVE_SYNTAX",
"REDUNDANT_EXPLICITNESS", "STILTED_CONNECTIVE",
"HEAVY_NOUN_PHRASE", "ABSTRACT_NOUN_STACK",
"MECHANICAL_PARALLELISM",
},
}
# ============================================================
# 2. RESULT OBJECT
# ============================================================
@dataclass
class PatternProfile:
grammar_families: set = field(default_factory=set)
formulaic_flags: set = field(default_factory=set)
naturalness_flags: set = field(default_factory=set)
complexity_flags: set = field(default_factory=set)
discourse_flags: set = field(default_factory=set)
metrics: dict = field(default_factory=dict)
evidence: dict = field(default_factory=dict)
# ============================================================
# 3. HELPERS
# ============================================================
def _pt_clean(text):
return re.sub(r"\s+", " ", str(text or "")).strip()
def _pt_words(text):
return re.findall(r"\b[\w'-]+\b", str(text or ""))
def _add_evidence(profile, flag, evidence):
profile.evidence.setdefault(flag, [])
if evidence not in profile.evidence[flag]:
profile.evidence[flag].append(evidence)
def _detect_content_complement(lower_text):
if re.search(r"\bwhether\b", lower_text):
return True
determiner = re.search(
r"\bthat\s+(?:type|kind|form|method|model|approach|system|procedure|"
r"framework|process|design|strategy|technique|case|example|result|"
r"study|analysis|experiment|feature|representation|classifier|"
r"algorithm|dataset|environment|platform|component|domain|alignment|"
r"space|constraint|condition|measure|attack|sample|architecture|"
r"methodology)\b",
lower_text,
)
if determiner:
return False
governor = re.search(
r"\b(?:show|shows|showed|indicate|indicates|indicated|suggest|"
r"suggests|suggested|demonstrate|demonstrates|demonstrated|report|"
r"reports|reported|find|finds|found|observe|observes|observed|confirm|"
r"confirms|confirmed|conclude|concludes|concluded|establish|"
r"establishes|established|assume|assumes|assumed|ensure|ensures|"
r"ensured|mean|means|meant|reveal|reveals|revealed|evidence|finding|"
r"findings|result|results)\s+that\b",
lower_text,
)
if governor:
return True
clause = re.search(
r"\bthat\s+(?:the|a|an|this|these|those|it|they|we|researchers|"
r"participants|results|findings|evidence|data|models?|systems?|"
r"methods?|samples?|features?)\s+(?:is|are|was|were|has|have|had|"
r"can|could|may|might|must|should|will|would|does|do|did|"
r"[A-Za-z][A-Za-z-]*(?:s|ed))\b",
lower_text,
)
return bool(clause)
# ============================================================
# 4. GRAMMAR-FAMILY DETECTOR
# ============================================================
def detect_grammar_families(text):
text = _pt_clean(text)
lower_text = text.lower()
families = set()
if re.search(r"\bwhereby\b", lower_text):
families.add("WHEREBY_CLAUSE")
if re.search(r"\bso\s+that\b", lower_text):
families.update({"SO_THAT_CLAUSE", "PURPOSE_RESULT_CLAUSE"})
if re.search(
r"\bwhile\s+(?:the\s+)?[A-Za-z][A-Za-z0-9_/-]*"
r"(?:\s+[A-Za-z][A-Za-z0-9_/-]*){0,5}\s+"
r"(?:is|are|was|were|has|have|had|does|do|did|tracks?|measures?|"
r"shows?|indicates?|preserves?|provides?|uses?|evaluates?|compares?|"
r"examines?|remains?|increases?|decreases?|continues?|represents?|"
r"performs?|captures?|retains?|allows?|enables?)\b",
lower_text,
):
families.add("FINITE_WHILE_CLAUSE")
if re.search(r"\bwhile\s+[A-Za-z][A-Za-z-]*ing\b", lower_text):
families.add("WHILE_PARTICIPIAL")
if re.search(r",\s*(?:allowing|enabling|permitting)\b", lower_text):
families.add("PARTICIPIAL_RESULT_CLAUSE")
for family, pattern in {
"WHEN_CLAUSE": r"\bwhen\b",
"WHEREAS_CLAUSE": r"\bwhereas\b",
"ALTHOUGH_CLAUSE": r"\balthough\b",
"BECAUSE_CLAUSE": r"\bbecause\b",
"IF_CLAUSE": r"\bif\b",
}.items():
if re.search(pattern, lower_text):
families.add(family)
if _detect_content_complement(lower_text):
families.add("CONTENT_COMPLEMENT")
if re.search(r"\bnot\b.+?\bbut\b", lower_text, re.S):
families.add("CONTRAST")
if re.search(
r"\b(?:purpose|aim|objective|goal)\b.+?\bis\s+not\s+to\b.+?\bbut\s+to\b",
lower_text,
re.S,
):
families.add("NEGATED_PURPOSE_CONTRAST")
if re.match(r"^[A-Za-z][A-Za-z-]*ing\b", text, re.I):
families.add("GERUND_SUBJECT")
if re.search(
r"\b(?:is|are|was|were|has been|have been|had been)\s+(?:not\s+)?"
r"(?:\w+\s+){0,2}\w+(?:ed|en)\b",
lower_text,
):
families.add("PASSIVE")
if re.search(r"\b(?:can|could|may|might|must|should)\s+be\s+\w+(?:ed|en)\b", lower_text):
families.add("MODAL_PASSIVE")
if re.search(
r"\b(?:is|are|was|were|has been|have been)\s+evaluated\s+"
r"(?:at|across|under|within|on|by|with|using)\b",
lower_text,
):
families.add("PASSIVE_EVALUATION_CONTEXT")
if re.search(
r"\b(?:is|are|was|were|has been|have been|had been)\s+"
r"[A-Za-z][A-Za-z-]*(?:ed|en)(?:\s+(?:independently|separately|"
r"jointly|simultaneously|iteratively|individually|concurrently))?\s+"
r"(?:on|in|within|under|across|using|with|from|for)\b",
lower_text,
):
families.add("PASSIVE_PROCESS_CONTEXT")
if re.search(
r"\b(?:is|are|was|were|has been|have been|had been)\s+not\s+"
r"(?:treated|regarded|interpreted|classified|considered)\s+as\b",
lower_text,
):
families.add("NEGATED_CLASSIFICATION_PASSIVE")
# NEW: coordinated passive predicates.
if re.search(
r"\b(?:is|are|was|were|has been|have been|had been)\s+"
r"[A-Za-z][A-Za-z-]*(?:ed|en)\s+(?:and|or)\s+"
r"[A-Za-z][A-Za-z-]*(?:ed|en)"
r"(?:\s+(?:independently|separately|jointly|simultaneously|individually))?\b",
lower_text,
):
families.add("COORDINATED_PASSIVE_PREDICATES")
# NEW: contrastive coordinated clauses.
if re.search(r",\s*(?:but|whereas|while)\s+.+", lower_text, re.S):
families.update({"CONTRASTIVE_COORDINATED_CLAUSES", "CONTRAST"})
# NEW: passive basis frame.
if re.search(
r"\b(?:is|are|was|were|has been|have been)\s+based\s+on\s+",
lower_text,
):
families.update({"PASSIVE_BASIS_FRAME", "PASSIVE"})
# NEW: semicolon followed by a negated assumption/implication clause.
if re.search(
r";\s*(?:it|this|that|the\s+[A-Za-z][A-Za-z-]*)\s+"
r"(?:does|do|did)\s+not\s+"
r"(?:assume|imply|indicate|mean|require|establish|demonstrate|suggest)\s+that\b",
lower_text,
):
families.update({"SEMICOLON_NEGATED_ASSUMPTION", "CONTRAST"})
if re.search(
r"\b(?:is|are|was|were|has been|have been)\s+"
r"(?:commonly|frequently|generally|typically|often|usually)\s+"
r"evaluated\s+(?:using|with)\b",
lower_text,
):
families.add("EVALUATION_FRAME")
if re.search(
r"\b(?:results|findings|outcomes|observations)\s+reported\s+"
r"(?:independently|separately)\b",
lower_text,
):
families.add("REPORTING_FRAME")
if re.search(r"\bthrough\b", lower_text):
families.add("METHOD_RELATION")
if re.search(r"\b(?:intended|designed)\s+to\b", lower_text):
families.add("PURPOSE_INFINITIVE")
if re.search(
r"\bbasis\s+for\s+(?:determining|evaluating|assessing|comparing)\b",
lower_text,
):
families.add("PURPOSE_RESULT_CLAUSE")
if re.match(
r"(?i)^(?:however|therefore|consequently|thus|accordingly|"
r"nevertheless|nonetheless|in contrast|by contrast|as a result)\b",
text,
):
families.add("DISCOURSE_MARKER")
if re.match(r"(?i)^(?:therefore|consequently|thus|accordingly|as a result)\b", text):
families.update({"CONSEQUENCE", "RESULT_CLAUSE"})
return families
# ============================================================
# 5. FORMULAIC-STYLE DETECTOR
# ============================================================
FORMULAIC_PATTERNS = {
"FORMULAIC_PURPOSE": [
r"\bthe purpose (?:of this|is to)\b",
r"\bthe aim (?:of this|is to)\b",
r"\bthe objective (?:of this|is to)\b",
],
"FORMULAIC_RESULT": [
r"\bas a result\b", r"\bconsequently\b", r"\btherefore\b",
r"\bthis suggests that\b", r"\bthese results indicate that\b",
],
"FORMULAIC_COMPARISON": [
r"\bin contrast\b", r"\bby contrast\b", r"\bcompared with\b", r"\bcompared to\b",
],
"FORMULAIC_EVALUATION": [
r"\bis evaluated using\b", r"\bare evaluated using\b",
r"\bis evaluated across\b", r"\bare evaluated across\b",
r"\bis assessed using\b", r"\bare assessed using\b",
],
"FORMULAIC_METHOD": [
r"\busing this approach\b", r"\bunder this framework\b",
r"\bwithin this framework\b", r"\bthe methodology allows\b",
],
"FORMULAIC_CONCLUSION": [
r"\btaken together\b", r"\boverall, these\b", r"\bcollectively, these\b",
],
"OVEREXPLICIT_LOGIC": [
r"\bthis means that\b", r"\bthis indicates that\b",
r"\bthis demonstrates that\b", r"\bit is important to note that\b",
r"\bit should be noted that\b",
],
"STILTED_CONNECTIVE": [
r"\bfurthermore\b", r"\bmoreover\b", r"\bnevertheless\b", r"\baccordingly\b",
],
}
def detect_formulaic_patterns(text, profile):
lower_text = _pt_clean(text).lower()
for flag, patterns in FORMULAIC_PATTERNS.items():
for pattern in patterns:
match = re.search(pattern, lower_text, re.I)
if match:
profile.formulaic_flags.add(flag)
_add_evidence(profile, flag, match.group(0))
# ============================================================
# 6. NATURALNESS / COMPLEXITY DETECTOR
# ============================================================
def detect_naturalness(text, profile):
text = _pt_clean(text)
words = _pt_words(text)
word_count = len(words)
profile.metrics["word_count"] = word_count
if word_count >= 35:
profile.complexity_flags.add("LONG_SENTENCE")
if word_count >= 50:
profile.complexity_flags.add("VERY_LONG_SENTENCE")
clause_markers = re.findall(
r"\b(?:that|which|whereby|whereas|although|because|while|when|whether|if|so that)\b",
text,
re.I,
)
profile.metrics["clause_marker_count"] = len(clause_markers)
if len(clause_markers) >= 3:
profile.complexity_flags.add("MULTI_EMBEDDED_CLAUSES")
if word_count >= 35 and len(clause_markers) >= 2:
profile.naturalness_flags.add("CLAUSE_OVERLOADING")
prepositions = re.findall(
r"\b(?:of|in|within|under|across|among|through|between|for|from|with|by|on|at)\b",
text,
re.I,
)
profile.metrics["preposition_count"] = len(prepositions)
if len(prepositions) >= 6 and word_count >= 25:
profile.complexity_flags.add("LONG_PREPOSITIONAL_CHAIN")
passive_hits = re.findall(
r"\b(?:is|are|was|were|has been|have been|had been)\s+(?:not\s+)?"
r"(?:\w+\s+){0,2}\w+(?:ed|en)\b",
text,
re.I,
)
profile.metrics["passive_count"] = len(passive_hits)
if len(passive_hits) >= 2:
profile.naturalness_flags.add("AWKWARD_PASSIVE")
transitions = re.findall(
r"\b(?:however|therefore|consequently|thus|moreover|furthermore|"
r"accordingly|nevertheless|nonetheless)\b",
text,
re.I,
)
profile.metrics["transition_count"] = len(transitions)
if len(transitions) >= 2:
profile.discourse_flags.add("REPETITIVE_TRANSITION")
nominalizations = re.findall(
r"\b[A-Za-z]+(?:tion|sion|ment|ance|ence|ity|ness)\b",
text,
re.I,
)
profile.metrics["nominalization_count"] = len(nominalizations)
if len(nominalizations) >= 4 and word_count >= 25:
profile.naturalness_flags.add("UNNATURAL_NOMINALIZATION")
and_count = len(re.findall(r"\band\b", text, re.I))
profile.metrics["and_count"] = and_count
if and_count >= 4 and word_count >= 30:
profile.naturalness_flags.add("MECHANICAL_PARALLELISM")
# ============================================================
# 7. MAIN ANALYZER / REPORT
# ============================================================
def analyze_pattern_taxonomy(text):
profile = PatternProfile()
profile.grammar_families.update(detect_grammar_families(text))
detect_formulaic_patterns(text, profile)
detect_naturalness(text, profile)
return profile
def taxonomy_categories(flag):
return [category for category, members in PATTERN_TAXONOMY.items() if flag in members]
def pattern_report(text):
profile = analyze_pattern_taxonomy(text)
return {
"grammar_families": sorted(profile.grammar_families),
"formulaic_flags": sorted(profile.formulaic_flags),
"naturalness_flags": sorted(profile.naturalness_flags),
"complexity_flags": sorted(profile.complexity_flags),
"discourse_flags": sorted(profile.discourse_flags),
"metrics": dict(profile.metrics),
"evidence": dict(profile.evidence),
}
# ============================================================
# 8. SELF-TESTS
# ============================================================
_PATTERN_TESTS = {
"while_participial": "The comparison preserves the constraints while applying the methodology.",
"while_finite": "Accuracy measures overall performance, while recall tracks missed examples.",
"whereby": "The design uses a common procedure whereby each model is evaluated so that comparisons remain consistent.",
"evaluation_context": "The models are evaluated across several conditions.",
"negated_purpose": "The purpose is not to rank the methods but to compare their behavior.",
"passive_process": "The models are trained independently on their respective feature representations.",
"negated_classification": "The representations are not treated as evidence of invariant features.",
"participial_result": "The models operate in separate environments, allowing their effects to be evaluated.",
"that_determiner": "The study does not implement that type of domain alignment.",
"that_content_complement": "The results indicate that the models preserve their original behavior.",
"coordinated_passive": "The models are trained and evaluated separately.",
"contrastive_coordination": "The models are trained separately, but both environments use the same procedure.",
"passive_basis": "The interpretation is based on changes in the measured outcomes.",
"semicolon_negated_assumption": "The comparison uses separate measurements; it does not assume that the representations are equivalent.",
}
_PATTERN_RESULTS = {name: pattern_report(sentence) for name, sentence in _PATTERN_TESTS.items()}
def _assert_pattern(test_name, expected_family):
detected = _PATTERN_RESULTS[test_name]["grammar_families"]
if expected_family not in detected:
raise RuntimeError(
f"Pattern taxonomy failed {expected_family} self-test for '{test_name}'. Detected: {detected}"
)
for test_name, expected in [
("while_participial", "WHILE_PARTICIPIAL"),
("while_finite", "FINITE_WHILE_CLAUSE"),
("whereby", "WHEREBY_CLAUSE"),
("evaluation_context", "PASSIVE_EVALUATION_CONTEXT"),
("negated_purpose", "NEGATED_PURPOSE_CONTRAST"),
("passive_process", "PASSIVE_PROCESS_CONTEXT"),
("negated_classification", "NEGATED_CLASSIFICATION_PASSIVE"),
("participial_result", "PARTICIPIAL_RESULT_CLAUSE"),
("that_content_complement", "CONTENT_COMPLEMENT"),
("coordinated_passive", "COORDINATED_PASSIVE_PREDICATES"),
("contrastive_coordination", "CONTRASTIVE_COORDINATED_CLAUSES"),
("passive_basis", "PASSIVE_BASIS_FRAME"),
("semicolon_negated_assumption", "SEMICOLON_NEGATED_ASSUMPTION"),
]:
_assert_pattern(test_name, expected)
if "CONTENT_COMPLEMENT" in _PATTERN_RESULTS["that_determiner"]["grammar_families"]:
raise RuntimeError("Pattern taxonomy incorrectly classified determiner 'that' as CONTENT_COMPLEMENT.")
# ============================================================
# 9. STATUS
# ============================================================
print("=" * 72)
print("CELL 4B PATTERN TAXONOMY SUCCESSFULLY LOADED")
print("=" * 72)
print("Grammar-family taxonomy: active")
print("Formulaic-expression analysis: active")
print("Naturalness analysis: active")
print("Complexity analysis: active")
print("Discourse analysis: active")
print("\nVerified grammar routes:")
for family in [
"FINITE_WHILE_CLAUSE", "WHILE_PARTICIPIAL", "WHEREBY_CLAUSE",
"PASSIVE_EVALUATION_CONTEXT", "PASSIVE_PROCESS_CONTEXT",
"NEGATED_CLASSIFICATION_PASSIVE", "PARTICIPIAL_RESULT_CLAUSE",
"NEGATED_PURPOSE_CONTRAST", "CONTENT_COMPLEMENT",
"COORDINATED_PASSIVE_PREDICATES", "CONTRASTIVE_COORDINATED_CLAUSES",
"PASSIVE_BASIS_FRAME", "SEMICOLON_NEGATED_ASSUMPTION",
]:
print(f" [OK] {family}")
print(" [OK] determiner 'that' exclusion")
print("\nCell 4B is ready. Update and run Cell 5 next.")
# ===== SOURCE: runtime/cell5.py =====
#@title 5. STANDALONE UNIVERSAL TRANSFORMATION ENGINE v4.1 — 30 deterministic rules
# Complete standalone replacement for Cell 5.
# Requires earlier notebook cells to define Candidate, CFG, Analyzer, nlp,
# optional, wn, and getInflection. This cell defines the rule registry,
# all 25 base rules, the Generator, and the v4.1 primary-clause upgrade.
from dataclasses import dataclass
from typing import Callable
from collections import Counter
import re
_REQUIRED_CELL5 = ["Candidate", "CFG", "Analyzer", "nlp"]
_missing_cell5 = [name for name in _REQUIRED_CELL5 if name not in globals()]
if _missing_cell5:
raise RuntimeError(
"Standalone Cell 5 cannot run. Missing: "
+ ", ".join(_missing_cell5)
+ ". Run Cells 1–4/4B first."
)
@dataclass
class Rule:
name: str
lanes: set
families: set
priority: float
fn: Callable
RULES = []
def rule(name, lanes, families, priority=.5):
"""Register or replace one deterministic transformation rule."""
def deco(fn):
global RULES
RULES = [registered for registered in RULES if registered.name != name]
RULES.append(
Rule(
str(name),
set(lanes),
set(families),
float(priority),
fn,
)
)
return fn
return deco
def clean(text):
value = re.sub(
r"\s+([,.;:!?])",
r"\1",
re.sub(r"\s+", " ", str(text or "")),
).strip()
if value:
value = value[0].upper() + value[1:]
return value if not value or value[-1] in ".!?" else value + "."
def bare(text):
return re.sub(r"[.?!]+$", "", clean(text)).strip()
def lower_initial(text):
value = str(text or "").strip()
if not value or re.match(r"^[A-Z]{2,}\b", value):
return value
return value[:1].lower() + value[1:]
def surface_key(text):
return re.sub(r"\W+", " ", str(text or "").lower()).strip()
_surface_key = surface_key
def K(text, lane, family, reason, priority=.5):
return Candidate(
clean(text),
lane,
family,
reason,
float(priority),
)
def emit(text, lane, family, reason, priority=.5):
value = clean(text)
return [] if not value else [K(value, lane, family, reason, priority)]
def _safe_subtree_text(token):
"""Return a token subtree without requiring a separate helper cell."""
try:
items = list(token.subtree)
if not items:
return token.text
start = min(item.i for item in items)
end = max(item.i for item in items) + 1
return token.doc[start:end].text
except Exception:
return getattr(token, "text", "")
# =====================================================================
# BASE RULES 1–25
# =====================================================================
@rule("copular_action_frame", {"Balanced", "Structural"}, {"COPULAR_ACTION_FRAME"}, .92)
def tr_copular_action(analysis, profile, user_terms):
match = re.match(
r"(?is)^The\s+(?P
next|first|second|third|final|primary|main)\s+"
r"(?Pstep|task|action|objective|goal)\s+is\s+to\s+"
r"(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
return [
K(
f"The {match['head']} {match['noun']} involves {match['action']}",
"Balanced",
"COPULAR_ACTION_FRAME",
"Converted a copular action frame into an event frame.",
.92,
)
]
@rule("need_to_action", {"Balanced", "Structural"}, {"NEED_TO_ACTION"}, .88)
def tr_need_to(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+(?Pneed|needs|needed)\s+to\s+"
r"(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
modal = "had to" if match["need"].lower() == "needed" else "must"
return [
K(
f"{match['subject']} {modal} {match['action']}",
"Balanced",
"NEED_TO_ACTION",
"Recast a need-to construction while retaining its subject and action.",
.88,
)
]
@rule(
"finite_intent_rather_than",
{"Balanced", "Structural"},
{"FINITE_PURPOSE_INTENT", "RATHER_THAN_GERUND"},
.90,
)
def tr_finite_intent(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+"
r"(?Pintend|intends|intended)\s+to\s+"
r"(?P.+?)\s+rather\s+than\s+"
r"(?P\w+ing\b.+?)[.]?$",
analysis.text,
)
if not match:
return []
return [
K(
f"Rather than {match['alternative']}, {lower_initial(match['subject'])} "
f"{match['intent']} to {match['action']}",
"Balanced",
"FINITE_PURPOSE_INTENT",
"Fronted the rejected alternative while preserving the stated intent.",
.90,
)
]
@rule(
"modal_copular_enumeration",
{"Balanced", "Structural"},
{"MODAL_COPULAR_ENUMERATION", "COORDINATED_OBJECTS_OR_ENUMERATION", "ENUMERATION"},
.91,
)
def tr_modal_enumeration(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+"
r"(?Pmay|might|could|can)\s+be\s+in\s+"
r"(?P.+?,\s*.+?\s*,?\s*(?:or|and)\s+.+?)[.]?$",
analysis.text,
)
if not match:
return []
return [
K(
f"Possible sources of {lower_initial(match['subject'])} "
f"{match['modal'].lower()} include {match['items']}",
"Balanced",
"MODAL_COPULAR_ENUMERATION",
"Recast a modal copular list while preserving uncertainty and every member.",
.91,
)
]
@rule(
"enumeration_frame",
{"Minimal", "Balanced"},
{"COORDINATED_OBJECTS_OR_ENUMERATION", "ENUMERATION"},
.65,
)
def tr_enumeration_frame(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+(?:consists?\s+of|comprises?)\s+"
r"(?P.+?,.+?(?:and|or).+?)[.]?$",
analysis.text,
)
if not match:
return []
return emit(
f"{match['subject']} includes {match['items']}",
"Minimal",
"ENUMERATION",
"Varied an explicit enumeration frame without changing its members.",
.65,
)
@rule(
"using_method_relation",
{"Balanced", "Structural"},
{"USING_METHOD_RELATION", "METHOD_RELATION"},
.89,
)
def tr_using_method(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+using\s+(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
return [
K(
f"Using {match['method']}, {lower_initial(match['main'])}",
"Balanced",
"USING_METHOD_RELATION",
"Fronted the explicitly stated method relation.",
.89,
)
]
@rule(
"through_method_relation",
{"Balanced", "Structural"},
{"THROUGH_METHOD_RELATION", "METHOD_RELATION"},
.86,
)
def tr_through_method(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+through\s+(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
return emit(
f"Through {match['method']}, {lower_initial(match['main'])}",
"Balanced",
"THROUGH_METHOD_RELATION",
"Fronted an explicitly stated through-method relation.",
.86,
)
@rule(
"by_gerund_method",
{"Balanced", "Structural"},
{"BY_GERUND_METHOD_RELATION", "METHOD_RELATION"},
.84,
)
def tr_by_gerund(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+by\s+(?P\w+ing\b.+?)[.]?$",
analysis.text,
)
if not match:
return []
return emit(
f"By {match['method']}, {lower_initial(match['main'])}",
"Balanced",
"BY_GERUND_METHOD_RELATION",
"Fronted an explicitly stated by-gerund method relation.",
.84,
)
@rule(
"purpose_infinitive_relocation",
{"Balanced", "Structural"},
{"PURPOSE_INFINITIVE_FRONTING"},
.88,
)
def tr_purpose_front(analysis, profile, user_terms):
match = re.match(
r"(?is)^To\s+(?P[^,]{2,160}),\s*(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
return emit(
f"{match['main']} to {match['purpose']}",
"Balanced",
"PURPOSE_INFINITIVE_FRONTING",
"Moved the explicit purpose clause after the main proposition.",
.88,
)
@rule(
"purpose_contrast",
{"Balanced", "Structural"},
{"NEGATED_PURPOSE_CONTRAST"},
.98,
)
def tr_purpose(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.*?\b(?:purpose|aim|objective|goal)\b.*?)\s+"
r"is\s+not\s+to\s+(?P.+?)\s+but\s+to\s+(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
return [
K(
f"{match['head']} is to {match['y']} rather than to {match['x']}",
"Balanced",
"NEGATED_PURPOSE_CONTRAST",
"Reordered contrasted objectives while preserving both scopes.",
.98,
),
K(
f"{match['head']} does not seek to {match['x']}. "
f"Instead, it aims to {match['y']}",
"Structural",
"NEGATED_PURPOSE_CONTRAST",
"Separated the excluded and intended objectives.",
.90,
),
]
@rule(
"evidential_complement",
{"Balanced", "Structural"},
{"EVIDENTIAL_COMPLEMENT"},
.94,
)
def tr_evidence(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+"
r"(?:provide|provides|provided|offer|offers|offered)\s+"
r"(?:clear\s+|strong\s+|empirical\s+)?evidence\s+that\s+"
r"(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
return [
K(
f"Evidence from {lower_initial(match['src'])} indicates that {match['claim']}",
"Balanced",
"EVIDENTIAL_COMPLEMENT",
"Recast the evidential frame while preserving the claim.",
.94,
),
K(
f"According to the evidence provided by {lower_initial(match['src'])}, "
f"{match['claim']}",
"Structural",
"EVIDENTIAL_COMPLEMENT",
"Reorganized the source and claim around the same evidential relation.",
.76,
),
]
@rule("whether_complement", {"Balanced", "Structural"}, {"WHETHER_COMPLEMENT"}, .89)
def tr_whether(analysis, profile, user_terms):
match = re.match(
r"(?is)^(?P.+?)\s+require(?:s|d)?\s+"
r"(?:an?\s+)?(?:consideration|assessment|evaluation|analysis)\s+"
r"of\s+whether\s+(?P.+?)[.]?$",
analysis.text,
)
if not match:
return []
subject = re.sub(r"\balso\b", "", match["subject"], flags=re.I).strip()
return emit(
f"Assessing whether {match['clause']} is also required when considering "
f"{lower_initial(subject)}",
"Balanced",
"WHETHER_COMPLEMENT",
"Converted a nominalized whether-complement into an assessment clause.",
.89,
)
@rule("gerund_subject", {"Balanced", "Structural"}, {"GERUND_SUBJECT"}, .88)
def tr_gerund(analysis, profile, user_terms):
source = bare(analysis.text)
match = re.match(
r"(?is)^(?PApplying|Using|Evaluating|Comparing|Assessing|Examining|"
r"Analyzing|Implementing|Testing|Measuring)\s+(?P