File size: 4,905 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""Conservative structured appearance metadata; never a visual certificate.

Only named fields/labels are read. Paths, model names and free prose are not
appearance evidence. Published unknown/pending fields contribute no labels.
"""
from __future__ import annotations
import math

DIMENSIONS = ('style_tags', 'colors', 'materials', 'shapes')
_ALIASES = {'wooden':'wood','wood_appearance':'wood',
            'grey':'gray','l_shaped':'l_shape','l-shaped':'l_shape',
            'round_shape':'round','contemporary_modern':'modern',
            'wood_look':'wood','metal_look':'metal','glass_look':'glass',
            'ceramic_look':'ceramic','fabric_look':'fabric','stone_look':'stone',
            'textile_look':'textile','leather_look':'leather','rectangular':'rectangle'}


def labels(value):
    if isinstance(value,str):
        token=value.strip().casefold().replace(' ','_').replace('-','_')
        return {_ALIASES.get(token,token)} if token and token not in {
            'unknown','unspecified','none','n/a','pending'} else set()
    if isinstance(value,list):
        return set().union(*(labels(v) for v in value)) if value else set()
    if isinstance(value,dict):
        if value.get('status') in {'unknown','pending','unverified','rejected','missing','failed','conflict'}:
            return set()
        if 'score' in value and (type(value['score']) not in (int,float) or
                                 not math.isfinite(value['score']) or value['score']<.4):
            return set()
        # Never flatten arbitrary dict values (evidence paths, status, source).
        for key in ('labels','tags','name','value','material_appearance','color_name','shape_name'):
            if key in value:return labels(value[key])
    return set()


def appearance_features(record):
    fields=record.get('field_values',{})
    attributes=record.get('attributes',{})
    containers=[('root',record),('field_values',fields),('attributes',attributes)]
    if isinstance(fields,dict):containers.append(('field_values.semantic',fields.get('semantic',{})))
    keys={'style_tags':('style','style_tags','style_metadata','design_style','aesthetic_style'),
          'colors':('colors','color','color_tags'),
          'materials':('materials','material','material_tags'),
          'shapes':('shapes','shape','shape_tags')}
    result={d:set() for d in DIMENSIONS};basis={d:[] for d in DIMENSIONS}
    for prefix,container in containers:
        if not isinstance(container,dict):continue
        for dimension,names in keys.items():
            for key in names:
                found=labels(container.get(key))
                if found:
                    result[dimension].update(found);basis[dimension].append(prefix+'.'+key)
        for tag in container.get('tags',[]) if isinstance(container.get('tags'),list) else []:
            if isinstance(tag,str) and tag.casefold().startswith('style:'):
                result['style_tags'].update(labels(tag.split(':',1)[1]));basis['style_tags'].append(prefix+'.tags[style:]')
    return {k:sorted(v) for k,v in result.items()},basis


def assess_appearance(features, preferences, explicit, *, style_match='all'):
    """Explicit lists are conjunctive; default families are alternatives.

    Defaults are soft design intent; explicit unknowns never pass as a match.
    Returns metadata ranking only, not source-image or geometry certification.
    """
    explicit=explicit or {};preferences=preferences or {}
    requirements={d:labels(explicit.get(d)) for d in DIMENSIONS}
    missing=[];mismatched=[]
    for d,wanted in requirements.items():
        observed=labels(features.get(d))
        if wanted and not observed:missing.append(d)
        elif wanted and not (bool(wanted&observed) if d=='style_tags' and style_match=='any'
                             else wanted<=observed):mismatched.append(d)
    hard_status='mismatch' if mismatched else 'unknown' if missing else 'match' if any(requirements.values()) else 'not_requested'
    effective={d:requirements[d] or labels(preferences.get(d)) for d in DIMENSIONS}
    distances={}
    for d,wanted in effective.items():
        if wanted:
            observed=labels(features.get(d))
            distances[d]=0 if wanted&observed else 1 if not observed else 2
    status=('unknown' if not distances or all(v==1 for v in distances.values()) else
            'metadata_match' if all(v==0 for v in distances.values()) else
            'partial_metadata_match' if any(v==0 for v in distances.values()) else 'metadata_mismatch')
    return dict(explicit_appearance_status=hard_status,explicit_missing_dimensions=missing,
        explicit_mismatched_dimensions=mismatched,combination_status=status,
        combination_rank=[distances.get('style_tags',0),sum(distances.values())/max(1,len(distances))],
        appearance_qualified=False,appearance_evidence_scope='structured_index_metadata_only')