catalog.py 4.03 KB
"""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]