File size: 4,627 Bytes
778d47d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Utilities for loading BIRD dataset column/value descriptions from
database_description/*.csv files (one CSV per table).

Adapted from CHESS (https://github.com/ShayanTalaei/CHESS)
chess/src/database_utils/db_catalog/csv_utils.py.

Schema returned:
    {
      table_name_lower: {
        column_name_lower: {
          "original_column_name": str,
          "column_name": str,          # expanded/human-readable name
          "column_description": str,
          "data_format": str,
          "value_description": str,
        }
      }
    }
"""

import logging
from pathlib import Path
from typing import Dict

import pandas as pd


def load_db_descriptions(
    db_directory_path: str,
    use_value_description: bool = True,
) -> Dict[str, Dict[str, Dict[str, str]]]:
    """Load table/column descriptions from BIRD database_description/*.csv.

    Args:
        db_directory_path: Path to the database directory (containing
            database_description/ sub-folder).
        use_value_description: Whether to include value_description field.

    Returns:
        Nested dict  table → column → field → value.
        Returns {} when the description folder does not exist.
    """
    encoding_types = ["utf-8-sig", "cp1252", "latin-1"]
    description_path = Path(db_directory_path) / "database_description"

    if not description_path.exists():
        return {}

    table_description: Dict[str, Dict[str, Dict[str, str]]] = {}

    for csv_file in sorted(description_path.glob("*.csv")):
        table_name = csv_file.stem.lower().strip()
        table_description[table_name] = {}
        loaded = False

        for encoding in encoding_types:
            try:
                df = pd.read_csv(csv_file, index_col=False, encoding=encoding)
                for _, row in df.iterrows():
                    col_key = str(row.get("original_column_name", "")).lower().strip()
                    if not col_key:
                        continue

                    def _clean(val, remove_prefix: str = "") -> str:
                        if not pd.notna(val):
                            return ""
                        s = str(val).replace("\n", " ").strip()
                        if remove_prefix and s.lower().startswith(remove_prefix):
                            s = s[len(remove_prefix):].strip()
                        return s

                    col_description = _clean(
                        row.get("column_description", ""),
                        remove_prefix="commonsense evidence:",
                    )
                    value_desc = ""
                    if use_value_description:
                        value_desc = _clean(
                            row.get("value_description", ""),
                            remove_prefix="commonsense evidence:",
                        )
                        if value_desc.lower().startswith("not useful"):
                            value_desc = value_desc[10:].strip()

                    table_description[table_name][col_key] = {
                        "original_column_name": str(row.get("original_column_name", col_key)),
                        "column_name": _clean(row.get("column_name", "")),
                        "column_description": col_description,
                        "data_format": _clean(row.get("data_format", "")),
                        "value_description": value_desc,
                    }

                logging.debug("Loaded descriptions from %s (%s)", csv_file, encoding)
                loaded = True
                break
            except Exception:
                continue

        if not loaded:
            logging.warning("Could not read descriptions from %s", csv_file)

    return table_description


def load_all_db_descriptions(
    bird_dataset_path: str,
    use_value_description: bool = True,
) -> Dict[str, Dict[str, Dict[str, Dict[str, str]]]]:
    """Load descriptions for every database under a BIRD split directory.

    Args:
        bird_dataset_path: Path to a BIRD split, e.g.
            /data/bird/train/train_databases
            Each sub-directory is one db_id.
        use_value_description: Whether to include value_description.

    Returns:
        {db_id: load_db_descriptions(db_dir)}
    """
    root = Path(bird_dataset_path)
    all_descriptions: Dict[str, Dict] = {}

    for db_dir in sorted(root.iterdir()):
        if db_dir.is_dir():
            db_id = db_dir.name
            all_descriptions[db_id] = load_db_descriptions(
                str(db_dir), use_value_description=use_value_description
            )

    return all_descriptions