File size: 9,828 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
Build BM25 (Lucene) content indexes for all datasets needed by MATS-TIST.

Run from the mats-sql-tist/ root directory:
    conda run -n mats python scripts/build_all_bm25_indexes.py

CPU-only; no GPU required.

Datasets covered:
  - BIRD dev / train          (data/bird/dev|train)
  - Spider dev+test           (data/spider)
  - Spider-DK                 (3 new databases)
  - Spider-Syn / spider-realistic  (share Spider databases → symlinked)
  - Dr.Spider NLQ_* / SQL_*   (share original Spider databases → symlinked)
  - Dr.Spider DB_*            (post-perturbation databases, built fresh)
  - Domain datasets           (Bank_Financials, Aminer_Simplified)
"""

import os
import sys
import shutil
import json
from tqdm import tqdm

# Make sure we can import from the project root
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.db_utils import get_cursor_from_path, execute_sql_long_time_limitation


# ---------------------------------------------------------------------------
# Core indexer (copied from build_contents_index.py)
# ---------------------------------------------------------------------------

def build_content_index(db_path: str, index_path: str) -> None:
    """Build a per-column BM25 index for one SQLite database."""
    cursor = get_cursor_from_path(db_path)
    results = execute_sql_long_time_limitation(
        cursor, "SELECT name FROM sqlite_master WHERE type='table';"
    )
    table_names = [r[0] for r in results]

    for table_name in table_names:
        table_name = table_name.lower()
        if table_name == "sqlite_sequence":
            continue
        results = execute_sql_long_time_limitation(
            cursor, f"SELECT name FROM PRAGMA_TABLE_INFO('{table_name}')"
        )
        column_names = [r[0].lower() for r in results]

        for column_name in column_names:
            column_index_path = f"{index_path}/{table_name}-**-{column_name}"
            if os.path.exists(column_index_path):
                continue

            all_column_contents = []
            try:
                rows = execute_sql_long_time_limitation(
                    cursor,
                    f"SELECT DISTINCT `{column_name}` FROM `{table_name}` WHERE `{column_name}` IS NOT NULL;",
                )
                for c_id, row in enumerate(rows):
                    content = str(row[0]).strip()
                    if 0 < len(content) <= 50:
                        all_column_contents.append(
                            {
                                "id": f"{table_name}-**-{column_name}-**-{c_id}".lower(),
                                "contents": content,
                            }
                        )
            except Exception as e:
                print(f"  [WARN] {table_name}.{column_name}: {e}")

            os.makedirs("./data/temp_db_index", exist_ok=True)
            with open("./data/temp_db_index/contents.json", "w") as f:
                json.dump(all_column_contents, f, indent=2, ensure_ascii=True)

            cmd = (
                "python -m pyserini.index.lucene "
                "--collection JsonCollection "
                "--input ./data/temp_db_index "
                f'--index "{column_index_path}" '
                "--generator DefaultLuceneDocumentGenerator "
                "--threads 16 --storePositions --storeDocvectors --storeRaw"
            )
            ret = os.system(cmd)
            if os.path.exists("./data/temp_db_index/contents.json"):
                os.remove("./data/temp_db_index/contents.json")
            if ret != 0:
                print(f"  [ERROR] indexing failed for {column_index_path}")


def index_dataset(db_root: str, index_root: str, label: str) -> None:
    """Index all databases under db_root into index_root."""
    if not os.path.isdir(db_root):
        print(f"[SKIP] {label}: db_root not found: {db_root}")
        return

    os.makedirs(index_root, exist_ok=True)
    db_ids = [d for d in os.listdir(db_root) if os.path.isdir(os.path.join(db_root, d))]
    print(f"\n{'='*60}")
    print(f"[INDEX] {label}  ({len(db_ids)} databases → {index_root})")
    print(f"{'='*60}")

    for db_id in tqdm(db_ids, desc=label):
        sqlite_path = os.path.join(db_root, db_id, f"{db_id}.sqlite")
        if not os.path.exists(sqlite_path):
            # Some Dr.Spider perturbation folders have different sqlite name
            candidates = [
                f for f in os.listdir(os.path.join(db_root, db_id))
                if f.endswith(".sqlite")
            ]
            if candidates:
                sqlite_path = os.path.join(db_root, db_id, candidates[0])
            else:
                print(f"  [SKIP] no .sqlite in {db_id}")
                continue
        build_content_index(sqlite_path, os.path.join(index_root, db_id))


def symlink_index(src: str, dst: str, label: str) -> None:
    """Create a symlink dst → src if dst does not already exist."""
    if os.path.exists(dst) or os.path.islink(dst):
        print(f"[OK]   {label} already present: {dst}")
        return
    if not os.path.isdir(src):
        print(f"[WARN] {label}: source index not found: {src}")
        return
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    os.symlink(src, dst)
    print(f"[LINK] {label}: {dst}{src}")


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    os.chdir(ROOT)
    print(f"Working directory: {ROOT}")

    DR = "./data/sft_data_collections/diagnostic-robustness-text-to-sql/data"

    # ------------------------------------------------------------------
    # 1. BIRD dev / train  (bird-062024)
    # ------------------------------------------------------------------
    index_dataset(
        db_root="./data/bird/dev/dev_databases",
        index_root="./data/bird/dev/db_contents_index",
        label="BIRD dev",
    )
    index_dataset(
        db_root="./data/bird/train/train_databases",
        index_root="./data/bird/train/db_contents_index",
        label="BIRD train",
    )

    # sft_data_collections/bird → symlink to the same bird index
    symlink_index(
        src=os.path.abspath("./data/bird/dev/db_contents_index"),
        dst="./data/sft_data_collections/bird/dev/db_contents_index",
        label="sft bird/dev (symlink)",
    )
    symlink_index(
        src=os.path.abspath("./data/bird/train/db_contents_index"),
        dst="./data/sft_data_collections/bird/train/db_contents_index",
        label="sft bird/train (symlink)",
    )

    # ------------------------------------------------------------------
    # 2. Spider dev + test  (all share the same 169 databases)
    # ------------------------------------------------------------------
    index_dataset(
        db_root="./data/spider/database",
        index_root="./data/spider/db_contents_index",
        label="Spider (dev/test/train databases)",
    )

    # Spider-Syn and spider-realistic share Spider databases → symlink
    symlink_index(
        src=os.path.abspath("./data/spider/db_contents_index"),
        dst="./data/sft_data_collections/Spider-Syn/db_contents_index",
        label="Spider-Syn (symlink)",
    )
    symlink_index(
        src=os.path.abspath("./data/spider/db_contents_index"),
        dst="./data/sft_data_collections/spider-realistic/db_contents_index",
        label="spider-realistic (symlink)",
    )

    # ------------------------------------------------------------------
    # 3. Spider-DK  (3 new databases not in Spider)
    # ------------------------------------------------------------------
    index_dataset(
        db_root="./data/sft_data_collections/Spider-DK/database",
        index_root="./data/sft_data_collections/Spider-DK/db_contents_index",
        label="Spider-DK",
    )

    # ------------------------------------------------------------------
    # 4. Dr. Spider — NLQ_* and SQL_* reuse original Spider databases
    #    → symlink their db_contents_index to Spider's
    # ------------------------------------------------------------------
    for dr_name in [
        "NLQ_keyword_synonym", "NLQ_keyword_carrier", "NLQ_column_synonym",
        "NLQ_column_carrier", "NLQ_column_attribute", "NLQ_column_value",
        "NLQ_value_synonym", "NLQ_multitype", "NLQ_others",
        "SQL_comparison", "SQL_sort_order", "SQL_NonDB_number",
        "SQL_DB_text", "SQL_DB_number",
    ]:
        symlink_index(
            src=os.path.abspath("./data/spider/db_contents_index"),
            dst=f"{DR}/{dr_name}/db_contents_index",
            label=f"Dr.Spider/{dr_name} (symlink)",
        )

    # ------------------------------------------------------------------
    # 5. Dr. Spider — DB_* perturbation sets have MODIFIED databases
    # ------------------------------------------------------------------
    for dr_name in [
        "DB_schema_synonym",
        "DB_schema_abbreviation",
        "DB_DBcontent_equivalence",
    ]:
        index_dataset(
            db_root=f"{DR}/{dr_name}/database_post_perturbation",
            index_root=f"{DR}/{dr_name}/db_contents_index",
            label=f"Dr.Spider/{dr_name}",
        )

    # ------------------------------------------------------------------
    # 6. Domain datasets (Bank_Financials, Aminer_Simplified)
    # ------------------------------------------------------------------
    index_dataset(
        db_root="./data/sft_data_collections/domain_datasets/databases",
        index_root="./data/sft_data_collections/domain_datasets/db_contents_index",
        label="Domain datasets",
    )

    print("\n[DONE] All BM25 indexes built / symlinked.")