RoboHome / code /robohome /src /appearance_requirements.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame Contribute Delete
14.9 kB
"""Finite bilingual appearance modifiers for existing scene entities only.
Canonical values are intent tags, not asset eligibility or satisfaction proof.
Whole-house style is only ``spec.style.style_tags``; no native style filter is
enabled. Entity/style/source pins and existing structured appearance win.
Negation, alternatives, multiple noun references or duplicate entity kinds in one scope are
unresolved. This deliberately does not perform general language understanding.
"""
import copy
import re
_VOCABULARY = {
'style_tags': {
'modern': ('现代风格', '现代风', '现代', 'modern'),
'scandinavian': ('北欧风格', '北欧风', '北欧', 'scandinavian', 'nordic'),
'industrial': ('工业风格', '工业风', '工业', 'industrial'),
'japanese': ('日式风格', '日式', 'japanese'),
},
'colors': {
'blue': ('蓝色', '蓝', 'blue'), 'white': ('白色', '白', 'white'),
'black': ('黑色', '黑', 'black'), 'gray': ('灰色', '灰', 'gray', 'grey'),
'beige': ('米色', 'beige'), 'red': ('红色', '红', 'red'),
'green': ('绿色', '绿', 'green'), 'brown': ('棕色', '褐色', 'brown'),
},
'materials': {
'solid_wood': ('实木', 'solid wood', 'solid-wood'),
'wood': ('木质', '木制', '木头', 'wooden', 'wood'),
'metal': ('金属', 'metal'), 'velvet': ('丝绒', 'velvet'),
'leather': ('皮革', 'leather'), 'glass': ('玻璃', 'glass'),
},
'shapes': {
'l_shaped': ('L型', 'L形', 'L-shaped', 'L shaped'),
'round': ('圆形', '圆的', 'round', 'circular'),
'square': ('方形', '方的', 'square'),
'three_seater': ('三人位', '三人座', 'three-seater', 'three seater', '3-seater'),
},
}
def _literal(term):
pattern = re.escape(term)
if term[0].isascii() and term[0].isalnum():
pattern = r'(?<![A-Za-z0-9_])' + pattern
if term[-1].isascii() and term[-1].isalnum():
pattern += r'(?![A-Za-z0-9_])'
return pattern
_TERMS = {alias.casefold(): (field, value)
for field, values in _VOCABULARY.items()
for value, aliases in values.items() for alias in aliases}
_TERM_RE = re.compile('|'.join(_literal(a) for a in sorted(_TERMS, key=len, reverse=True)), re.I)
_NOUNS = {'沙发': 'sofa', 'sofa': 'sofa', 'sofas': 'sofa', 'couch': 'sofa', 'couches': 'sofa',
'餐桌': 'dining_table', 'dining table': 'dining_table', 'dining tables': 'dining_table',
'茶几': 'coffee_table', 'coffee table': 'coffee_table', 'coffee tables': 'coffee_table',
'床': 'bed', 'bed': 'bed', 'beds': 'bed'}
_NOUN_RE = re.compile('|'.join(
('床(?!头柜|头灯|垫|单|罩|品|架|边柜|笠)' if a == '床' else _literal(a))
for a in sorted(_NOUNS, key=len, reverse=True)), re.I)
_ROLES = {'sofa': 'sofa', 'couch': 'sofa', 'dining_table': 'dining_table',
'coffee_table': 'coffee_table', 'bed': 'bed', '沙发': 'sofa', '餐桌': 'dining_table',
'茶几': 'coffee_table', '床': 'bed'}
_NEGATIVE = re.compile(r'不要|不|别|避免|排除|禁止|非|无|'
r"\b(?:not|no|without|avoid|exclude|except|neither|nor)\b|don['’]t", re.I)
_ALTERNATIVE = re.compile(r'或者|或|还是|\b(?:either|or)\b', re.I)
_MULTIPLE = re.compile(r'[两二三四五六七八九十2-9]\s*(?:张|个|套|把)|'
r'\b(?:two|three|four|several|multiple|both)\b', re.I)
_GLOBAL = re.compile(r'全屋|整屋|全家|整个住宅|\b(?:whole|entire)\s+(?:house|home)\b', re.I)
_EXPLICIT = re.compile(r'风格|款式|颜色|色彩|材质|材料|形状|型号|品牌|asset[_ ]?id|'
r'\b(?:style|colou?r|material|shape|brand|model)\b', re.I)
_SUFFIX = re.compile(r'^\s*(?:的?\s*(?:要求|需要|要|是|为|用|采用|选择|颜色|材质|款式|形状|风格)|'
r'(?:is|are|should|must|with|in|made|of|style|colou?r|material|shape)\b)', re.I)
_ROOMS = {
'living': ('客厅', '起居室', 'living room', 'living_room'),
'dining': ('餐厅', 'dining room', 'dining_room'),
'master': ('主卧', 'master bedroom', 'master_bedroom'),
'guest': ('次卧', '客卧', 'guest bedroom', 'guest_bedroom'),
'bedroom': ('卧室', 'bedroom'), 'kitchen': ('厨房', 'kitchen'),
'study': ('书房', 'study', 'office'), 'bathroom': ('卫生间', '浴室', 'bathroom'),
'children': ('儿童房', 'kids room', 'children room'),
}
_ROOM_NAMES = {alias.casefold(): key for key, aliases in _ROOMS.items() for alias in aliases}
_ROOM_RE = re.compile('|'.join(_literal(a) for a in sorted(_ROOM_NAMES, key=len, reverse=True)), re.I)
_FILLERS = ('机器人', '客厅里', '餐厅里', '请', '我', '想', '希望', '给', '在', '里', '中',
'放置', '摆放', '放', '摆', '配置', '选择', '选用', '配', '采用', '添加', '需要',
'要求', '要', '使用', '用', '有', '是', '为', '一个', '一张', '一套', '一把',
'的', '款式', '风格', '风', '颜色', '色彩', '材质', '材料', '形状', '指定',
'到达', '靠近', '前往', '全屋', '整屋', '全家', '整个住宅',
'please', 'i', 'would', 'like', 'want', 'need', 'a', 'an', 'the', 'and',
'place', 'put', 'choose', 'select', 'add', 'use', 'have', 'has', 'is', 'are',
'should', 'must', 'be', 'with', 'in', 'of', 'for', 'to', 'made',
'style', 'color', 'colour', 'material', 'shape', 'whole', 'entire', 'house', 'home')
_FILLER_RE = re.compile('|'.join(_literal(a) for a in sorted(_FILLERS, key=len, reverse=True)), re.I)
_PINS = ('asset_id', 'record_id', 'source_sha256', 'asset_sha256', 'runtime_sha256',
'canonical_transform', 'explicit_source_pins', 'source_release_record_id',
'candidate_asset_ids', 'candidate_record_ids')
_STRUCTURED = {'style_tags': ('style', 'style_tags'), 'colors': ('color', 'colors'),
'materials': ('material', 'materials'), 'shapes': ('shape', 'shapes', 'shape_terms')}
def _terms(text, offset):
return [dict(field=_TERMS[m.group().casefold()][0], value=_TERMS[m.group().casefold()][1],
text=m.group(), span=[offset+m.start(), offset+m.end()])
for m in _TERM_RE.finditer(text)]
def _unsupported(text):
text = _TERM_RE.sub(' ', text)
text = _ROOM_RE.sub(' ', text)
text = _FILLER_RE.sub(' ', text)
return re.sub(r'[\s::=、/"“”\-()()]+', '', text).strip()
def _room_matches(entity, text, spec):
scopes = {_ROOM_NAMES[m.group().casefold()] for m in _ROOM_RE.finditer(text)}
if not scopes:
return True
if len(scopes) != 1:
return False
room_id = entity.get('room_id')
room = next((r for r in spec.get('rooms', []) if r.get('room_id') == room_id), {})
labels = {str(room_id).casefold(), str(room.get('room_type', '')).casefold(),
str(room.get('name', '')).casefold(),
str(room.get('room_purpose',room.get('purpose',''))).casefold()}
known = {_ROOM_NAMES.get(label, label) for label in labels}
return bool(scopes & known)
def _apply(entity, terms, report, text, span):
requirements = entity.get('requirements', {})
if not isinstance(requirements, dict) or not isinstance(requirements.get('appearance', {}), dict):
report['unresolved'].append(dict(text=text, span=span, reason='invalid_structured_appearance',
entity_id=entity.get('entity_id')))
return
if any(holder.get(key) for holder in (entity, requirements) for key in _PINS):
report['unresolved'].append(dict(text=text, span=span, reason='structured_pin_precedence',
entity_id=entity.get('entity_id'), recognized_terms=terms))
return
appearance = requirements.get('appearance', {})
for field in _VOCABULARY:
hits = [r for r in terms if r['field'] == field]
if not hits:
continue
values = list(dict.fromkeys(r['value'] for r in hits))
existing = appearance.get(field)
protected = (field in appearance or any(k in holder for holder in (requirements, entity)
for k in _STRUCTURED[field]))
if protected and not (isinstance(existing, list) and all(v in existing for v in values)):
report['unresolved'].append(dict(text=text, span=span, entity_id=entity.get('entity_id'),
reason='structured_requirement_precedence', field=field, requested_values=values))
continue
if not protected:
requirements = entity.setdefault('requirements', {})
appearance = requirements.setdefault('appearance', {})
appearance[field] = values
report['recognized'].extend(dict(row, scope='entity', entity_id=entity.get('entity_id'))
for row in hits)
def apply_appearance_requirements(spec, raw):
"""Return a deep copy with finite intent tags and a non-qualification receipt.
Unresolved entries are actionable input ambiguities/unsupported appearance,
not inferred facts. Unrelated task text is retained without becoming an
appearance failure. All offsets refer to the unchanged raw input string.
"""
if not isinstance(spec, dict) or not isinstance(raw, str):
raise TypeError('spec must be an object and raw must be the original text string')
result = copy.deepcopy(spec)
if not isinstance(result.get('entities', []), list) or not isinstance(result.get('constraints', {}), dict):
raise TypeError('entities must be a list and constraints must be an object')
report = dict(schema='rhg.appearance_parse.v1', parser='bounded_bilingual_dictionary_v1',
raw_text=raw, recognized=[], unresolved=[], unparsed_clauses=[],
general_nlu=False, native_style_enabled=False, satisfaction='not_evaluated')
for match in re.finditer(r'[^,,。.;;!?!?\n]+', raw):
text = match.group(); offset = match.start(); span = [offset, match.end()]
nouns = list(_NOUN_RE.finditer(text)); all_terms = _terms(text, offset)
global_scope = bool(_GLOBAL.search(text))
explicit = bool(_EXPLICIT.search(text))
if not nouns and not global_scope:
if all_terms or explicit:
report['unresolved'].append(dict(text=text, span=span,
reason='appearance_without_supported_entity_or_scope', recognized_terms=all_terms))
elif text.strip():
report['unparsed_clauses'].append(dict(text=text, span=span, reason='outside_appearance_dictionary'))
continue
if global_scope and not nouns:
style_terms = [r for r in all_terms if r['field'] == 'style_tags']
if _NEGATIVE.search(text) or _ALTERNATIVE.search(text):
report['unresolved'].append(dict(text=text, span=span, reason='negation_or_alternative'))
continue
tags = list(dict.fromkeys(r['value'] for r in style_terms))
style = result.get('style', {})
if tags and (not style or isinstance(style, dict) and style.get('style_tags') == tags):
result.setdefault('style', {})['style_tags'] = tags
report['recognized'].extend(dict(r, scope='whole_house', entity_id=None) for r in style_terms)
elif tags:
report['unresolved'].append(dict(text=text, span=span, reason='structured_style_precedence'))
remaining = _unsupported(text)
if remaining or not tags or any(r['field'] != 'style_tags' for r in all_terms):
report['unresolved'].append(dict(text=text, span=span, reason='unsupported_whole_house_appearance',
unsupported_text=remaining or text))
continue
# Clauses with several nouns have no safe modifier attachment in this
# small grammar. Separate noun-specific clauses are supported.
if len(nouns) != 1 or global_scope:
if all_terms or explicit:
report['unresolved'].append(dict(text=text, span=span, reason='ambiguous_multiple_noun_or_scope'))
continue
noun = nouns[0]; role = _NOUNS[noun.group().casefold()]
prefix = text[:noun.start()]
after = text[noun.end():]
suffix = after if _SUFFIX.match(after) or _TERM_RE.match(after.lstrip()) or _EXPLICIT.search(after) else ''
terms = _terms(prefix, offset) + _terms(suffix, offset+noun.end())
unsupported = ' '.join(v for v in (_unsupported(prefix), _unsupported(suffix)) if v)
if not terms and not unsupported and not explicit and not all_terms:
continue
if _NEGATIVE.search(text) or _ALTERNATIVE.search(text):
report['unresolved'].append(dict(text=text, span=span, reason='negation_or_alternative'))
continue
if _MULTIPLE.search(_TERM_RE.sub(' ', text)) or noun.group().casefold() in ('sofas', 'couches', 'beds', 'dining tables', 'coffee tables'):
report['unresolved'].append(dict(text=text, span=span, reason='multiple_requested_entities'))
continue
targets = [e for e in result.get('entities', []) if isinstance(e, dict) and
_ROLES.get(e.get('category', e.get('role', ''))) == role]
if _ROOM_RE.search(text):
scoped=[e for e in targets if _room_matches(e,text,result)]
if scoped:targets=scoped
reason = ('entity_not_found' if not targets else 'multiple_existing_entities' if len(targets) != 1
else 'room_scope_unresolved' if not _room_matches(targets[0], text, result) else None)
if reason:
report['unresolved'].append(dict(text=text, span=span, reason=reason,
candidate_entity_ids=[e.get('entity_id') for e in targets]))
continue
if terms:
_apply(targets[0], terms, report, text, span)
if unsupported:
report['unresolved'].append(dict(text=text, span=span, reason='unsupported_local_appearance',
entity_id=targets[0].get('entity_id'), unsupported_text=unsupported))
outside = [r for r in all_terms if r not in terms]
if outside:
report['unresolved'].append(dict(text=text, span=span, reason='appearance_outside_local_modifier_scope',
recognized_terms=outside))
report['status'] = ('partial' if report['recognized'] else 'unresolved') if report['unresolved'] else (
'recognized' if report['recognized'] else 'no_appearance_requirements')
result.setdefault('constraints', {})['appearance_parse'] = report
return result