File size: 12,089 Bytes
25c66a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
"""Drug Concept Entity Linking - HuggingFace Space"""

import os
import tempfile
import traceback
from pathlib import Path
import gradio as gr
import lancedb
from sentence_transformers import SentenceTransformer
import pandas as pd

# ===== CONFIG =====
# ดึงจาก Space Secrets (ตั้งค่าใน Settings > Secrets)
def _get_env(name: str, default: str | None = None) -> str | None:
    value = os.environ.get(name)
    if value is None:
        return default
    value = value.strip()
    if not value or value.lower() == "none":
        return default
    return value


HF_TOKEN = _get_env("HF_TOKEN")  # หรือไม่ใส่ก็ได้ถ้า public
INDEX_REPO = _get_env("INDEX_REPO", "amnnma/drug-concept-index")  # เปลี่ยนชื่อ repo
LOCAL_INDEX_PATH = _get_env("LOCAL_INDEX_PATH", "data/lancedb")
DEBUG = _get_env("DEBUG", "0") == "1"

# Model
MODEL_ID = "cambridgeltl/SapBERT-UMLS-2020AB-all-lang-from-XLMR"
TOP_K = 10

class DrugConceptSearcher:
    def __init__(self):
        self.model = None
        self.db = None
        self.table = None
        self._load()

    def _load(self):
        """Load model and connect to LanceDB"""
        print("Loading model...")
        # Force slow tokenizer to avoid fast-tokenizer conversion issues on Space
        self.model = SentenceTransformer(MODEL_ID, tokenizer_kwargs={"use_fast": False})

        # Prefer local index when available (useful for local runs)
        local_root = Path(LOCAL_INDEX_PATH) if LOCAL_INDEX_PATH else None
        if local_root and local_root.exists() and (local_root / "db").exists():
            index_root = local_root
            print(f"Connecting to local LanceDB at {index_root}...")
        else:
            repo_id = INDEX_REPO or "amnnma/drug-concept-index"
            if not isinstance(repo_id, str):
                repo_id = str(repo_id)
            repo_id = repo_id.strip()
            if repo_id.startswith("http"):
                # Accept full HF URLs and extract the repo id
                parts = repo_id.split("/")
                if "datasets" in parts:
                    repo_id = "/".join(parts[parts.index("datasets") + 1 :]).strip("/")
                elif "spaces" in parts:
                    repo_id = "/".join(parts[parts.index("spaces") + 1 :]).strip("/")
                else:
                    repo_id = "/".join(parts[-2:]).strip("/")
            if repo_id.startswith("datasets/"):
                repo_id = repo_id[len("datasets/") :]
            print(f"Connecting to LanceDB from {repo_id}...")
            # Download และ connect ไปยัง LanceDB ใน HF repo
            from huggingface_hub import snapshot_download

            # Download index (cache ไว้ใน /data)
            download_root = Path(os.environ.get("HF_DATA_DIR", "/data")) / "lancedb"
            try:
                download_root.mkdir(parents=True, exist_ok=True)
            except OSError:
                download_root = Path("data/lancedb")
                download_root.mkdir(parents=True, exist_ok=True)

            # Avoid implicit token usage for public datasets
            os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
            try:
                index_root = Path(
                    snapshot_download(
                        repo_id=repo_id,
                        repo_type="dataset",
                        token=False,
                        revision=os.environ.get("HF_DATASET_REVISION", "main"),
                        local_dir=str(download_root),
                    )
                )
            except Exception as e:
                if HF_TOKEN:
                    index_root = Path(
                        snapshot_download(
                            repo_id=repo_id,
                            repo_type="dataset",
                            token=HF_TOKEN,
                            local_dir=str(download_root),
                        )
                    )
                else:
                    raise e

        # Connect to LanceDB
        self.db = lancedb.connect(str(index_root / "db"))
        self.table = self.db.open_table("concepts_drug")
        print("✅ Ready!")

    def search(self, query: str, top_k: int = TOP_K):
        """Search drug concepts"""
        if not query or not query.strip():
            return pd.DataFrame()

        # Encode query
        query_emb = self.model.encode(query, normalize_embeddings=True)

        # Search
        results = self.table.search(query_emb).limit(top_k).to_pandas()

        # Format output
        if "_distance" in results.columns:
            results["score"] = 1 - results["_distance"]  # Convert distance to similarity
            results = results.sort_values("score", ascending=False)

        return results[["concept_id", "concept_name", "concept_code", "vocabulary_id", "score"]]

# Initialize
searcher = None

def get_searcher():
    global searcher
    if searcher is None:
        searcher = DrugConceptSearcher()
    return searcher

def _format_results(results: pd.DataFrame, query: str) -> tuple[str, pd.DataFrame]:
    if results.empty:
        return "No results found. Try a different search term.", results

    output = f"## Results for: \"{query}\"\n\n"
    best = results.iloc[0]
    output += f"**Top match:** {best['concept_name']} (score {best['score']:.4f})\n\n"
    return output, results


def search_drugs(query: str, top_k: int):
    """Gradio search function (single query)"""
    try:
        s = get_searcher()
        results = s.search(query, top_k)

        output, table = _format_results(results, query)
        return output, table
    except Exception as e:
        print("Search error:", e)
        print(traceback.format_exc())
        if DEBUG:
            return f"❌ Error: {str(e)}\n\n```\n{traceback.format_exc()}\n```", pd.DataFrame()
        return f"❌ Error: {str(e)}", pd.DataFrame()


def search_batch(queries_text: str, top_k: int):
    """Gradio search function (batch queries)"""
    try:
        if not queries_text or not queries_text.strip():
            return "Please enter clinical terms to search.", gr.update(visible=False)

        lines = [line.strip() for line in queries_text.splitlines() if line.strip()]
        if not lines:
            return "No valid queries found.", gr.update(visible=False)

        s = get_searcher()
        rows = []
        for q in lines:
            results = s.search(q, top_k)
            for i, (_, row) in enumerate(results.iterrows(), start=1):
                rows.append(
                    {
                        "query_text": q,
                        "rank": i,
                        "concept_id": row["concept_id"],
                        "concept_name": row["concept_name"],
                        "concept_code": row["concept_code"],
                        "vocabulary_id": row["vocabulary_id"],
                        "score": float(row["score"]),
                    }
                )

        if not rows:
            return "No results found.", gr.update(visible=False)

        df = pd.DataFrame(rows)
        tmp_dir = Path(tempfile.gettempdir()) / "thirawat_results"
        tmp_dir.mkdir(parents=True, exist_ok=True)
        out_path = tmp_dir / "batch_results.csv"
        df.to_csv(out_path, index=False)

        md = f"""## Batch Search Complete

- **Queries processed:** {len(lines)}
- **Rows returned:** {len(rows)}
- **Top-K per query:** {top_k}
"""
        return md, gr.update(value=str(out_path), visible=True)
    except Exception as e:
        print("Batch search error:", e)
        print(traceback.format_exc())
        if DEBUG:
            return f"❌ Error: {str(e)}\n\n```\n{traceback.format_exc()}\n```", gr.update(visible=False)
        return f"❌ Error: {str(e)}", gr.update(visible=False)

# ===== GRADIO INTERFACE =====
with gr.Blocks(title="THIRAWAT - Drug Concept Search") as demo:
    gr.HTML(
        """
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 10px; margin-bottom: 20px;">
            <h1 style="color: white; margin: 0; font-size: 2em;">THIRAWAT</h1>
            <p style="color: rgba(255,255,255,0.9); margin: 5px 0 0 0;">Drug Concept Entity Linking</p>
            <p style="color: rgba(255,255,255,0.8); margin: 5px 0 0 0;">Map drug names to OMOP concepts using SapBERT + LanceDB.</p>
        </div>
        """
    )

    with gr.Tabs():
        with gr.Tab("Single Query"):
            with gr.Row():
                with gr.Column(scale=3):
                    query_input = gr.Textbox(
                        label="Drug name or query",
                        placeholder="e.g., aspirin, paracetamol, amoxicillin 500mg...",
                        lines=2,
                    )
                with gr.Column(scale=1):
                    domain_hint = gr.Dropdown(
                        label="Domain",
                        choices=["Drug", "Condition", "Procedure", "Observation", "Device", "Unit"],
                        value="Drug",
                        interactive=False,
                    )
                    top_k = gr.Slider(
                        minimum=1,
                        maximum=50,
                        value=10,
                        step=1,
                        label="Number of results",
                    )

            with gr.Row():
                search_btn = gr.Button("Search", variant="primary")
                clear_btn = gr.Button("Clear", variant="secondary")

            output_md = gr.Markdown(label="Results")
            output_table = gr.Dataframe(label="Results Table", interactive=False)

        with gr.Tab("Batch Query"):
            with gr.Row():
                with gr.Column(scale=3):
                    batch_queries = gr.Textbox(
                        label="Drug names (one per line)",
                        placeholder="aspirin\nparacetamol\namoxicillin 500mg",
                        lines=10,
                    )
                with gr.Column(scale=1):
                    batch_domain_hint = gr.Dropdown(
                        label="Domain",
                        choices=["Drug", "Condition", "Procedure", "Observation", "Device", "Unit"],
                        value="Drug",
                        interactive=False,
                    )
                    batch_topk = gr.Slider(
                        minimum=1,
                        maximum=50,
                        value=10,
                        step=1,
                        label="Top-K per query",
                    )

            with gr.Row():
                batch_btn = gr.Button("Process Batch", variant="primary")
                batch_clear = gr.Button("Clear", variant="secondary")

            batch_output = gr.Markdown(label="Summary")
            batch_download = gr.DownloadButton(
                label="Download Results (CSV)",
                variant="secondary",
                visible=False,
            )

    def clear_single():
        return "", 10, "", pd.DataFrame()

    def clear_batch():
        return "", 10, "", gr.update(visible=False)

    search_btn.click(
        fn=search_drugs,
        inputs=[query_input, top_k],
        outputs=[output_md, output_table],
        api_name=False,
    )
    clear_btn.click(
        fn=clear_single,
        outputs=[query_input, top_k, output_md, output_table],
        api_name=False,
    )

    batch_btn.click(
        fn=search_batch,
        inputs=[batch_queries, batch_topk],
        outputs=[batch_output, batch_download],
        api_name=False,
    )
    batch_clear.click(
        fn=clear_batch,
        outputs=[batch_queries, batch_topk, batch_output, batch_download],
        api_name=False,
    )
    gr.Markdown(
        """
        ---

        **THIRAWAT** is a dense retrieval toolkit for mapping drug terminology to OMOP standard concepts.
        """
    )

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860, share=False)