Blame view

offline_tasks/agent_tools/catalog.py 4.03 KB
b4f7574f   tangwang   feat(agent): add ...
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
  """Small searchable catalog for turning names into index dimension values."""
  
  import json
  import os
  from datetime import datetime
  
  
  _CATALOG_DIMENSION_ALIASES = {
      'category': 'category',
      'category_level1': 'category',
      'category_level2': 'category',
      'category_level3': 'category',
      'category_level4': 'category',
      'supplier': 'supplier',
      'platform': 'platform',
      'client_platform': 'client_platform',
      'country_code': 'country_code',
      'customer_type': 'customer_type',
  }
  
  
  def save_agent_dimension_catalog(mappings, output_dir, generated_at=None):
      """Write the small Agent catalog without copying the item name mapping."""
      os.makedirs(output_dir, exist_ok=True)
      dimensions = {
          'category': mappings.get('category', {}),
          'supplier': mappings.get('supplier', {}),
          'platform': {
              'essa': 'essa',
              'essaone': 'essaone',
              'essabuy': 'essabuy',
          },
          'client_platform': {
              'pc': 'PC',
          },
      }
      catalog = {
          'schema_version': 1,
          'generated_at': generated_at or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
          'dimensions': dimensions,
      }
      catalog_file = os.path.join(output_dir, 'agent_dimension_catalog.json')
      temporary_file = catalog_file + '.tmp'
      with open(temporary_file, 'w', encoding='utf-8') as output_file:
          json.dump(catalog, output_file, ensure_ascii=False, separators=(',', ':'))
      os.replace(temporary_file, catalog_file)
      return catalog_file
  
  
  class DimensionCatalog(object):
      """Resolve human-readable category or supplier names without a database call."""
  
      def __init__(self, dimensions=None, metadata=None):
          self.dimensions = {}
          for name, values in (dimensions or {}).items():
              if isinstance(values, dict):
                  self.dimensions[name] = {
                      str(value): str(label)
                      for value, label in values.items()
                      if value is not None and label is not None
                  }
          self.metadata = dict(metadata or {})
  
      @classmethod
      def from_file(cls, path):
          with open(path, 'r', encoding='utf-8') as catalog_file:
              payload = json.load(catalog_file)
          dimensions = payload.get('dimensions', {})
          metadata = {
              key: value for key, value in payload.items() if key != 'dimensions'
          }
          return cls(dimensions=dimensions, metadata=metadata)
  
      @property
      def available(self):
          return bool(self.dimensions)
  
      def resolve(self, dimension, query, limit=10):
          catalog_dimension = _CATALOG_DIMENSION_ALIASES.get(dimension)
          values = self.dimensions.get(catalog_dimension, {})
          query_text = str(query or '').strip()
          if not query_text or not values:
              return []
  
          folded_query = query_text.casefold()
          query_tokens = [token for token in folded_query.split() if token]
          matches = []
          for value, label in values.items():
              folded_value = value.casefold()
              folded_label = label.casefold()
              match_type = None
              score = 0.0
              if folded_query == folded_value:
                  match_type, score = 'exact_value', 1.0
              elif folded_query == folded_label:
                  match_type, score = 'exact_label', 0.99
              elif folded_label.startswith(folded_query):
                  match_type, score = 'label_prefix', 0.90
              elif folded_query in folded_label:
                  match_type, score = 'label_contains', 0.82
              elif query_tokens and all(token in folded_label for token in query_tokens):
                  match_type, score = 'all_tokens', 0.75
              if match_type:
                  matches.append({
                      'value': value,
                      'label': label,
                      'match_type': match_type,
                      'score': score,
                  })
  
          matches.sort(key=lambda match: (
              -match['score'], len(match['label']), match['value']
          ))
          return matches[:limit]