File size: 9,474 Bytes
37a3be7
 
 
 
 
0d1d7d7
 
 
 
a3c9a3f
0d1d7d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3c9a3f
 
 
 
 
0d1d7d7
 
 
 
 
 
 
 
a3c9a3f
 
 
0d1d7d7
 
 
a3c9a3f
 
 
0d1d7d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3c9a3f
0d1d7d7
a3c9a3f
 
 
 
 
 
 
 
 
0d1d7d7
a3c9a3f
 
0d1d7d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3c9a3f
0d1d7d7
 
 
 
 
 
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
import subprocess
import sys

subprocess.check_call([sys.executable, "-m", "pip", "install", "-U", "transformers==4.56.2"])

import logging
from typing import List, Dict, Tuple
import gradio as gr
from pylate import indexes, models, retrieve
from documents import MULTILINGUAL_DOCUMENTS

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


class CrossLingualRetriever:
    """Cross-lingual retrieval system using LiquidAI's LFM2-ColBERT model."""
    
    def __init__(self, model_name: str = "LiquidAI/LFM2-ColBERT-350M-RC"):
        """Initialize the retriever with model and index."""
        logger.info(f"Loading model: {model_name}")
        
        self.model = models.ColBERT(model_name_or_path=model_name)
        
        # Set padding token if not present
        if self.model.tokenizer.pad_token is None and hasattr(self.model.tokenizer, "eos_token"):
            self.model.tokenizer.pad_token = self.model.tokenizer.eos_token
        
        # Initialize PLAID index
        self.index = indexes.PLAID(
            index_folder="pylate-index",
            index_name="cross_lingual_index",
            override=True,
        )
        
        self.retriever = retrieve.ColBERT(index=self.index)
        self.documents_data = []
        
        logger.info("Model and index initialized successfully")
    
    def load_documents(self, documents: List[Dict[str, str]]) -> None:
        """Load and index multilingual documents."""
        logger.info(f"Loading {len(documents)} documents")
        
        self.documents_data = documents
        documents_ids = [doc["id"] for doc in documents]
        documents_text = [doc["text"] for doc in documents]
        
        # Encode documents
        documents_embeddings = self.model.encode(
            documents_text,
            batch_size=32,
            is_query=False,
            show_progress_bar=True,
        )
        
        # Add to index
        self.index.add_documents(
            documents_ids=documents_ids,
            documents_embeddings=documents_embeddings,
        )
        
        logger.info("Documents indexed successfully")
    
    def search(self, query: str, k: int = 5) -> List[Dict]:
        """Perform cross-lingual search."""
        logger.info(f"Searching for: {query}")
        
        # Encode query
        query_embedding = self.model.encode(
            [query],
            batch_size=32,
            is_query=True,
            show_progress_bar=False,
        )
        
        # Retrieve results
        scores = self.retriever.retrieve(
            queries_embeddings=query_embedding,
            k=k,
        )
        
        # Format results
        results = []
        for score in scores[0]:
            doc = next((d for d in self.documents_data if d["id"] == score["id"]), None)
            if doc:
                results.append({
                    "id": score["id"],
                    "score": round(score["score"], 4),
                    "text": doc["text"],
                    "language": doc["language"],
                    "title": doc["title"]
                })
        
        return results


# Initialize retriever and load documents
retriever = CrossLingualRetriever()
retriever.load_documents(MULTILINGUAL_DOCUMENTS)


def format_results(results: List[Dict]) -> str:
    """Format search results as HTML for better visualization."""
    if not results:
        return "<div style='padding: 20px; text-align: center; color: #666;'>No results found</div>"
    
    html = "<div style='font-family: Arial, sans-serif;'>"
    
    for i, result in enumerate(results, 1):
        score_color = "#22c55e" if result["score"] > 30 else "#eab308" if result["score"] > 20 else "#ef4444"
        
        html += f"""
        <div style='margin-bottom: 20px; padding: 15px; border: 1px solid #e5e7eb; border-radius: 8px; background: #f9fafb;'>
            <div style='display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;'>
                <div>
                    <span style='font-weight: bold; font-size: 16px;'>#{i} {result["title"]}</span>
                    <span style='margin-left: 10px; padding: 2px 8px; background: #dbeafe; color: #1e40af; border-radius: 4px; font-size: 12px;'>{result["language"]}</span>
                </div>
                <span style='padding: 4px 12px; background: {score_color}; color: white; border-radius: 4px; font-weight: bold;'>
                    Score: {result["score"]}
                </span>
            </div>
            <div style='color: #374151; line-height: 1.6;'>
                {result["text"]}
            </div>
        </div>
        """
    
    html += "</div>"
    return html


def search_documents(query: str, top_k: int) -> Tuple[str, str]:
    """Search documents and return formatted results."""
    if not query.strip():
        return "", "Please enter a search query."
    
    try:
        results = retriever.search(query, k=min(top_k, 10))
        formatted_results = format_results(results)
        
        # Create summary
        if results:
            languages_found = set(r["language"] for r in results)
            summary = f"โœ… Found {len(results)} relevant documents across {len(languages_found)} language(s): {', '.join(sorted(languages_found))}"
        else:
            summary = "โŒ No relevant documents found."
        
        return formatted_results, summary
    
    except Exception as e:
        logger.error(f"Search error: {e}")
        return "", f"โŒ Error during search: {str(e)}"


# Example queries in different languages
EXAMPLE_QUERIES = [
    ["What is artificial intelligence?", 5],
    ["ยฟQuรฉ es el cambio climรกtico?", 5],
    ["์–‘์ž ์ปดํ“จํŒ…์ด๋ž€ ๋ฌด์—‡์ธ๊ฐ€์š”?", 5],
    ["ู…ุง ู‡ูŠ ุงู„ุตุญุฉ ุงู„ู†ูุณูŠุฉุŸ", 5],
    ["้‡ๅญ่ฎก็ฎ—ๆ˜ฏไป€ไนˆ๏ผŸ", 5],
    ["Qu'est-ce que l'รฉconomie numรฉrique?", 5],
    ["ๅฎ‡ๅฎ™ๆŽขๆŸปใซใคใ„ใฆๆ•™ใˆใฆใใ ใ•ใ„", 5],
]


# Build Gradio interface
with gr.Blocks(title="Cross-Lingual Retrieval Demo", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # ๐ŸŒ Cross-Lingual Document Retrieval
        ### Powered by [LiquidAI/LFM2-ColBERT-350M](https://huggingface.co/LiquidAI/LFM2-ColBERT-350M)
        
        Search for documents in any language using queries in any language!
        
        The model finds semantically similar documents regardless of the language mismatch.
        
        **Supported Languages:** English, Arabic, Chinese, French, German, Japanese, Korean, and Spanish
        
        **Topics:** AI, Climate, Energy, Health, Business, Education, Culture, Space Exploration, and more!
        """
    )
    
    with gr.Row():
        with gr.Column(scale=2):
            query_input = gr.Textbox(
                label="๐Ÿ” Enter your query (in any language)",
                placeholder="E.g., 'artificial intelligence', 'cambio climรกtico', 'energie renouvelable'...",
                lines=2
            )
            
            top_k_slider = gr.Slider(
                minimum=1,
                maximum=10,
                value=5,
                step=1,
                label="Number of results to retrieve",
            )
            
            search_btn = gr.Button("Search", variant="primary", size="lg")
        
        with gr.Column(scale=1):
            gr.Markdown(
                """
                ### ๐Ÿ“š Document Corpus
                
                **30+ documents** covering:
                - ๐Ÿค– **Technology**: AI, Quantum Computing
                - ๐ŸŒ **Environment**: Climate, Biodiversity
                - โšก **Energy**: Renewable Sources
                - ๐Ÿฅ **Health**: Medicine, Mental Wellness
                - ๐Ÿ’ผ **Business**: Digital Economy, Startups
                - ๐Ÿ“– **Education**: Online Learning
                - ๐ŸŽญ **Culture**: Global Connectivity
                - ๐Ÿš€ **Science**: Space Exploration
                
                **Languages:**  
                ๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿ‡ช๐Ÿ‡ธ ๐Ÿ‡ซ๐Ÿ‡ท ๐Ÿ‡ฉ๐Ÿ‡ช ๐Ÿ‡จ๐Ÿ‡ณ ๐Ÿ‡ฏ๐Ÿ‡ต ๐Ÿ‡ธ๐Ÿ‡ฆ ๐Ÿ‡ฐ๐Ÿ‡ท
                """
            )
    
    summary_output = gr.Textbox(
        label="๐Ÿ“Š Search Summary",
        interactive=False,
        lines=2
    )
    
    results_output = gr.HTML(
        label="๐ŸŽฏ Search Results"
    )
    
    # Event handlers
    search_btn.click(
        fn=search_documents,
        inputs=[query_input, top_k_slider],
        outputs=[results_output, summary_output]
    )
    
    query_input.submit(
        fn=search_documents,
        inputs=[query_input, top_k_slider],
        outputs=[results_output, summary_output]
    )
    
    # Examples section
    gr.Markdown("### ๐Ÿ’ก Try these example queries:")
    gr.Examples(
        examples=EXAMPLE_QUERIES,
        inputs=[query_input, top_k_slider],
        outputs=[results_output, summary_output],
        fn=search_documents,
        cache_examples=False,
    )
    
    gr.Markdown(
        """
        ---
        **How it works:** This demo uses the LiquidAI LFM2-ColBERT-350M model with late interaction retrieval. 
        The model encodes both queries and documents into token-level embeddings, enabling fine-grained matching 
        across languages with high speed and accuracy.
        """
    )


if __name__ == "__main__":
    demo.launch()