creegon's picture
Release 0.1.0 (same files as staging-0.1.0 @ 90a07ac4)
7b0b7bc verified
Raw History Blame Contribute Delete
4.84 kB
"""Conservative count noun-phrase grammar, frozen before benchmark inspection.
Runtime imports only the shared static vocabulary. It has no benchmark routes,
template prefixes, class combinations, annotations, or corpus-derived rules.
Recognizes one unique exact quantity + 0..3 adjective tokens + COCO noun phrase.
"""
import re
import unicodedata
from .count_vocab import FORMS, UNIT_FORMS
NUMBER_WORDS = dict(zip('one two three four five six seven eight nine ten eleven twelve'.split(), range(1, 13)))
ADJECTIVES = frozenset('''adult adorable aged ancient angry antique artificial athletic attractive baby beautiful beige big black blank blue blurry bold brass brave bright broad broken bronze brown calm ceramic cheerful clean clear colorful colourful compact concrete cool cotton crowded curved cute dark delicate dense detailed different dirty distant distinct double dried dry dull eager elegant enormous expressive extra fake fancy fast fat female fierce fine flat fluffy folded fresh friendly frozen full funny fuzzy giant glossy golden gray green grey happy hard heavy huge identical individual indoor large lean light little living long loose loud lovely low male massive mature metallic miniature modern narrow natural navy neat new old open orange ordinary outdoor oval painted pale patterned peaceful pink plain plastic playful plump polished porcelain pretty purple quiet real rectangular red reflective ripe round royal rusty sad sandy separate shiny short silver simple single small smooth soft solid spotted square stainless static striped strong sturdy tall tame thin tiny transparent tropical upright varied vibrant vintage visible vivid warm wet white wide wild wooden woolen yellow young zebra-striped'''.split())
ADJECTIVES = ADJECTIVES | {'empty', 'sailing'}
_SINGULAR_UNITS = '|'.join(re.escape(x) for x in UNIT_FORMS if not x.split()[0].endswith('s'))
_NUMBER = re.compile(r'(?<![\w.])(?:a(?=\s+(?:'+_SINGULAR_UNITS+r')(?!\w))|a\s+(?:pair|couple|trio)\s+of|'+ '|'.join(NUMBER_WORDS) +r'|[0-9]+)(?![\w.])')
_NOUN = re.compile(r'(?<!\w)(?:'+ '|'.join(re.escape(x) for x in sorted(FORMS,key=lambda x:(-len(x),x))) +r')(?!\w)')
_NONEXACT = re.compile(r'\b(?:at least|at most|more than|less than|fewer than|up to|no more than|no fewer than|about|around|roughly|approximately|almost|over|under|between|not|without|minus|plus|or|to|through)\s*$')
def _text(prompt):
return re.sub(r'\s+', ' ', unicodedata.normalize('NFKC',prompt).casefold().replace('–','-').replace('—','-')).strip()
def explain_prompt(prompt):
"""Return diagnostic status without reading any labels or suite information."""
if not isinstance(prompt,str): return {'status':'missing','reason':'not_text','target':None,'candidates':[]}
text = _text(prompt)
candidates=[]
invalid=[]
nouns=list(_NOUN.finditer(text))
for number in _NUMBER.finditer(text):
# Require spaces within the noun phrase; punctuation cannot be an adjective.
possible=[]
for noun in nouns:
if noun.start() <= number.end(): continue
middle=text[number.end():noun.start()]
if not re.fullmatch(r'\s+(?:[a-z]+\s+){0,3}',middle): continue
adjectives=middle.split()
if not all(word in ADJECTIVES for word in adjectives): continue
possible.append(noun)
if not possible: continue
# e.g. "two orange cats": orange is an adjective of cats, not a fruit.
noun=max(possible,key=lambda m:(m.end(),-m.start()))
surface=number.group()
value=({'a':1,'a pair of':2,'a couple of':2,'a trio of':3}.get(surface)
or NUMBER_WORDS.get(surface) or (int(surface) if surface.isdigit() else None))
before=text[:number.start()]
after=text[noun.end():]
if (_NONEXACT.search(before) or re.search(r'[0-9]\s*[-/]\s*$',before)
or re.match(r'\s*(?:[-/]\s*[0-9]|or\s+(?:[0-9]+|'+'|'.join(NUMBER_WORDS)+r')\b)',after)
or before.endswith(('-', '+'))):
invalid.append({'surface':text[number.start():noun.end()],'reason':'non_exact_or_alternative'})
continue
candidates.append({'skill':'count','object':FORMS[noun.group()],'count':value})
unique={tuple(sorted(x.items())) for x in candidates}
if invalid: return {'status':'ambiguous','reason':'non_exact_quantity','target':None,'candidates':candidates,'rejected':invalid}
if len(unique)>1: return {'status':'ambiguous','reason':'multiple_count_targets','target':None,'candidates':candidates}
if not unique: return {'status':'missing','reason':'no_supported_count_phrase','target':None,'candidates':[]}
return {'status':'parsed','reason':'unique_exact_count','target':candidates[0],'candidates':candidates}
def parse_prompt(prompt):
return explain_prompt(prompt)['target']