File size: 5,483 Bytes
4a14841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""Split a Data Card into the texts that represent it in the vector index."""

# Embedding algorithm (section-level chunking):
# 1. One "overview" chunk summarizes what the model is: name, type, primary
#    use, taxonomy capabilities, domains, datasets, and description.
# 2. Every other Data Card section with at least one filled field becomes its
#    own chunk, for example "Performance" or "Legal and ethical".
# 3. Every chunk starts with the model name and section title, so a chunk still
#    makes sense on its own. Missing values ("N/A", not_reported, ...) are
#    left out.
# 4. Retrieval searches all chunks and scores each model by its best chunk.
#
# One vector per section keeps each vector focused on one topic. A single
# vector for the whole card mixes about 66 fields and many empty values, which
# blurs its meaning.

import re
from typing import Any

from rag_chatbot.shared.datacard_values import MISSING_VALUES

EMBEDDING_TEXT_VERSION = "datacard-sections-v1"
OVERVIEW_SECTION = "overview"
FRONT_MATTER = re.compile(r"\A\s*---.*?---\s*", re.DOTALL)
SECTION_TITLES = {
    "general_information": "General information",
    "performance_metrics": "Performance",
    "model_dataset_characteristics": "Model characteristics",
    "training_hardware": "Training and hardware",
    "ai_safety_responsible_ai": "Safety and responsible AI",
    "security_privacy": "Security and privacy",
    "recommendations": "Deployment recommendations",
    "community_support": "Community and support",
    "legal_ethical_considerations": "Legal and ethical",
    "additional_considerations": "Additional considerations",
    "lineage_licensing": "Lineage and licensing",
}
# Already part of the overview chunk.
OVERVIEW_ONLY = {"taxonomy_relations"}
OVERVIEW_FIELDS = {"general_information": {"description"}}


def _text(value: Any) -> str:
    if isinstance(value, list):
        return ", ".join(text for item in value if (text := _text(item)))
    if not isinstance(value, str):
        return ""
    value = value.strip()
    return "" if value.lower() in MISSING_VALUES else value


def _label(key: str) -> str:
    return key.replace("_", " ").strip().capitalize()


def _render(value: Any) -> str:
    """Render any field value as compact text, skipping empty parts."""
    if isinstance(value, dict):
        return "; ".join(
            f"{_label(key)}: {text}"
            for key, item in value.items()
            if (text := _render(item))
        )
    if isinstance(value, list):
        return "; ".join(text for item in value if (text := _render(item)))
    if isinstance(value, (bool, int, float)):
        return str(value)
    return _text(value)


def _names(items: Any, key: str | None = None) -> list[str]:
    """Return unique label names from a taxonomy list, optionally under `key`."""
    names = []
    for item in items if isinstance(items, list) else []:
        labels = item.get(key) if key and isinstance(item, dict) else item
        for label in labels if isinstance(labels, list) else [labels]:
            if isinstance(label, dict) and (name := _text(label.get("name"))):
                names.append(name)
    return list(dict.fromkeys(names))


def _model_name(datacard: dict) -> str:
    general = datacard.get("general_information") or {}
    return _text(general.get("model_dataset_name"))


def datacard_embedding_text(datacard: dict) -> str:
    """Return the overview chunk: what the model is and what it is for."""
    general = datacard.get("general_information") or {}
    taxonomy = datacard.get("taxonomy_relations") or {}
    capabilities = taxonomy.get("capabilities")
    description = FRONT_MATTER.sub("", _text(general.get("description")))

    parts = [
        ("Model", _model_name(datacard)),
        ("Type", _text(general.get("model_type"))),
        ("Primary use", _text(general.get("primary_use_case"))),
        ("Tasks", ", ".join(_names(capabilities, "task"))),
        ("Modalities", ", ".join(_names(capabilities, "modality"))),
        ("Use cases", ", ".join(_names(capabilities, "use_case"))),
        ("Applications", ", ".join(_names(capabilities, "applications"))),
        ("Domains", ", ".join(
            name
            for key in ("sector", "subsector", "industry")
            for name in _names(taxonomy.get("domains"), key)
        )),
        ("Datasets", ", ".join(_names(taxonomy.get("datasets_used")))),
        ("Description", description),
    ]
    return "\n".join(f"{label}: {value}" for label, value in parts if value)


def datacard_chunks(datacard: dict) -> list[dict[str, str]]:
    """Return the overview chunk followed by one chunk per filled section."""
    model = _model_name(datacard)
    chunks = [{"section": OVERVIEW_SECTION, "text": datacard_embedding_text(datacard)}]

    for section, fields in datacard.items():
        if section in OVERVIEW_ONLY or not isinstance(fields, dict):
            continue
        skipped = OVERVIEW_FIELDS.get(section, set())
        lines = [
            f"{_label(field)}: {text}"
            for field, value in fields.items()
            if field not in skipped and (text := _render(value))
        ]
        if not lines:
            continue
        title = SECTION_TITLES.get(section, _label(section))
        header = f"Model: {model}\nSection: {title}" if model else f"Section: {title}"
        chunks.append({"section": section, "text": "\n".join([header, *lines])})

    return [chunk for chunk in chunks if chunk["text"]]