File size: 8,019 Bytes
628bda0
 
 
 
f98d92f
628bda0
f98d92f
 
628bda0
 
f98d92f
 
 
 
3d8ce85
f98d92f
628bda0
f98d92f
 
 
1fb3b25
 
628bda0
 
f98d92f
 
 
 
 
628bda0
f98d92f
628bda0
 
f98d92f
 
 
 
 
 
 
 
 
628bda0
f98d92f
3d8ce85
f98d92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f537fa
 
f98d92f
 
0f537fa
d1cde39
2efb95c
f98d92f
 
 
 
 
df6f47b
 
 
f98d92f
0adf63d
f98d92f
 
 
 
628bda0
d1cde39
f98d92f
628bda0
f98d92f
 
d1cde39
f98d92f
 
8ba12a0
3518799
f98d92f
628bda0
8ba12a0
628bda0
 
f98d92f
8ba12a0
f98d92f
 
df6f47b
 
 
 
f98d92f
 
8ba12a0
 
 
 
df6f47b
 
 
 
f98d92f
 
8ba12a0
3518799
 
 
 
 
 
 
 
 
df6f47b
3518799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df6f47b
8ba12a0
 
 
 
 
 
df6f47b
fe65577
8ba12a0
 
 
 
 
 
f98d92f
8ba12a0
 
 
 
 
 
df6f47b
8ba12a0
df6f47b
8ba12a0
 
 
153a78e
8ba12a0
 
 
38d1269
8ba12a0
38d1269
f98d92f
8ba12a0
 
fe65577
 
38d1269
fe65577
 
df6f47b
628bda0
fe65577
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
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModel
import numpy as np
from typing import List, Dict
import pandas as pd
import os
from pinecone import Pinecone


# =========================
# Retriever Class
# =========================
class ParrotletRetriever:
    def __init__(self, model_name: str):
        """Initialize model and Pinecone client."""
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        print(f"🚀 Loading model on {self.device}...")

        # Load tokenizer and model
        self.tokenizer = AutoTokenizer.from_pretrained(model_name, token=os.getenv("HF_TOKEN"))
        self.model = AutoModel.from_pretrained(model_name, token=os.getenv("HF_TOKEN"))
        self.model.to(self.device)
        self.model.eval()

        self.pinecone_namespace = os.environ.get("NAMESPACE")
        self.pinecone_client = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))
        self.pinecone_index = self.pinecone_client.Index(host=os.environ.get("PINECONE_HOST"))

    def mean_pooling(self, model_output, attention_mask):
        """Mean pooling for sentence embeddings."""
        token_embeddings = model_output[0]
        input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
        return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
            input_mask_expanded.sum(1), min=1e-9
        )

    # --------------------------
    # Text Encoder
    # --------------------------
    def encode(self, texts: List[str]) -> np.ndarray:
        """Encode text into normalized embeddings."""
        with torch.no_grad():
            encoded_input = self.tokenizer(
                texts, padding=True, truncation=True, max_length=60, return_tensors="pt"
            ).to(self.device)

            model_output = self.model(**encoded_input)
            embeddings = self.mean_pooling(model_output, encoded_input["attention_mask"])
            embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
            return embeddings.cpu().numpy()

    # --------------------------
    # Pinecone Search
    # --------------------------
    def search(self, query: str, top_k: int = 5) -> List[Dict]:
        """Search Pinecone index."""
        query_vector = self.encode([query])[0]

        results = self.pinecone_index.query(
            namespace=self.pinecone_namespace,
            vector=query_vector.tolist(),
            top_k=top_k,
            include_metadata=True,
            include_values=False,
        )

        docs = []
        for i, match in enumerate(results["matches"]):
            metadata = match["metadata"]
            text = metadata.get("text")
            docs.append({
                "Rank": i + 1,
                "Score": f"{match['score']:.2f}",
                "Document": text,
                "Snomed_id": metadata.get("concept_id")
            })

        return docs


# =========================
# Instantiate Retriever
# =========================
MODEL_NAME = "ekacare/parrotlet-e"
retriever = ParrotletRetriever(MODEL_NAME)


def retrieve_documents(query: str, top_k: int = 5):
    """Perform retrieval and return results."""
    if not query.strip():
        return pd.DataFrame(), "Please enter a valid query."

    try:
        results = retriever.search(query, top_k)
        if not results:
            return pd.DataFrame(), "No results found."

        df = pd.DataFrame(results)
        status = f"✅ Retrieved top {len(results)} documents."
        return df

    except Exception as e:
        return pd.DataFrame(), f"⚠️ Error: {str(e)}"


# =========================
# Gradio Interface (VERTICAL)
# =========================
SAMPLE_QUERIES = [
    "takhne me dard",
    "ghotyalu dard",
    "ghera aana",
    "vayiru vali",
    "छाती में दर्द",
    "talenovu",
    "వాంతులు"
    "ಕಾಮಲೆ", # jaundice
    "பேசுவது சிரமம்", # Dysphasia 
    "Peshab Kartaana Jalan", # Scalding pain on urination
    "Kurunnal",
    "sunn hua",
    "moochithinaral",
    "মাথাব্যথা"
]

with gr.Blocks(title="Parrotlet-e Retrieval", theme=gr.themes.Base()) as demo:
#     gr.Markdown(
#         """
#         # **Multilingual Embedding Retrieval powered by EkaCare’s Parrotlet-e — the Indic Medical Entity Embedding Model.**  
# Parrotlet-e is a multilingual embedding model built to understand and represent medical terminology across India’s diverse languages and scripts, enabling seamless search and interoperability in healthcare data.

# - 🔗 **Model on Hugging Face:** [Parrotlet-e](https://huggingface.co/ekacare/parrotlet-e)  
# - 📊 **Benchmarked on:** [Eka-IndicMTEB](https://huggingface.co/datasets/ekacare/Eka-IndicMTEB)  
# - 📰 **Read more on our blog:** [Introducing Parrotlet-e and Eka-IndicMTEB — Bridging India’s Multilingual Healthcare Gap](https://info.eka.care/services/introducing-parrotlet-e-and-eka-indicmteb-bridging-indias-multilingual-healthcare-gap)
#     """)
    gr.Markdown(
    """
    <div style="text-align: center; margin-top: 10px; margin-bottom: 15px;">
        <h2 style="color:#1f2937; font-size: 26px; margin-bottom: 6px;">
            🦜 <b>Parrotlet-e</b> — Indic Medical Entity Embedding Model
        </h2>
        <p style="font-size:16px; color:#4b5563; max-width:700px; margin: 0 auto;">
            A multilingual embedding model designed to represent Indian medical terminology across diverse languages and scripts — 
            enabling seamless medical search, interoperability, and data understanding across India’s healthcare ecosystem.
        </p>
    </div>

    <div style="text-align: left; margin-top: 15px; font-size:15px;">
        <ul style="list-style: none; padding-left: 0;">
            <li>🔗 <b>Model on Hugging Face:</b> 
                <a href="https://huggingface.co/ekacare/parrotlet-e" target="_blank" style="color:#2563eb;">Parrotlet-e</a>
            </li>
            <li>📊 <b>Benchmarked on:</b> 
                <a href="https://huggingface.co/datasets/ekacare/Eka-IndicMTEB" target="_blank" style="color:#2563eb;">Eka-IndicMTEB</a>
            </li>
            <li>📰 <b>Read more on our blog:</b> 
                <a href="https://info.eka.care/services/introducing-parrotlet-e-and-eka-indicmteb-bridging-indias-multilingual-healthcare-gap" 
                target="_blank" style="color:#2563eb;">
                Introducing Parrotlet-e and Eka-IndicMTEB — Bridging India’s Multilingual Healthcare Gap
                </a>
            </li>
        </ul>
    </div>

    <hr style="margin-top:25px; margin-bottom:10px;">
    """
)


    # ---- Input Section ----
    with gr.Group():
        query_input = gr.Textbox(
            label="Enter a medical term (not sentences in any language)",
            placeholder="Type your query here...",
            lines=1,
        )

        examples = gr.Examples(
            examples=SAMPLE_QUERIES,
            inputs=query_input,
            label="Example Queries",
            examples_per_page=len(SAMPLE_QUERIES)
        )

        top_k_input = gr.Number(
            label="Number of results (K)",
            value=5,
            precision=0,
            interactive=True
        )

        search_btn = gr.Button("retrieve", variant="primary")

    # ---- Output Section ----
    with gr.Group():
        results_output = gr.Dataframe(
            headers=["Rank", "Score", "Term", "Snomed_id"],
            datatype=["number", "str", "str", "str"],
            interactive=False,
            wrap=True,
            label="Search Results"
        )
        # status_box = gr.Textbox(label="Status", interactive=False)

    # ---- Function Binding ----
    search_btn.click(
        fn=retrieve_documents,
        inputs=[query_input, top_k_input],
        outputs=[results_output],
    )


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