File size: 13,858 Bytes
f9b063b
 
 
 
8b0cc53
 
 
 
 
 
 
 
 
 
f9b063b
4a784da
f9b063b
 
8b0cc53
 
 
f9b063b
4a784da
 
 
 
 
f9b063b
 
4a784da
 
 
f9b063b
8b0cc53
f9b063b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b0cc53
f9b063b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b0cc53
 
 
f9b063b
8b0cc53
 
 
f9b063b
f129974
 
e581b39
f129974
f9b063b
8b0cc53
69dd8d4
 
 
 
 
 
 
e7f8388
8b0cc53
f9b063b
 
 
 
8b0cc53
 
 
f9b063b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b0cc53
 
 
 
 
69dd8d4
8b0cc53
f9b063b
f129974
 
 
 
8b0cc53
 
 
 
 
 
 
 
 
f129974
 
8b0cc53
 
 
 
 
 
 
f129974
 
 
f9b063b
 
 
 
 
 
 
 
8b0cc53
f9b063b
 
 
 
8b0cc53
 
 
 
 
 
 
f9b063b
8b0cc53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9b063b
 
 
 
8b0cc53
f9b063b
 
8b0cc53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9b063b
 
 
8b0cc53
 
 
 
 
 
 
 
 
 
 
 
f9b063b
 
 
8b0cc53
 
 
 
 
 
 
 
 
f9b063b
8b0cc53
 
 
 
 
 
 
 
 
f9b063b
 
 
8b0cc53
 
 
 
 
 
f9b063b
 
 
 
8b0cc53
69dd8d4
 
 
 
 
 
 
 
f129974
 
f9b063b
 
 
 
8b0cc53
 
 
 
 
 
 
 
94b0814
 
8b0cc53
 
 
 
 
 
 
 
 
 
 
94b0814
 
8b0cc53
 
 
 
 
 
 
 
 
 
 
69dd8d4
 
8b0cc53
 
 
f9b063b
 
8b0cc53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9b063b
 
8b0cc53
 
 
 
 
 
f129974
 
8b0cc53
 
 
f129974
f9b063b
8b0cc53
 
 
 
 
 
 
 
 
 
 
 
 
 
f9b063b
 
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
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
import gradio as gr
import pandas as pd
import numpy as np
import os
from utils import (
    plot_distances_tsne,
    plot_distances_umap,
    cluster_languages_hdbscan,
    cluster_languages_kmeans,
    plot_mst,
    cluster_languages_by_families,
    cluster_languages_by_subfamilies,
    filter_languages_by_families,
)
from functools import partial
import datasets


dataset = datasets.load_dataset(
    "mshamrai/language-metric-data", split="train", trust_remote_code=True
)

languages = dataset["languages_list"][0]
average_distances_matrix = np.array(dataset["average_distances_matrix"][0])

DATASETS = dataset["distances_matrices"][0]["dataset_name"]
MODELS = dataset["distances_matrices"][0]["models"][0]["model_name"]

distance_matrices = {
    DATASETS[i]: {
        MODELS[j]: np.array(dataset["distances_matrices"][0]["models"][i]["matrix"][j])
        for j in range(len(MODELS))
    }
    for i in range(len(DATASETS))
}


def filter_languages_nan(model, dataset, use_average):
    if use_average:
        matrix = average_distances_matrix
    else:
        matrix = distance_matrices[dataset][model]

    vector = matrix[0]
    updated_languages = np.array(languages)[~np.isnan(vector)]
    updated_matrix = matrix[~np.isnan(vector), :][:, ~np.isnan(vector)]

    return updated_matrix, updated_languages


def get_similar_languages(model, dataset, selected_language, use_average, n):
    """
    Retrieves the distances for the selected language from the chosen model and dataset,
    sorts them by similarity (lowest distance first), and returns a DataFrame.
    """
    if use_average:
        matrix = average_distances_matrix
    else:
        matrix = distance_matrices[dataset][model]
    selected_language_index = languages.index(selected_language)
    distances = matrix[selected_language_index]
    df = pd.DataFrame({"Language": languages, "Distance": distances})
    sorted_distances = df.sort_values(by="Distance")
    sorted_distances.drop(index=selected_language_index, inplace=True)
    sorted_distances.reset_index(drop=True, inplace=True)
    sorted_distances.reset_index(inplace=True)
    sorted_distances["Distance"] = sorted_distances["Distance"].round(4)
    return sorted_distances.head(n)


def update_languages(model, dataset):
    """
    Returns the language list based on the given model and dataset.
    """
    matrix = distance_matrices[dataset][model]
    vector = matrix[0]
    updated_languages = np.array(languages)[~np.isnan(vector)]
    return list(updated_languages)


def update_language_options(model, dataset, language, use_average):
    if use_average:
        updated_languages = languages
    else:
        updated_languages = update_languages(model, dataset)
    if language not in updated_languages:
        language = updated_languages[0]
    return gr.Dropdown(label="Language", choices=updated_languages, value=language)


def toggle_inputs(use_average):
    if use_average:
        return gr.update(interactive=False, visible=False), gr.update(
            interactive=False, visible=False
        )
    else:
        return gr.update(interactive=True, visible=True), gr.update(
            interactive=True, visible=True
        )


plot_path = "plots/last_plot.pdf"
os.makedirs("plots", exist_ok=True)


def plot_distances(
    model,
    dataset,
    use_average,
    cluster_method,
    cluster_method_param,
    figsize_h,
    figsize_w,
    plot_fn,
):
    """
    Plots all languages from the distances matrix using t-SNE.
    """

    updated_matrix, updated_languages = filter_languages_nan(
        model, dataset, use_average
    )

    if cluster_method == "HDBSCAN":
        filtered_matrix, filtered_languages, clusters = cluster_languages_hdbscan(
            updated_matrix, updated_languages, min_cluster_size=cluster_method_param
        )
        legends = None
    elif cluster_method == "KMeans":
        filtered_matrix, filtered_languages, clusters = cluster_languages_kmeans(
            updated_matrix, updated_languages, n_clusters=cluster_method_param
        )
        legends = None
    elif cluster_method == "Family":
        clusters, legends = cluster_languages_by_families(updated_languages)
        filtered_matrix = updated_matrix
        filtered_languages = updated_languages
    elif cluster_method == "Subfamily":
        clusters, legends = cluster_languages_by_subfamilies(updated_languages)
        filtered_matrix = updated_matrix
        filtered_languages = updated_languages
    else:
        raise ValueError("Invalid cluster method")

    fig = plot_fn(
        filtered_matrix,
        filtered_languages,
        clusters,
        legends,
        fig_size=(figsize_w, figsize_h),
    )
    fig.tight_layout()
    fig.savefig(plot_path, format="pdf")
    return fig, gr.DownloadButton(label="Download Plot", value=plot_path)


def plot_families_subfamilies(
    families, model, dataset, use_average, figsize_h, figsize_w
):
    updated_matrix, updated_languages = filter_languages_nan(
        model, dataset, use_average
    )
    updated_matrix, updated_languages = filter_languages_by_families(
        updated_matrix, updated_languages, families
    )

    clusters, legends = cluster_languages_by_subfamilies(updated_languages)
    fig = plot_mst(
        updated_matrix,
        updated_languages,
        clusters,
        legends,
        fig_size=(figsize_w, figsize_h),
    )
    fig.tight_layout()
    fig.savefig(plot_path, format="pdf")
    return fig, gr.DownloadButton(label="Download Plot", value=plot_path)


with gr.Blocks() as demo:
    gr.Markdown("## Language Distance Explorer")
    average_checkbox = gr.Checkbox(label="Use Average Distances", value=False)
    with gr.Row():
        model_input = gr.Dropdown(label="Model", choices=MODELS, value=MODELS[0])
        dataset_input = gr.Dropdown(
            label="Dataset", choices=DATASETS, value=DATASETS[0]
        )

    with gr.Tab(label="Closest Languages Table"):
        with gr.Row():
            language_input = gr.Dropdown(
                label="Language", choices=languages, value=languages[0]
            )
            top_n_input = gr.Slider(
                label="Top N", minimum=1, maximum=30, step=1, value=10
            )

        output_table = gr.Dataframe(label="Similar Languages")

        model_input.change(
            fn=update_language_options,
            inputs=[model_input, dataset_input, language_input, average_checkbox],
            outputs=language_input,
        )
        dataset_input.change(
            fn=update_language_options,
            inputs=[model_input, dataset_input, language_input, average_checkbox],
            outputs=language_input,
        )
        language_input.change(
            fn=get_similar_languages,
            inputs=[
                model_input,
                dataset_input,
                language_input,
                average_checkbox,
                top_n_input,
            ],
            outputs=output_table,
        )
        model_input.change(
            fn=get_similar_languages,
            inputs=[
                model_input,
                dataset_input,
                language_input,
                average_checkbox,
                top_n_input,
            ],
            outputs=output_table,
        )
        dataset_input.change(
            fn=get_similar_languages,
            inputs=[
                model_input,
                dataset_input,
                language_input,
                average_checkbox,
                top_n_input,
            ],
            outputs=output_table,
        )
        top_n_input.change(
            fn=get_similar_languages,
            inputs=[
                model_input,
                dataset_input,
                language_input,
                average_checkbox,
                top_n_input,
            ],
            outputs=output_table,
        )

        average_checkbox.change(
            fn=toggle_inputs,
            inputs=[average_checkbox],
            outputs=[model_input, dataset_input],
        )

        average_checkbox.change(
            fn=update_language_options,
            inputs=[model_input, dataset_input, language_input, average_checkbox],
            outputs=language_input,
        )
        average_checkbox.change(
            fn=get_similar_languages,
            inputs=[
                model_input,
                dataset_input,
                language_input,
                average_checkbox,
                top_n_input,
            ],
            outputs=output_table,
        )

    with gr.Tab(label="Distance Plot"):
        with gr.Row():
            cluster_method_input = gr.Dropdown(
                label="Cluster Method",
                choices=["HDBSCAN", "KMeans", "Family", "Subfamily"],
                value="HDBSCAN",
            )
            clusters_input = gr.Slider(
                label="Minimum Elements in a Cluster",
                minimum=2,
                maximum=10,
                step=1,
                value=2,
            )

        def update_clusters_input_option(cluster_method):
            if cluster_method == "HDBSCAN":
                return gr.Slider(
                    label="Minimum Elements in a Cluster",
                    minimum=2,
                    maximum=10,
                    step=1,
                    value=2,
                    visible=True,
                    interactive=True,
                )
            elif cluster_method == "KMeans":
                return gr.Slider(
                    label="Number of Clusters",
                    minimum=2,
                    maximum=20,
                    step=1,
                    value=2,
                    visible=True,
                    interactive=True,
                )
            else:
                return gr.update(interactive=False, visible=False)

        cluster_method_input.change(
            fn=update_clusters_input_option,
            inputs=[cluster_method_input],
            outputs=clusters_input,
        )

        with gr.Row():
            plot_tsne_button = gr.Button("Plot t-SNE")
            plot_umap_button = gr.Button("Plot UMAP")
            plot_mst_button = gr.Button("Plot MST")

        with gr.Row():
            plot_figsize_dist_h_input = gr.Slider(
                label="Figure Height", minimum=5, maximum=30, step=1, value=15
            )
            plot_figsize_dist_w_input = gr.Slider(
                label="Figure Width", minimum=5, maximum=30, step=1, value=15
            )

        with gr.Row():
            download_plot_button = gr.DownloadButton("Download Plot")

        with gr.Row():
            plot_output = gr.Plot(label="Distance Plot")

        plot_tsne_button.click(
            fn=partial(plot_distances, plot_fn=plot_distances_tsne),
            inputs=[
                model_input,
                dataset_input,
                average_checkbox,
                cluster_method_input,
                clusters_input,
                plot_figsize_dist_h_input,
                plot_figsize_dist_w_input,
            ],
            outputs=[plot_output, download_plot_button],
        )
        plot_umap_button.click(
            fn=partial(plot_distances, plot_fn=plot_distances_umap),
            inputs=[
                model_input,
                dataset_input,
                average_checkbox,
                cluster_method_input,
                clusters_input,
                plot_figsize_dist_h_input,
                plot_figsize_dist_w_input,
            ],
            outputs=[plot_output, download_plot_button],
        )
        plot_mst_button.click(
            fn=partial(plot_distances, plot_fn=plot_mst),
            inputs=[
                model_input,
                dataset_input,
                average_checkbox,
                cluster_method_input,
                clusters_input,
                plot_figsize_dist_h_input,
                plot_figsize_dist_w_input,
            ],
            outputs=[plot_output, download_plot_button],
        )

    with gr.Tab(label="Language Families Subplot"):

        checked_families_input = gr.CheckboxGroup(
            label="Language Families",
            choices=[
                "Afroasiatic",
                "Austroasiatic",
                "Austronesian",
                "Constructed",
                "Creole",
                "Dravidian",
                "Germanic",
                "Indo-European",
                "Japonic",
                "Kartvelian",
                "Koreanic",
                "Language Isolate",
                "Niger-Congo",
                "Northeast Caucasian",
                "Romance",
                "Sino-Tibetan",
                "Turkic",
                "Uralic",
            ],
            value=["Indo-European"],
        )
        with gr.Row():
            plot_family_button = gr.Button("Plot Families")
            plot_figsize_h_input = gr.Slider(
                label="Figure Height", minimum=5, maximum=30, step=1, value=15
            )
            plot_figsize_w_input = gr.Slider(
                label="Figure Width", minimum=5, maximum=30, step=1, value=15
            )

        with gr.Row():
            download_families_plot_button = gr.DownloadButton(
                "Download Plot", value=plot_path
            )

        plot_family_output = gr.Plot(label="Families Plot")

        plot_family_button.click(
            fn=plot_families_subfamilies,
            inputs=[
                checked_families_input,
                model_input,
                dataset_input,
                average_checkbox,
                plot_figsize_h_input,
                plot_figsize_w_input,
            ],
            outputs=[plot_family_output, download_families_plot_button],
        )


demo.launch(share=True)