Datasets:
Download code/robohome/src/bedroom_asset_diversity.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/bedroom_asset_diversity.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/bedroom_asset_diversity.py
-
curl -L -o bedroom_asset_diversity.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/bedroom_asset_diversity.py
12.4 kB
| """Bounded bedroom source preferences shared by normal and support selection. | |
| These are ordering hints only. No source is admitted or removed here, and no | |
| retrieval, preparation, or pair-search budget is extended for variety. | |
| """ | |
| from collections import Counter | |
| from asset_diversity_order import TOP_N | |
| METADATA_SCAN_LIMIT = 512 | |
| def bedroom_role(entity): | |
| category=entity.get('category') or entity.get('role') | |
| if category=='bed' or entity.get('furnishing_function')=='sleeping': | |
| return 'bed' | |
| if category=='nightstand' or entity.get('furnishing_function')=='bedside_surface': | |
| return 'nightstand' | |
| return None | |
| class BedroomAssetDiversity: | |
| def __init__(self, request, catalog, by_need, retained, *, enabled=True, excluded_by_need=None, blocked=()): | |
| self.entities={e['entity_id']:e for e in request['entities']} | |
| self.rules={r['entity_id']:r for r in request.get('furniture',[])} | |
| self.catalog=catalog | |
| self.by_need=by_need | |
| self.retained=retained | |
| self.excluded_by_need=excluded_by_need or {} | |
| self.metadata_windows={} | |
| self.blocked=blocked | |
| self.enabled=enabled and request.get('mode')!='locked' | |
| self.fixed={e['entity_id']:e for e in request.get('search_constraints',{}).get('fixed_entities',[])} | |
| self.families={c['asset_id']:(c.get('shape_family') or {}).get('family_id') | |
| for c in catalog.values() if (c.get('shape_family') or {}).get('family_id')} | |
| for eid,need in by_need.items(): | |
| if not bedroom_role(self.entities[eid]):continue | |
| for hit in need.get('ranked_assets',need.get('hits',[])): | |
| family=(hit.get('shape_family') or {}).get('family_id') | |
| if family:self.families[hit['asset_id']]=family | |
| def family(self, asset_id): | |
| return self.families.get(asset_id) or asset_id | |
| def protected(self, eid): | |
| rule=self.rules.get(eid,{}) | |
| if eid in self.retained:return 'retained_qualified_selection' | |
| if eid in self.fixed or self.entities[eid].get('fixed') or rule.get('fixed'): | |
| return 'fixed_entity' | |
| if rule.get('asset_id') or rule.get('record_id'):return 'explicit_pin' | |
| if ('preferred_candidate_record_ids' in rule and | |
| not rule.get('suitability_preference_generated') and | |
| not rule.get('grouped_preference_generated')): | |
| return 'explicit_preference' | |
| return None | |
| def available_sources(self, eid): | |
| rule=self.rules.get(eid,{}) | |
| allowed={rule['asset_id']} if rule.get('asset_id') else set(rule.get('candidate_asset_ids',[])) or None | |
| refs={rule['record_id']} if rule.get('record_id') else set(rule.get('candidate_record_ids',[])) | |
| fixed=self.fixed.get(eid,{}) | |
| if fixed.get('record_id'):refs={fixed['record_id']} | |
| if refs: | |
| sources={self.catalog[r]['asset_id'] for r in refs if r in self.catalog} | |
| allowed=sources if allowed is None else allowed & sources | |
| if eid in self.retained:allowed={self.retained[eid]['asset_id']} | |
| elif fixed.get('asset_id'):allowed={fixed['asset_id']} | |
| need=self.by_need[eid] | |
| return [h['asset_id'] for h in need.get('ranked_assets',need.get('hits',[])) | |
| if h['asset_id'] not in self.excluded_by_need.get(eid,set()) | |
| and (allowed is None or h['asset_id'] in allowed)] | |
| def shared_bedside_sources(self, eid): | |
| room=self.entities[eid].get('room_id') | |
| siblings=[other for other,e in self.entities.items() | |
| if e.get('room_id')==room and bedroom_role(e)=='nightstand'] | |
| common=None | |
| for other in siblings: | |
| sources=set(self.available_sources(other)[:METADATA_SCAN_LIMIT]) | |
| # A measured rejection remains pair-local. It can disfavor a | |
| # parent for matching only when every remaining source for one | |
| # carried child forms a known blocked pair with that parent. | |
| for aid in list(sources): | |
| children={child for parent,source,child,_ in self.blocked if parent==other and source==aid} | |
| for child in children: | |
| candidates=self.available_sources(child) | |
| if candidates and all((other,aid,child,c) in self.blocked for c in candidates): | |
| sources.discard(aid) | |
| common=sources if common is None else common & sources | |
| return common or set() | |
| def metadata_window(self, eid, ranked, check, selected=None): | |
| """Finite metadata stages shared by support search and normal selection.""" | |
| if not bedroom_role(self.entities[eid]) or not self.enabled or self.protected(eid): | |
| return list(ranked), [] | |
| audit=self.metadata_windows.setdefault(eid,dict(checked_count=0, | |
| metadata_eligible_asset_ids=[],checked_asset_ids=[],scan_limit_exhausted=False,unchecked_count=0)) | |
| checked=set(audit['checked_asset_ids']) | |
| admitted=set(audit['metadata_eligible_asset_ids']) | |
| eligible=[];families=set();variants=[];consumed=0 | |
| room=self.entities[eid].get('room_id') | |
| matching={aid for other,aid in (selected or {}).items() if other!=eid and other in self.entities | |
| and self.entities[other].get('room_id')==room | |
| and bedroom_role(self.entities[other])=='nightstand'} if bedroom_role(self.entities[eid])=='nightstand' else set() | |
| for hit in ranked: | |
| aid=hit['asset_id'] | |
| if aid not in checked: | |
| if len(checked)>=METADATA_SCAN_LIMIT:break | |
| checked.add(aid);audit['checked_asset_ids'].append(aid) | |
| if not check(eid,hit): | |
| admitted.add(aid);audit['metadata_eligible_asset_ids'].append(aid) | |
| consumed+=1 | |
| if aid in admitted: | |
| family=self.family(aid) | |
| (variants if family in families else eligible).append(hit) | |
| families.add(family) | |
| if len(families)>=TOP_N and (not matching or matching & admitted):break | |
| audit.update(checked_count=len(checked), | |
| scan_limit_exhausted=audit['scan_limit_exhausted'] or (len(checked)>=METADATA_SCAN_LIMIT and consumed<len(ranked)), | |
| unchecked_count=sum(h['asset_id'] not in checked for h in ranked)) | |
| # Preserve the support search audit when normal selection pins one result. | |
| if len(ranked)==1 and len(checked)>1: | |
| audit['unchecked_count']=max(audit.get('remaining_unchecked_count',0),audit['unchecked_count']) | |
| audit['remaining_unchecked_count']=audit['unchecked_count'] | |
| if matching: | |
| eligible.sort(key=lambda h:h['asset_id'] not in matching) | |
| return eligible+variants,list(ranked[consumed:]) | |
| def order(self, eid, ranked, selected): | |
| entity=self.entities[eid];role=bedroom_role(entity) | |
| if not role or not self.enabled:return ranked | |
| protected=self.protected(eid) | |
| if protected: | |
| # Keep authored preference order ahead of diversity, including a | |
| # fixed record supplied through native search constraints. | |
| rule=self.fixed.get(eid) or self.rules.get(eid,{}) | |
| refs=([rule['record_id']] if rule.get('record_id') else | |
| rule.get('preferred_candidate_record_ids',[])) | |
| sources=([rule['asset_id']] if rule.get('asset_id') else | |
| [self.catalog[r]['asset_id'] for r in refs if r in self.catalog]) | |
| if sources: | |
| priority={a:i for i,a in reversed(list(enumerate(sources)))} | |
| return sorted(ranked,key=lambda h:priority.get(h['asset_id'],len(priority))) | |
| return ranked | |
| peers=[(self.entities[other],aid) for other,aid in selected.items() | |
| if aid and other!=eid and other in self.entities and bedroom_role(self.entities[other])==role] | |
| # Retained selections may occur later in request order. Reserve them | |
| # now so an editable bedroom can use a different existing source. | |
| peers.extend((self.entities[other],value['asset_id']) for other,value in self.retained.items() | |
| if other not in selected and other!=eid and bedroom_role(self.entities[other])==role) | |
| same={aid for other,aid in peers if other.get('room_id')==entity.get('room_id')} | |
| outside={aid for other,aid in peers if other.get('room_id')!=entity.get('room_id')} | |
| families={self.family(aid) for aid in outside} | |
| shared=self.shared_bedside_sources(eid) if role=='nightstand' else set() | |
| head,tail=list(ranked[:TOP_N]),list(ranked[TOP_N:]) | |
| # A paired source already selected in this room takes precedence over | |
| # cross-room variety. Remaining rank is stable within the finite metadata scan. | |
| head.sort(key=lambda h:(bool(shared) and h['asset_id'] not in shared, | |
| bool(same) and role=='nightstand' and h['asset_id'] not in same, | |
| self.family(h['asset_id']) in families,h['asset_id'] in outside)) | |
| return head+tail | |
| def receipt(self, result, selected, excluded_by_need): | |
| included={r['entity_id']:r for r in result.get('furniture',[])} | |
| groups={} | |
| for eid,entity in self.entities.items(): | |
| role=bedroom_role(entity) | |
| if not role or eid not in included:continue | |
| aid=selected.get(eid) | |
| rule=included[eid] | |
| qualified={self.catalog[r]['asset_id'] for r in rule.get('candidate_record_ids',[]) if r in self.catalog} | |
| if aid not in qualified:aid=None | |
| group=groups.setdefault((entity.get('room_id'),role),dict(room_id=entity.get('room_id'),role=role, | |
| entity_ids=[],selected_asset_ids=[],selected_family_ids=[],protected_entities={},bounded_candidate_counts={})) | |
| group['entity_ids'].append(eid) | |
| if aid: | |
| group['selected_asset_ids'].append(aid);group['selected_family_ids'].append(self.family(aid)) | |
| reason=self.protected(eid) | |
| if reason:group['protected_entities'][eid]=reason | |
| pool=self.by_need[eid].get('ranked_assets',self.by_need[eid].get('hits',[])) | |
| group['bounded_candidate_counts'][eid]=len(self.metadata_windows.get(eid,{}).get('metadata_eligible_asset_ids',[])) | |
| uses=Counter((g['role'],family) for g in groups.values() for family in set(g['selected_family_ids'])) | |
| repeated=[] | |
| for group in groups.values(): | |
| complete=len(group['selected_asset_ids'])==len(group['entity_ids']) | |
| group['matched_within_room']=complete and len(set(group['selected_asset_ids']))==1 | |
| if not group['matched_within_room']: | |
| group['match_reason']=('incomplete_qualified_selection' if not complete else | |
| 'protected_selection' if group['protected_entities'] else | |
| 'no_shared_source_in_bounded_domains' if not self.shared_bedside_sources(group['entity_ids'][0]) else | |
| 'qualification_or_support_constraints') | |
| repeats=sorted(f for f in set(group['selected_family_ids']) if uses[(group['role'],f)]>1) | |
| if repeats: | |
| reason=('policy_disabled' if not self.enabled else 'protected_selection' if group['protected_entities'] else | |
| 'metadata_scan_limit_unresolved' if any(self.metadata_windows.get(e,{}).get('scan_limit_exhausted') for e in group['entity_ids']) else | |
| 'only_one_metadata_eligible_source_in_scanned_window' if max(group['bounded_candidate_counts'].values(),default=0)<=1 else | |
| 'bounded_preference_or_qualification_or_support_constraints') | |
| repeated.append(dict(room_id=group['room_id'],role=group['role'],family_ids=repeats,reason=reason)) | |
| return dict(schema='rhg.bedroom-asset-diversity.v1',enabled=self.enabled,top_n=TOP_N,metadata_scan_limit=METADATA_SCAN_LIMIT, | |
| groups=list(groups.values()),repeated_across_rooms=repeated,metadata_windows=self.metadata_windows, | |
| distinct_assets_guaranteed=False,scope='qualified_source_domains_before_native_layout', | |
| retrieval_budget_increased=False,preparation_budget_increased=False, | |
| unknown_family_identity='asset_id_fallback') | |