File size: 3,764 Bytes
bec5145
 
 
 
 
 
70277bf
 
bec5145
 
 
70277bf
 
 
 
 
 
 
 
 
 
 
f8c1138
 
70277bf
 
 
f8c1138
 
1073a7b
f8c1138
 
 
 
 
 
 
 
29ec487
1073a7b
f8c1138
 
1073a7b
 
29ec487
1073a7b
 
29ec487
f8c1138
 
 
 
 
 
 
 
 
 
 
 
1073a7b
f8c1138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70277bf
 
bec5145
 
70277bf
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
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Transformers.js - Named Entity Recognition</title>
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <h1>Named Entity Recognition (NER) w/ 🤗 Transformers.js</h1>

    <!-- Seção de reconhecimento de entidades nomeadas (NER) -->
    <section>
        <h2>Named Entity Recognition (NER)</h2>
        <textarea id="text-input" rows="6" placeholder="Digite ou cole o texto aqui..."></textarea>
        <button id="analyze-text">Analisar Texto</button>
        <div id="text-output"></div>
    </section>

    <script type="module">
        import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/[email protected]';

        const textInput = document.getElementById('text-input');
        const analyzeTextButton = document.getElementById('analyze-text');
        const textOutput = document.getElementById('text-output');

        // Verifique se os elementos existem
        if (!textInput || !analyzeTextButton || !textOutput) {
            console.error('Erro: Elementos não encontrados no DOM.');
        }

        // Variável para armazenar o modelo
        let nerModel;

        // Carregar o modelo NER com quantização q4
        async function loadModel() {
            try {
                textOutput.textContent = 'Carregando modelo de NER...';
                nerModel = await pipeline('token-classification', 'Xenova/distilbert-base-multilingual-cased-ner-hrl', {
                    dtype: 'quantized'
                });
                textOutput.textContent = 'Modelo de NER pronto!';
            } catch (error) {
                console.error('Erro ao carregar o modelo:', error);
                textOutput.textContent = 'Erro ao carregar o modelo. Tente novamente mais tarde.';
            }
        }

        // Carregar o modelo ao iniciar
        await loadModel();

        // Evento de clique para análise
        analyzeTextButton.addEventListener('click', async () => {
            const inputText = textInput.value.trim();

            if (!inputText) {
                textOutput.textContent = 'Por favor, insira um texto para análise.';
                return;
            }

            textOutput.textContent = 'Analisando...';

            try {
                console.log("inputText",inputText)
                const nerOutput = await nerModel(inputText,{
        ignore_labels: []   // Return all labels
    });
                console.log(nerOutput)
                renderEntities(nerOutput);
            } catch (error) {
                console.error('Erro durante a análise:', error);
                textOutput.textContent = 'Erro durante a análise. Verifique o texto inserido.';
            }
        });

        // Função para renderizar as entidades
        function renderEntities(entities) {
            textOutput.innerHTML = ''; // Limpar saída anterior

            if (entities.length === 0) {
                textOutput.textContent = 'Nenhuma entidade encontrada.';
                return;
            }

            entities.forEach(entity => {
                const { word, entity_group, score } = entity;

                const entityElement = document.createElement('div');
                entityElement.className = 'entity';
                entityElement.innerHTML = `
                    <strong>Palavra:</strong> ${word} <br>
                    <strong>Entidade:</strong> ${entity_group} <br>
                    <strong>Confiança:</strong> ${(score * 100).toFixed(2)}%
                `;
                textOutput.appendChild(entityElement);
            });
        }
    </script>
</body>

</html>