File size: 9,467 Bytes
a50a91d
 
 
 
 
 
 
 
 
 
 
 
 
 
7a06b89
a50a91d
 
 
 
 
 
243e89b
 
a50a91d
 
 
243e89b
 
 
a50a91d
 
 
 
669fa24
a50a91d
 
 
243e89b
 
 
 
a50a91d
 
 
 
 
 
 
 
7a06b89
a50a91d
 
7a06b89
a50a91d
 
 
 
 
 
7a06b89
 
a50a91d
 
 
243e89b
a50a91d
 
7a06b89
a50a91d
7a06b89
a50a91d
 
 
7a06b89
a50a91d
 
 
 
 
 
 
7a06b89
a50a91d
 
 
7a06b89
 
 
a50a91d
 
 
 
 
7a06b89
a50a91d
 
 
7a06b89
a50a91d
 
 
 
 
7a06b89
a50a91d
 
 
 
7a06b89
a50a91d
 
 
7a06b89
 
 
a50a91d
7a06b89
a50a91d
 
243e89b
 
a50a91d
 
7a06b89
243e89b
7a06b89
243e89b
a50a91d
 
7a06b89
a50a91d
7a06b89
a50a91d
 
 
7a06b89
a50a91d
243e89b
 
 
 
 
 
 
 
 
 
 
 
 
 
7a06b89
243e89b
 
 
 
 
 
 
 
 
 
 
7a06b89
a50a91d
 
 
 
 
7a06b89
a50a91d
 
 
 
7a06b89
a50a91d
 
 
 
 
7a06b89
243e89b
 
 
 
7a06b89
a50a91d
 
243e89b
7a06b89
243e89b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a06b89
243e89b
 
 
 
 
 
7a06b89
a50a91d
 
 
 
 
7a06b89
a50a91d
 
 
 
 
7a06b89
243e89b
 
 
 
7a06b89
a50a91d
 
 
7a06b89
a50a91d
243e89b
 
 
 
 
 
7a06b89
243e89b
 
 
 
 
 
 
7a06b89
a50a91d
 
 
 
 
7a06b89
a50a91d
 
243e89b
 
a50a91d
 
 
 
7a06b89
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
#!/usr/bin/env python3
"""
Kabyle Semantic Toolkit
Hugging Face Space using boffire/kabyle-sentence-transformer-mpnet
"""

import warnings
warnings.filterwarnings("ignore")
import gradio as gr
import torch
import numpy as np
import pandas as pd
from sentence_transformers import SentenceTransformer
import torch.nn.functional as F
import os

# Load model once
print("Loading model...")
MODEL = SentenceTransformer("boffire/kabyle-sentence-transformer-mpnet")
print("Model loaded")

# Pre-load and pre-compute search index at startup
print("Pre-computing search index...")
try:
    from datasets import load_dataset
    ds = load_dataset("Imsidag-community/english-kabyle-parallel", split="train")
    SEARCH_PAIRS = [(row["en"], row["kab"]) for row in ds.select(range(min(500, len(ds))))]
except Exception as e:
    print("Could not load dataset, using fallback: " + str(e))
    SEARCH_PAIRS = [
        ("Hello!", "Azul!"),
        ("How are you?", "Amek i telliḍ?"),
        ("Thank you", "Tanemmirt"),
        ("Good morning", "Tifawin"),
        ("Water is life", "Aman d tudert"),
    ]

# Pre-compute embeddings once at startup
_all_texts = [en for en, _ in SEARCH_PAIRS] + [kab for _, kab in SEARCH_PAIRS]
SEARCH_EMBEDDINGS = MODEL.encode(_all_texts, convert_to_tensor=True, show_progress_bar=False)
print("Search index ready: " + str(len(SEARCH_PAIRS)) + " pairs")

def get_embeddings(texts):
    return MODEL.encode(texts, convert_to_tensor=True)

def check_quality(en_text, kab_text):
    """Tab 1: Translation Quality Checker"""
    if not en_text.strip() or not kab_text.strip():
        return "Please enter both sentences", None
    
    emb = get_embeddings([en_text, kab_text])
    sim = F.cosine_similarity(emb[0].unsqueeze(0), emb[1].unsqueeze(0)).item()
    
    if sim > 0.85:
        quality = "Excellent match"
    elif sim > 0.6:
        quality = "Good match"
    else:
        quality = "Poor match"
    
    result = "Similarity: " + str(round(sim, 4)) + os.linesep + "Quality: " + quality
    return result, sim

def search_similar(query, top_k=5):
    """Tab 2: Semantic Search - fast because embeddings are pre-computed"""
    if not query.strip():
        return "Please enter a query"
    
    query_emb = get_embeddings([query])
    
    # Search both English and Kabyle sides
    scores = F.cosine_similarity(query_emb, SEARCH_EMBEDDINGS).cpu().numpy()
    top_indices = np.argsort(scores)[::-1][:top_k]
    
    results = []
    seen = set()
    for idx in top_indices:
        if idx < len(SEARCH_PAIRS):
            pair = SEARCH_PAIRS[idx]
        else:
            pair = SEARCH_PAIRS[idx - len(SEARCH_PAIRS)]
        
        key = pair[0] + " || " + pair[1]
        if key not in seen:
            seen.add(key)
            results.append(pair[1] + os.linesep + "  (EN: " + pair[0] + ") -- Score: " + str(round(scores[idx], 4)))
    
    return (os.linesep + os.linesep).join(results) if results else "No results found"

def validate_csv(file):
    """Tab 3: Parallel Data Validator"""
    if file is None:
        return None, "Please upload a CSV file with 'en' and 'kab' columns"
    
    df = pd.read_csv(file.name)
    if "en" not in df.columns or "kab" not in df.columns:
        return None, "CSV must have 'en' and 'kab' columns"
    
    scores = []
    for _, row in df.iterrows():
        emb = get_embeddings([str(row["en"]), str(row["kab"])])
        sim = F.cosine_similarity(emb[0].unsqueeze(0), emb[1].unsqueeze(0)).item()
        scores.append(sim)
    
    df["similarity"] = scores
    df["quality"] = df["similarity"].apply(
        lambda s: "good" if s > 0.6 else "poor"
    )
    
    # Save result
    output_path = "/tmp/validated_pairs.csv"
    df.to_csv(output_path, index=False)
    
    summary = "Processed " + str(len(df)) + " pairs" + os.linesep
    summary += "Good quality: " + str(len(df[df["quality"]=="good"])) + os.linesep
    summary += "Poor quality: " + str(len(df[df["quality"]=="poor"]))
    
    return output_path, summary

# Build UI with Soft theme
with gr.Blocks(title="Kabyle Semantic Toolkit", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # Kabyle Semantic Toolkit
    
    Powered by [**boffire/kabyle-sentence-transformer-mpnet**](https://huggingface.co/boffire/kabyle-sentence-transformer-mpnet)
    
    This tool understands meaning, not just words. Use it to check translations,
    find similar sentences, or validate your parallel data.
    """)
    
    with gr.Tabs():
        
        # Tab 1: Quality Checker
        with gr.TabItem("Translation Quality"):
            gr.Markdown("Check if an English-Kabyle pair has similar meaning.")
            
            with gr.Row():
                with gr.Column(scale=2):
                    en_input = gr.Textbox(
                        label="English",
                        placeholder="Enter English text...",
                        lines=3
                    )
                    kab_input = gr.Textbox(
                        label="Kabyle",
                        placeholder="Enter Kabyle text...",
                        lines=3
                    )
                    with gr.Row():
                        clear_btn_1 = gr.Button("Clear", variant="secondary")
                        check_btn = gr.Button("Check Quality", variant="primary")
                
                with gr.Column(scale=3):
                    result_text = gr.Textbox(
                        label="Result",
                        lines=3,
                        interactive=False
                    )
                    score_bar = gr.Slider(
                        0, 1,
                        label="Similarity Score",
                        interactive=False
                    )
            
            check_btn.click(
                fn=check_quality,
                inputs=[en_input, kab_input],
                outputs=[result_text, score_bar]
            )
            
            gr.Examples(
                examples=[
                    ["Hello!", "Azul!"],
                    ["The computer works.", "Aselkim iteddu."],
                    ["I love you.", "Hemmleɣ-kent."],
                    ["Hello!", "Aselkim iteddu."],
                ],
                inputs=[en_input, kab_input],
                label="Try these examples"
            )
            
            clear_btn_1.click(
                fn=lambda: ("", "", "", None),
                outputs=[en_input, kab_input, result_text, score_bar]
            )
        
        # Tab 2: Similar Search
        with gr.TabItem("Similar Sentences"):
            gr.Markdown("Find Kabyle sentences similar to your query. Search index is pre-loaded for instant results.")
            
            with gr.Row():
                with gr.Column(scale=2):
                    query_input = gr.Textbox(
                        label="Query (English or Kabyle)",
                        placeholder="Enter text to search...",
                        lines=3
                    )
                    top_k_slider = gr.Slider(
                        1, 10,
                        value=5,
                        step=1,
                        label="Number of results"
                    )
                    with gr.Row():
                        clear_btn_2 = gr.Button("Clear", variant="secondary")
                        search_btn = gr.Button("Search", variant="primary")
                
                with gr.Column(scale=3):
                    search_output = gr.Textbox(
                        label="Results",
                        lines=10,
                        interactive=False
                    )
            
            search_btn.click(
                fn=search_similar,
                inputs=[query_input, top_k_slider],
                outputs=search_output
            )
            
            gr.Examples(
                examples=["How are you?", "Thank you", "Water is life"],
                inputs=query_input,
                label="Example queries"
            )
            
            clear_btn_2.click(
                fn=lambda: ("", 5, ""),
                outputs=[query_input, top_k_slider, search_output]
            )
        
        # Tab 3: Data Validator
        with gr.TabItem("Data Validator"):
            gr.Markdown("Upload a CSV with 'en' and 'kab' columns to validate alignment quality.")
            
            with gr.Row():
                with gr.Column(scale=2):
                    file_input = gr.File(
                        label="Upload CSV",
                        file_types=[".csv"]
                    )
                    validate_btn = gr.Button("Validate", variant="primary")
                
                with gr.Column(scale=3):
                    summary_output = gr.Textbox(
                        label="Summary",
                        lines=4,
                        interactive=False
                    )
                    download_output = gr.File(label="Download Results")
            
            validate_btn.click(
                fn=validate_csv,
                inputs=file_input,
                outputs=[download_output, summary_output]
            )
    
    gr.Markdown("""
    ---
    **Related tools**:
    [LibreTranslate](https://imsidag-community-libretranslate-kabyle.hf.space/) |
    [MarianMT](https://huggingface.co/boffire/marianmt-en-kab)
    """)

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