File size: 15,123 Bytes
d43fb2c
 
 
 
 
 
6a75090
 
d43fb2c
6a75090
d43fb2c
 
 
 
 
 
6a75090
d43fb2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a75090
d43fb2c
 
 
 
 
 
 
 
6a75090
d43fb2c
 
 
 
6a75090
 
 
 
 
f2b528f
6a75090
 
 
 
 
f2b528f
6a75090
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d43fb2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2b528f
d43fb2c
 
6a75090
 
 
f2b528f
d43fb2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a75090
 
 
 
 
 
 
 
 
 
 
d43fb2c
 
 
 
 
6a75090
d43fb2c
 
0741edf
d43fb2c
 
 
 
 
 
6a75090
d43fb2c
 
0741edf
d43fb2c
 
 
6a75090
d43fb2c
 
 
 
 
 
 
 
6a75090
 
 
 
d43fb2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0741edf
 
d43fb2c
 
6a75090
 
 
 
 
 
d43fb2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a75090
 
 
d43fb2c
 
 
6a75090
d43fb2c
 
 
 
 
 
 
f2b528f
 
 
6a75090
d43fb2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
document.addEventListener("DOMContentLoaded", function() {
    const select = document.getElementById('language-family-select');
    const hoverBox = document.getElementById('hover-box');
    const searchBar = document.getElementById('search-bar');
    const depthSelector = document.getElementById('depth-number');
    const tokenizerFilterDiv = document.getElementById('tokenizer-filter');
    const scriptFiltersDiv = document.getElementById('script-filter');
    const showNonGlotlidCheckbox = document.getElementById('show-non-glotlid');
    const clearTokenizersFilter = document.getElementById('clear-tokenizers');
    const clearScriptsFilter = document.getElementById('clear-scripts');
    let nodeToCenter = null;
    let currentTreeData = null;
    let expandedNodes;
    let currentTransform = d3.zoomIdentity; // Save the current zoom and transform
        // Get unique tokenizer names
    let tokenizerNames;
    let scriptNames;
    let color;

    function setExpanded(id, state = true){
        if (state) {
            expandedNodes.add(id)
        }
        else if(expandedNodes.has(id)) {
            expandedNodes.delete(id)
        }
    }

    function addNodeIds(tree){
        function addIdToSubtree(tree, nodeCount = 0){
            tree.id = nodeCount++;
            let tree_subtreeSize = tree.children.length === 0 ? 1 : 0;
            let node = {
                ...tree,
                children: (tree.children || []).map(child => {
                    const [subtree, newCount, subtreeSize] = addIdToSubtree(child, nodeCount);
                    nodeCount = newCount;
                    tree_subtreeSize += subtreeSize;
                    return subtree;
                })
            };
            node.subtreeSize = tree_subtreeSize
            return [node, nodeCount, tree_subtreeSize];
        }
        const [parsedTree, _finalCount] = addIdToSubtree(tree);
        return parsedTree;
    }

    function loadLanguageFamily() {
        const family = select.value;
        fetch(`data/${family}.json`)
            .then(response => response.json())
            .then(data => {
                currentTreeData = addNodeIds(data);
                expandedNodes = new Set([0]);
                updateTokenizerFilter(data);
                updateScriptFilter(data);
                drawVisibleNodes(true);
            });
    }
    loadLanguageFamily();
    select.addEventListener('change', loadLanguageFamily);
    searchBar.addEventListener('input', () => searchNode(searchBar.value));

    depthSelector.addEventListener('change', (_) => drawVisibleNodes());
    showNonGlotlidCheckbox.addEventListener('click', (_) => drawVisibleNodes());
    clearTokenizersFilter.addEventListener('click', (_) => {
        tokenizerFilterDiv.querySelectorAll('input:checked').forEach((a) => a.checked = false);
        drawVisibleNodes();
    })
    clearScriptsFilter.addEventListener('click', (_) => {
        scriptFiltersDiv.querySelectorAll('input:checked').forEach((a) => a.checked = false);
        drawVisibleNodes();
    })

    function getScriptNames(node, namesSet = new Set('x')) {
        if (!node)
            return namesSet;
        if (node.scripts.length > 0) {
            for(const script of node.scripts)
                namesSet.add(script);
        }
        if (node.children) {
            node.children.forEach(child => getScriptNames(child, namesSet));
        }
        return namesSet;
    }

    function updateScriptFilter(data) {
        scriptNames = Array.from(getScriptNames(data));
        scriptFiltersDiv.innerHTML = '';
        scriptNames.forEach(name => {
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = name;
            checkbox.checked = true;
            checkbox.addEventListener('change', () => drawVisibleNodes());
            const label = document.createElement('label');
            label.appendChild(checkbox);
            label.appendChild(document.createTextNode(name));

            scriptFiltersDiv.appendChild(label);
            scriptFiltersDiv.appendChild(document.createElement('br'));
        });
    }

    function updateTokenizerFilter(data) {
        tokenizerNames = Array.from(getTokenizerNames(data));
        // Create color scale based on the unique tokenizer names
        color = d3.scaleOrdinal(tokenizerNames, d3.schemeCategory10);
        tokenizerFilterDiv.innerHTML = '';
        tokenizerNames.forEach(name => {
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = name;
            checkbox.checked = true;
            checkbox.addEventListener('change', () => drawVisibleNodes());
            const label = document.createElement('label');
            // Create the colored icon
            const icon = document.createElement('span');
            icon.style.display = 'inline-block';
            icon.style.width = '10px';
            icon.style.height = '10px';
            icon.style.backgroundColor = color(name);
            icon.style.marginRight = '5px';

            label.appendChild(icon); // Add the icon before the checkbox
            label.appendChild(checkbox);
            label.appendChild(document.createTextNode(name));

            tokenizerFilterDiv.appendChild(label);
            tokenizerFilterDiv.appendChild(document.createElement('br'));
        });
    }

    function getTokenizerNames(node, namesSet = new Set('x')) {
        if (!node)
            return namesSet;
        if (node.tokenizers) {
            for(const [script, tokenizer] of Object.entries(node.tokenizers))
                namesSet.add(tokenizer.original_lang_name);
        }
        if (node.children) {
            node.children.forEach(child => getTokenizerNames(child, namesSet));
        }
        return namesSet;
    }

    function createTree(data, recenter = false) {
        // Clear any existing tree
        d3.select("#tree-container svg").remove();

        // Set the SVG dimensions to fill the entire screen
        const width = window.innerWidth;
        const height = window.innerHeight;

        // Create the SVG element
        const svg = d3.select("#tree-container")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

        const g = svg.append("g");

        // Define zoom behavior without restricting translation extents
        const zoom = d3.zoom()
            .scaleExtent([0.1, 5])
            .on("zoom", function(event) {
                currentTransform = event.transform; // Save the current transform on zoom
                g.attr("transform", event.transform);
            });

        // Create a root hierarchy node
        const root = d3.hierarchy(data);

        // Dynamically compute tree layout for horizontal orientation
        const treeLayout = d3.tree().nodeSize([200, 100]);
        treeLayout(root);

        // Create links between nodes (now horizontal)
        g.selectAll('.link')
            .data(root.links())
            .enter()
            .append('path')
            .attr('class', 'link')
            .attr('d', d3.linkVertical()
                .x(d => d.x)
                .y(d => d.y))
            .attr('stroke', '#ccc')
            .attr('fill', 'none');

        // Create nodes
        const node = g.selectAll('.node')
            .data(root.descendants())
            .enter()
            .append('g')
            .attr('class', 'node')
            .attr('transform', d => `translate(${d.x},${d.y})`);

        const sizeScale = d3.scaleSqrt()
            .domain([1, root.data.subtreeSize])
            .range([5, 20]); // Adjust the range as needed for minimum and maximum circle


        const selectedTokenizers = Array.from(tokenizerFilterDiv.querySelectorAll('input:checked'))
            .map(input => input.value);
        const selectedScripts = Array.from(scriptFiltersDiv.querySelectorAll('input:checked'))
            .map(input => input.value);
        function getColorTokenizer(node) {
            // debugger;
            const toks = Object.entries(node.tokenizers).filter(([script, obj]) => selectedScripts.includes(script) && selectedTokenizers.includes(obj.original_lang_name));
            return toks.length > 0 ? toks[0][1].original_lang_name : 'unknown';
        }

        // Add circles to nodes
        node.append('circle')
            .filter(d => !d.data.iso_3_code)
            .attr('r', d => sizeScale(d.data.subtreeSize))
            .attr('fill', d => {
                const tokenizerName = getColorTokenizer(d.data);
                return color(tokenizerName);
            });
        node.filter(d => d.data.iso_3_code && d.data.native_tokenizers.length === 0) // Select leaf nodes
            .append('rect')
            .attr('width', 10)
            .attr('height', 10)
            .attr('x', -5)
            .attr('y', -5)
            .attr('fill', d => {
                const tokenizerName = getColorTokenizer(d.data);
                return color(tokenizerName);
            });
        node.filter(d => d.data.native_tokenizers.length !== 0) // Select leaf nodes with "own" assignment
            .append('path')
            .attr('d', d3.symbol().type(d3.symbolTriangle).size(100)) // Adjust size as needed
            .attr('fill', d => {
                const tokenizerName = getColorTokenizer(d.data);
                return color(tokenizerName);
            });

        // Add text labels to nodes
        node.append('text')
            .attr('dy', 4)
            .attr('x', d => sizeScale(d.data.subtreeSize) + 4)
            .attr('text-anchor', 'start')
            .text(d => {
                const tokenizerName = getColorTokenizer(d.data);
                return `${d.data.name} - ${tokenizerName || 'x'}${d.data.iso_3_code ? '' : ' (' + d.data.subtreeSize + ')'}`
            });

        if (!currentTransform || recenter)
            currentTransform = d3.zoomIdentity.translate(width / 2, height / 2);

        if (nodeToCenter){
            debugger;
            let element = g.selectAll('.node').filter(d => d.data.id === nodeToCenter).data()[0];
            if (element){
                const x = element.x;
                const y = element.y;
                const scale = 1.0; // Adjust scale as needed

                currentTransform = d3.zoomIdentity.translate(window.innerWidth / 2 - x, window.innerHeight / 2 - y).scale(scale);
            }
            nodeToCenter = null;
        }
        svg.call(zoom).call(zoom).call(zoom.transform, d3.zoomIdentity.translate(currentTransform.x, currentTransform.y).scale(currentTransform.k));


        // Add hover event to nodes for hover-box
        node.on("mouseover", function(event, d) {
            hoverBox.style.display = "block";
            hoverBox.style.left = (event.pageX) + "px";
            hoverBox.style.top = (event.pageY) + "px";
            const tokenizersList = Object.keys(d.data.tokenizers).map((script) =>
                `<li><em>${script}</em>: ${d.data.tokenizers[script]['class_name']}-${d.data.tokenizers[script]['original_lang_name']}${d.data.native_tokenizers.includes(script) ? '(👤)' :'(🤖)'}</li>`).join('')
            hoverBox.innerHTML = `
                <strong>Name:</strong> ${d.data.name}<br>
                ${d.data.iso_1_code ? '<strong>ISO 1 Code:</strong> ' + d.data.iso_1_code + '<br>' : ''}
                ${d.data.iso_3_code ? '<strong>ISO 3 Code:</strong> ' + d.data.iso_3_code + '<br>' : ''}
                ${d.data.scripts.length > 0 ? '<strong>Scripts:</strong> ' + d.data.scripts.join(', ') + '<br>' : ''}
                ${d.data.iso_3_code ? '<strong>In GlotLID:</strong> ' + (d.data.scripts.length > 0 ? 'YES' : 'NO') + '<br>' : ''}
                
                <strong>Tokenizers:</strong><ul>${tokenizersList}</ul>
                <strong>Subtree size:</strong> ${d.data.subtreeSize}
            `;
        }).on("mousemove", function(event) {
            hoverBox.style.left = (event.pageX) + "px";
            hoverBox.style.top = (event.pageY) + "px";
        }).on("mouseout", function() {
            hoverBox.style.display = "none";
        });

        node.on('click', function(event, d) {
            setExpanded(d.data.id, !expandedNodes.has(d.data.id))
            hoverBox.style.display = "none";
            drawVisibleNodes();
        })
    }

    function drawVisibleNodes(recenter = false) {
        if (!currentTreeData) return;

        // Get selected tokenizers
        const selectedTokenizers = Array.from(tokenizerFilterDiv.querySelectorAll('input:checked'))
            .map(input => input.value);
        const selectedScripts = Array.from(scriptFiltersDiv.querySelectorAll('input:checked'))
            .map(input => input.value);
        const showNonGlotlid = showNonGlotlidCheckbox.checked;

        // Create a new root node containing only selected tokenizers and their ancestors
        function filterHierarchy(node, parentExpanded = true, depth = 0) {
            if ((node.iso_3_code && node.scripts.length === 0 && !showNonGlotlid) || (!parentExpanded && !(depthSelector.value == 0 || depth <= depthSelector.value))) {
                return null;
            }

            const filteredChildren = (node.children || [])
                    .map(child => filterHierarchy(child, expandedNodes.has(node.id), depth + 1))
                    .filter(child => child !== null);

            const shouldBeShown = selectedTokenizers.some(tok => (Object.keys(node.tokenizers).length > 0 ? Object.values(node.tokenizers).map(x => x.original_lang_name) : ['x']).includes(tok)) &&
                selectedScripts.some(scr => (node.scripts.length ? node.scripts : ['x']).includes(scr) && (node.scripts.length > 0 || showNonGlotlid));  // if one of the leaves has this tokenizer and the selected scripts

            if (!parentExpanded && filteredChildren.length === 0 && !(node.children.length === 0 && shouldBeShown) && node.id != 0)
                return null;

            return {
                ...node,
                children: filteredChildren
            };
        }

        const filteredData = filterHierarchy(currentTreeData);
        createTree(filteredData, recenter);
    }

    function searchNode(name) {
        name = name.toLowerCase();
        if (!currentTreeData || name.length < 2) return;

        // Find node by name
        function expandNode(node) {
            if (node.name.toLowerCase() === name || node.iso_3_code === name || node.iso_1_code === name) {
                return node;
            }

            for (const child of (node.children || [])) {
                const found = expandNode(child);
                if (found) {
                    setExpanded(node.id)
                    return found;
                }
            }

            return null;
        }

        const expandedNode = expandNode(currentTreeData);
        if (expandedNode) {
            nodeToCenter = expandedNode.id;
            drawVisibleNodes();
        }
    }
});