| 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: |
| |
| 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 |
| |
| 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: |
| |
| |
| |
| |
| |
| |
| results = [json.loads(searcher.doc(0).raw())['contents']] |
| else: |
| results = [] |
|
|
| |
| |
| |
| return results |
|
|
| |
| app = FastAPI(title="Column Content Searcher API") |
|
|
| |
| column_content_searcher = None |
|
|
| @app.on_event("startup") |
| def startup_event(): |
| global column_content_searcher |
| |
| test_set_names = [ |
| |
| 'DB_schema_synonym', |
| 'DB_schema_abbreviation', |
| 'DB_DBcontent_equivalence', |
|
|
| |
| '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', |
| ] |
|
|
| DR_SPIDER_BASE = './data/sft_data_collections/diagnostic-robustness-text-to-sql/data' |
| source_db_content_index_paths = { |
| |
| 'bird-dev': './data/bird/dev/db_contents_index', |
| 'bird-train': './data/bird/train/db_contents_index', |
| |
| 'spider-train': './data/spider/db_contents_index', |
| |
| 'spider-dk': './data/sft_data_collections/Spider-DK/db_contents_index', |
| |
| 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', |
| |
| 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', |
| |
| 'bank_financials-dev': './data/sft_data_collections/domain_datasets/db_contents_index', |
| 'bank_financials-train': './data/sft_data_collections/domain_datasets/db_contents_index', |
| } |
| |
| 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: |
| |
| source_db_content_index_paths = {k: v for k, v in source_db_content_index_paths.items() if k == args.db_content_index} |
|
|
| |
| 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) |
|
|
| |
| class SearchRequest(BaseModel): |
| source: str |
| db_id: str |
| table: str |
| column: str |
| query: str |
| k: Optional[int] = 10 |
|
|
| |
| 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() |
|
|
| |
| import uvicorn |
| uvicorn.run(app, host="0.0.0.0", port=args.port, reload=False) |
|
|