parsing.py 3.44 KB
"""Compatibility parsing for recommendation index values."""

import json
import math
import re


_INTEGER_FLOAT_RE = re.compile(r'^([+-]?\d+)\.0+$')


def normalize_identifier(value):
    """Return a stable string representation for an item or dimension ID."""
    if value is None or isinstance(value, bool):
        return None
    if isinstance(value, int):
        return str(value)
    if isinstance(value, float):
        if not math.isfinite(value):
            return None
        if value.is_integer():
            return str(int(value))
        return str(value)

    text = str(value).strip()
    if not text or len(text) > 256:
        return None
    if any(char in text for char in ('\x00', '\r', '\n', '\t')):
        return None
    integer_match = _INTEGER_FLOAT_RE.match(text)
    if integer_match:
        return integer_match.group(1)
    return text


def _parse_score(value):
    if value is None or isinstance(value, bool):
        return None
    try:
        score = float(value)
    except (TypeError, ValueError, OverflowError):
        return None
    if not math.isfinite(score):
        return None
    return score


def _append_result(results, seen, item_id, score=None):
    item_id = normalize_identifier(item_id)
    if item_id is None or item_id in seen:
        return
    seen.add(item_id)
    results.append((item_id, _parse_score(score)))


def _parse_json_value(parsed, results, seen):
    if isinstance(parsed, dict):
        for item_id, score in parsed.items():
            _append_result(results, seen, item_id, score)
        return True

    if not isinstance(parsed, list):
        return False

    for entry in parsed:
        if isinstance(entry, dict):
            item_id = entry.get('item_id', entry.get('id'))
            _append_result(results, seen, item_id, entry.get('score'))
        elif isinstance(entry, (list, tuple)):
            if entry:
                score = entry[1] if len(entry) > 1 else None
                _append_result(results, seen, entry[0], score)
        else:
            _append_result(results, seen, entry)
    return True


def parse_ranked_items(value):
    """Parse current and historical Redis value formats.

    Supported forms include ``id:score,id:score``, JSON pairs, JSON objects,
    plain JSON ID lists, and a JSON-encoded legacy string.
    """
    if value is None:
        return []
    if isinstance(value, bytes):
        try:
            value = value.decode('utf-8')
        except UnicodeDecodeError:
            return []

    if isinstance(value, (list, dict)):
        results = []
        _parse_json_value(value, results, set())
        return results

    text = str(value).strip()
    if not text:
        return []

    results = []
    seen = set()
    if text[0] in '[{"':
        try:
            parsed = json.loads(text)
        except (TypeError, ValueError):
            parsed = None
        if isinstance(parsed, str) and parsed != text:
            return parse_ranked_items(parsed)
        if _parse_json_value(parsed, results, seen):
            return results

    for token in text.split(','):
        token = token.strip()
        if not token:
            continue
        if ':' in token:
            item_id, score = token.rsplit(':', 1)
            parsed_score = _parse_score(score)
            if parsed_score is None:
                continue
            _append_result(results, seen, item_id, parsed_score)
        else:
            _append_result(results, seen, token)
    return results