Spaces:
Configuration error
Configuration error
Download src/rag_chatbot/shared/embedding/text.py from nhabibi/HF-RAGChatbot-Streamlit: direct link, hf CLI and curl.
- Browser
- Download file 5.48 kB
-
https://huggingface.co/spaces/nhabibi/HF-RAGChatbot-Streamlit/resolve/main/src/rag_chatbot/shared/embedding/text.py
- Command line
-
hf download hf://spaces/nhabibi/HF-RAGChatbot-Streamlit/src/rag_chatbot/shared/embedding/text.py
-
curl -L -o text.py https://huggingface.co/spaces/nhabibi/HF-RAGChatbot-Streamlit/resolve/main/src/rag_chatbot/shared/embedding/text.py
5.48 kB
| """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"]] | |