File size: 11,220 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
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from pyserini.search.lucene import LuceneSearcher
from tqdm import tqdm
import json

class ColumnContentSearcher:
    def __init__(self, source_db_content_index_paths, synonym_sources, lazy_load: bool = False):
        """
        Initialize the ColumnContentSearcher with multiple sources.

        Parameters:
            source_db_content_index_paths (dict): A dictionary mapping source names to their db_content_index_paths.
            lazy_load (bool): If True, store only index paths at startup; construct LuceneSearcher
                              on demand at first request (memory-efficient — fixes OOM on large index sets).
        """
        self.source_db_content_index_paths = source_db_content_index_paths
        self.searcher = {}
        self.lazy_load = lazy_load

        for source, db_content_index_path in source_db_content_index_paths.items():
            db_ids = os.listdir(db_content_index_path)
            self.searcher[source] = {}
            for db_id in tqdm(db_ids, desc=f"{'Indexing paths' if lazy_load else 'Loading searchers'} for source '{source}'"):
                table_column_indexes = os.listdir(os.path.join(db_content_index_path, db_id))
                for table_column_index in table_column_indexes:
                    try:
                        table, column = table_column_index.split("-**-")
                        searcher_path = os.path.join(db_content_index_path, db_id, table_column_index)
                        if os.path.isdir(searcher_path):
                            subdirs = os.listdir(searcher_path)
                            if len(subdirs) == 1:
                                searcher_path = os.path.join(searcher_path, subdirs[0])
                                column = column + "/" + subdirs[0]

                        if lazy_load:
                            # Just remember the path; build the searcher on first hit.
                            self.searcher[source].setdefault(db_id, {}).setdefault(table, {})[column] = searcher_path
                        else:
                            lucene_searcher = LuceneSearcher(searcher_path)
                            lucene_searcher.set_bm25(k1=1.2, b=0.75)
                            self.searcher[source].setdefault(db_id, {}).setdefault(table, {})[column] = lucene_searcher
                    except Exception as e:
                        print(f"Error loading {source}/{db_id}/{table_column_index}: {e}")

        for source in synonym_sources:
            self.searcher[source] = self.searcher[synonym_sources[source]]

    def get_searcher(self, source, db_id, table, column):
        """
        Retrieve the searcher for the given source, db_id, table, and column.
        Lazy-loads the LuceneSearcher on first request when lazy_load=True.
        """
        entry = self.searcher.get(source, {}).get(db_id, {}).get(table, {}).get(column, None)
        if entry is None:
            return None
        # Lazy: if entry is a path string, build searcher and replace in cache.
        if isinstance(entry, str):
            try:
                searcher = LuceneSearcher(entry)
                searcher.set_bm25(k1=1.2, b=0.75)
                self.searcher[source][db_id][table][column] = searcher
                return searcher
            except Exception as e:
                print(f"Warning: Failed to load Lucene index at {entry}: {e}")
                self.searcher[source][db_id][table][column] = None
                return None
        return entry

    def search_column_content(self, source, db_id, table, column, query, k=10):
        """
        Search the column content for a given query.

        Parameters:
            source (str): The source name (e.g., 'bird-dev', 'bird-train').
            db_id (str): The database identifier.
            table (str): The table name.
            column (str): The column name.
            query (str): The search query.
            k (int): The number of results to return.

        Returns:
            list: A list of search results, or None if the searcher is not found.
        """
        searcher = self.get_searcher(source, db_id, table, column)
        if searcher is None:
            return None
        hits = searcher.search(query, k=k)
        if len(hits) > 0:
            results = [json.loads(hit.raw) for hit in hits]
            results = [x['contents'] for x in results]
        elif searcher.num_docs > 0:
            # BM25 found no query-relevant hits, but the column is non-empty.
            # Return the first indexed document as a fixed, reproducible
            # "representative example" from the column's value set.
            # This satisfies the paper's claim that the fallback provides a
            # representative in-domain value — the first document by Lucene
            # insertion order is a stable, deterministic sample from V_ci.
            results = [json.loads(searcher.doc(0).raw())['contents']]
        else:
            results = []

        # if args.lazy_load:
        #     del searcher
        #     gc.collect()
        return results

# FastAPI app
app = FastAPI(title="Column Content Searcher API")

# Initialize the ColumnContentSearcher in the startup event
column_content_searcher = None

@app.on_event("startup")
def startup_event():
    global column_content_searcher
# Replace 'your_db_content_index_path' with the actual path to your index
    test_set_names = [
        # DB Schema related
        'DB_schema_synonym',
        'DB_schema_abbreviation',
        'DB_DBcontent_equivalence',

        # NLQ related
        '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 related
        'SQL_comparison',
        'SQL_sort_order',
        'SQL_NonDB_number',
        'SQL_DB_text',
        'SQL_DB_number',
    ]

    DR_SPIDER_BASE = './data/sft_data_collections/diagnostic-robustness-text-to-sql/data'
    source_db_content_index_paths = {
        # BIRD
        'bird-dev':   './data/bird/dev/db_contents_index',
        'bird-train': './data/bird/train/db_contents_index',
        # Spider main (dev + test share same databases)
        'spider-train': './data/spider/db_contents_index',
        # Spider-DK (3 new databases)
        'spider-dk': './data/sft_data_collections/Spider-DK/db_contents_index',
        # Dr. Spider — DB perturbation sets have modified databases
        f'dr.spider-DB_schema_synonym':       f'{DR_SPIDER_BASE}/DB_schema_synonym/db_contents_index',
        f'dr.spider-DB_schema_abbreviation':  f'{DR_SPIDER_BASE}/DB_schema_abbreviation/db_contents_index',
        f'dr.spider-DB_DBcontent_equivalence':f'{DR_SPIDER_BASE}/DB_DBcontent_equivalence/db_contents_index',
        # Dr. Spider — NLQ/SQL perturbation sets reuse the original Spider databases
        f'dr.spider-NLQ_keyword_synonym':  f'{DR_SPIDER_BASE}/NLQ_keyword_synonym/db_contents_index',
        f'dr.spider-NLQ_keyword_carrier':  f'{DR_SPIDER_BASE}/NLQ_keyword_carrier/db_contents_index',
        f'dr.spider-NLQ_column_synonym':   f'{DR_SPIDER_BASE}/NLQ_column_synonym/db_contents_index',
        f'dr.spider-NLQ_column_carrier':   f'{DR_SPIDER_BASE}/NLQ_column_carrier/db_contents_index',
        f'dr.spider-NLQ_column_attribute': f'{DR_SPIDER_BASE}/NLQ_column_attribute/db_contents_index',
        f'dr.spider-NLQ_column_value':     f'{DR_SPIDER_BASE}/NLQ_column_value/db_contents_index',
        f'dr.spider-NLQ_value_synonym':    f'{DR_SPIDER_BASE}/NLQ_value_synonym/db_contents_index',
        f'dr.spider-NLQ_multitype':        f'{DR_SPIDER_BASE}/NLQ_multitype/db_contents_index',
        f'dr.spider-NLQ_others':           f'{DR_SPIDER_BASE}/NLQ_others/db_contents_index',
        f'dr.spider-SQL_comparison':       f'{DR_SPIDER_BASE}/SQL_comparison/db_contents_index',
        f'dr.spider-SQL_sort_order':       f'{DR_SPIDER_BASE}/SQL_sort_order/db_contents_index',
        f'dr.spider-SQL_DB_text':          f'{DR_SPIDER_BASE}/SQL_DB_text/db_contents_index',
        f'dr.spider-SQL_DB_number':        f'{DR_SPIDER_BASE}/SQL_DB_number/db_contents_index',
        f'dr.spider-SQL_NonDB_number':     f'{DR_SPIDER_BASE}/SQL_NonDB_number/db_contents_index',
        # Domain datasets
        'bank_financials-dev':   './data/sft_data_collections/domain_datasets/db_contents_index',
        'bank_financials-train': './data/sft_data_collections/domain_datasets/db_contents_index',
    }
    # Filter to only existing index directories to avoid startup errors
    source_db_content_index_paths = {
        k: v for k, v in source_db_content_index_paths.items() if os.path.isdir(v)
    }
    synonym_sources = {
        'spider-dev':      'spider-train',
        'spider-syn-dev':  'spider-train',
        'spider-realistic':'spider-train',
        'aminer_simplified-dev':   'bank_financials-dev',
        'aminer_simplified-train': 'bank_financials-dev',
    }

    if args.db_content_index is not None:
        # delete all the default paths except the one specified
        source_db_content_index_paths = {k: v for k, v in source_db_content_index_paths.items() if k == args.db_content_index}

    # Only keep synonym entries whose target source is actually loaded
    synonym_sources = {
        k: v for k, v in synonym_sources.items()
        if v in source_db_content_index_paths
    }

    use_lazy = bool(args is not None and getattr(args, "lazy_load", False))
    column_content_searcher = ColumnContentSearcher(source_db_content_index_paths, synonym_sources, lazy_load=use_lazy)

# Request model
class SearchRequest(BaseModel):
    source: str
    db_id: str
    table: str
    column: str
    query: str
    k: Optional[int] = 10  # Number of results to return

# Response model
class SearchResponse(BaseModel):
    results: List[str]

@app.post("/search_column_content", response_model=SearchResponse)
def search_column_content(request: SearchRequest):
    if column_content_searcher is None:
        raise HTTPException(status_code=500, detail="Searcher not initialized.")
    results = column_content_searcher.search_column_content(
        source=request.source,
        db_id=request.db_id,
        table=request.table,
        column=request.column,
        query=request.query,
        k=request.k
    )
    if results is None:
        print(request.source, request.db_id, request.table, request.column)
        raise HTTPException(status_code=404, detail="Searcher not found for the given db_id, table, and column.")
    return SearchResponse(results=results)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--lazy_load", action='store_true')
    parser.add_argument("--port", type=int, default=8005)
    parser.add_argument("--db_content_index", type=str, default=None)
    args = parser.parse_args()

    # Run the app with Uvicorn
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=args.port, reload=False)