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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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""

conversation_search_tools.py



This module combines TWO search tools over the same cleaned

doctor–patient conversation dataset:



1. Semantic (vector) search using FAISS + embeddings.

2. Keyword search using simple substring matching + scoring.



It is designed to be used both:



- As a library/module for LLM tools:

    - search_conversations_semantic_tool(...)

    - search_conversations_keyword_tool(...)



- And as a local CLI for debugging:

    python conversation_search_tools.py --mode semantic

    python conversation_search_tools.py --mode keyword

"""

import argparse
import os
from typing import List, Dict, Any, Optional

import numpy as np
import pandas as pd
import faiss

try:
    from openai import OpenAI
    client = OpenAI()
except ImportError:
    client = None


# Embedding model name (must match the one used to build the FAISS index)
EMBEDDING_MODEL = "text-embedding-3-small"

# Global caches to avoid reloading large files on every tool call
_GLOBAL_DF: Optional[pd.DataFrame] = None
_GLOBAL_DATA_PATH: Optional[str] = None

_GLOBAL_INDEX: Optional[faiss.Index] = None
_GLOBAL_INDEX_PATH: Optional[str] = None


# ======================= Data / index loading =======================

def _load_data_internal(data_path: str) -> pd.DataFrame:
    """

    Low-level function to load the cleaned CSV file.

    It does NOT enforce keyword-specific columns here; those are checked

    in the keyword tool function.

    """
    if not os.path.exists(data_path):
        raise FileNotFoundError(f"Data CSV not found: {data_path}")

    df = pd.read_csv(data_path)

    # Base required columns (used by both tools)
    base_required_cols = [
        "conversation_id",
        "description",
        "patient_text",
        "doctor_text",
    ]
    for col in base_required_cols:
        if col not in df.columns:
            raise ValueError(
                f"Required column '{col}' not in CSV. "
                f"Available columns: {list(df.columns)}"
            )

    # Keep row order consistent with whatever was used to build the index
    df = df.reset_index(drop=True)
    return df


def _ensure_data_loaded(data_path: str) -> None:
    """

    Ensure that the global DataFrame is loaded into memory.

    Reload if the path changes.

    """
    global _GLOBAL_DF, _GLOBAL_DATA_PATH

    if _GLOBAL_DF is None or _GLOBAL_DATA_PATH != data_path:
        _GLOBAL_DF = _load_data_internal(data_path)
        _GLOBAL_DATA_PATH = data_path


def _load_index_internal(index_path: str) -> faiss.Index:
    """

    Low-level function to load the FAISS index from disk.

    """
    if not os.path.exists(index_path):
        raise FileNotFoundError(f"FAISS index file not found: {index_path}")
    index = faiss.read_index(index_path)
    return index


def _ensure_index_loaded(index_path: str) -> None:
    """

    Ensure that the global FAISS index is loaded into memory.

    Reload if the path changes.

    """
    global _GLOBAL_INDEX, _GLOBAL_INDEX_PATH

    if _GLOBAL_INDEX is None or _GLOBAL_INDEX_PATH != index_path:
        _GLOBAL_INDEX = _load_index_internal(index_path)
        _GLOBAL_INDEX_PATH = index_path


# ======================= Embedding helper =======================

def embed_query(query: str) -> np.ndarray:
    """

    Convert a text query into an embedding vector (float32 numpy array).



    By default this uses OpenAI embeddings. You can replace this with any

    other embedding backend as long as you keep the same dimension and

    normalization as when the FAISS index was built.

    """
    if client is None:
        raise RuntimeError(
            "OpenAI client not available. "
            "Install `openai` and set OPENAI_API_KEY, or modify "
            "embed_query() to use your own embedding model."
        )

    resp = client.embeddings.create(
        model=EMBEDDING_MODEL,
        input=[query]
    )
    emb = np.array(resp.data[0].embedding, dtype="float32")
    # Normalize so that inner product approximates cosine similarity
    faiss.normalize_L2(emb.reshape(1, -1))
    return emb


# ======================= Semantic search core =======================

def _semantic_search_core(

    index: faiss.Index,

    df: pd.DataFrame,

    query: str,

    top_k: int = 5,

) -> List[Dict[str, Any]]:
    """

    Run vector search in FAISS to find conversations semantically

    similar to the query.

    """
    if not query:
        return []

    q_emb = embed_query(query)
    q_emb = q_emb.reshape(1, -1)

    scores, indices = index.search(q_emb, top_k)
    scores = scores[0]
    indices = indices[0]

    results: List[Dict[str, Any]] = []
    for idx, score in zip(indices, scores):
        if idx < 0:
            continue
        row = df.iloc[idx]
        results.append(
            {
                "conversation_id": str(row["conversation_id"]),
                "description": str(row.get("description", "")),
                "patient_text": str(row.get("patient_text", "")),
                "doctor_text": str(row.get("doctor_text", "")),
                "score": float(score),
            }
        )
    return results


# ======================= Keyword search core =======================

def _keyword_search_core(

    df: pd.DataFrame,

    query: str,

    top_k: int = 5,

) -> List[Dict[str, Any]]:
    """

    Perform simple keyword-based search over the "text_for_keyword_lower"

    column, then score and rank results.



    Ranking priorities:

        1. Whether patient_text contains the query (case-insensitive).

        2. Whether doctor_text contains the query (case-insensitive).

        3. Shorter text_for_keyword is ranked slightly higher.

    """
    if not query:
        return []

    required_cols = [
        "text_for_keyword",
        "text_for_keyword_lower",
    ]
    for col in required_cols:
        if col not in df.columns:
            raise ValueError(
                f"Required column '{col}' for keyword search is missing. "
                f"Available columns: {list(df.columns)}"
            )

    q = query.lower()

    mask = df["text_for_keyword_lower"].str.contains(q, na=False)
    hits = df[mask].copy()

    if hits.empty:
        return []

    # Base score column
    hits["score"] = 0.0

    # +2 if patient_text contains the query
    hits.loc[
        hits["patient_text"].str.lower().str.contains(q, na=False),
        "score"
    ] += 2.0

    # +1 if doctor_text contains the query
    hits.loc[
        hits["doctor_text"].str.lower().str.contains(q, na=False),
        "score"
    ] += 1.0

    # Length penalty: shorter text_for_keyword is preferred
    hits["length_penalty"] = hits["text_for_keyword"].str.len()

    hits = hits.sort_values(
        by=["score", "length_penalty"],
        ascending=[False, True],
    ).head(top_k)

    results: List[Dict[str, Any]] = []
    for _, row in hits.iterrows():
        results.append(
            {
                "conversation_id": str(row["conversation_id"]),
                "description": str(row.get("description", "")),
                "patient_text": str(row.get("patient_text", "")),
                "doctor_text": str(row.get("doctor_text", "")),
                "score": float(row["score"]),
            }
        )
    return results


# ======================= PUBLIC TOOL FUNCTIONS =======================

def search_conversations_semantic_tool(

    query: str,

    top_k: int = 5,

    data_path: str = "conversations_clean.csv",

    index_path: str = "conversation_vectors.index",

) -> List[Dict[str, Any]]:
    """

    LLM TOOL #1: Semantic (vector) search.



    Args:

        query: User's natural-language question (any language).

        top_k: Number of most similar conversations to retrieve.

        data_path: Path to the cleaned conversations CSV file.

        index_path: Path to the FAISS index file.



    Returns:

        A list of dicts, each with:

            - conversation_id: str

            - description: str

            - patient_text: str

            - doctor_text: str

            - score: float (similarity score; larger = more similar)

    """
    if not query or not query.strip():
        return []

    _ensure_data_loaded(data_path)
    _ensure_index_loaded(index_path)

    assert _GLOBAL_DF is not None
    assert _GLOBAL_INDEX is not None

    return _semantic_search_core(
        index=_GLOBAL_INDEX,
        df=_GLOBAL_DF,
        query=query.strip(),
        top_k=top_k,
    )


def search_conversations_keyword_tool(

    query: str,

    top_k: int = 5,

    data_path: str = "conversations_clean.csv",

) -> List[Dict[str, Any]]:
    """

    LLM TOOL #2: Keyword search.



    Args:

        query: User's keyword query or phrase (any language).

        top_k: Number of top results to return.

        data_path: Path to the cleaned conversations CSV file.



    Returns:

        A list of dicts, each with:

            - conversation_id: str

            - description: str

            - patient_text: str

            - doctor_text: str

            - score: float (simple keyword-based score)

    """
    if not query or not query.strip():
        return []

    _ensure_data_loaded(data_path)
    assert _GLOBAL_DF is not None

    return _keyword_search_core(
        df=_GLOBAL_DF,
        query=query.strip(),
        top_k=top_k,
    )


# ======================= CLI helpers (optional) =======================

def _pretty_print_results(results: List[Dict[str, Any]], title: str = "Results") -> None:
    if not results:
        print("No results found.")
        return

    print(f"\n=== {title} ===")
    for i, item in enumerate(results, start=1):
        print(f"\n[{i}] conversation_id = {item['conversation_id']}")
        print(f"Score: {item['score']:.4f}")
        if item["description"]:
            print(f"Description: {item['description']}")
        print(f"Patient: {item['patient_text']}")
        print(f"Doctor: {item['doctor_text']}")
    print(f"\n{'=' * 30}\n")


def main():
    parser = argparse.ArgumentParser(
        description=(
            "Combined search tools over cleaned doctor-patient conversations. "
            "Mode can be 'semantic' (vector search) or 'keyword'."
        )
    )
    parser.add_argument(
        "--mode",
        type=str,
        choices=["semantic", "keyword"],
        default="semantic",
        help="Search mode: 'semantic' (vector FAISS) or 'keyword'. Default: semantic",
    )
    parser.add_argument(
        "--data",
        type=str,
        default="conversations_clean.csv",
        help="Path to cleaned CSV file. Default: conversations_clean.csv",
    )
    parser.add_argument(
        "--index",
        type=str,
        default="conversation_vectors.index",
        help="Path to FAISS index file (semantic mode only).",
    )
    parser.add_argument(
        "--top_k",
        type=int,
        default=5,
        help="Number of top results to show. Default: 5",
    )
    parser.add_argument(
        "--query",
        type=str,
        default=None,
        help="Optional single query (non-interactive). "
             "If omitted, run in interactive loop.",
    )

    args = parser.parse_args()

    _ensure_data_loaded(args.data)
    if args.mode == "semantic":
        _ensure_index_loaded(args.index)

    if args.query:
        # Non-interactive: single query
        if args.mode == "semantic":
            results = search_conversations_semantic_tool(
                query=args.query,
                top_k=args.top_k,
                data_path=args.data,
                index_path=args.index,
            )
            _pretty_print_results(results, title="Semantic Search Results")
        else:
            results = search_conversations_keyword_tool(
                query=args.query,
                top_k=args.top_k,
                data_path=args.data,
            )
            _pretty_print_results(results, title="Keyword Search Results")
        return

    # Interactive loop
    print(f"{args.mode.capitalize()} search is ready.")
    print("Type your query and press Enter to search.")
    print("Type 'q' or empty line to exit.\n")

    while True:
        try:
            query = input("Query> ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nExiting.")
            break

        if query == "" or query.lower() == "q":
            print("Bye.")
            break

        if args.mode == "semantic":
            results = search_conversations_semantic_tool(
                query=query,
                top_k=args.top_k,
                data_path=args.data,
                index_path=args.index,
            )
            _pretty_print_results(results, title="Semantic Search Results")
        else:
            results = search_conversations_keyword_tool(
                query=query,
                top_k=args.top_k,
                data_path=args.data,
            )
            _pretty_print_results(results, title="Keyword Search Results")


if __name__ == "__main__":
    main()