File size: 6,279 Bytes
92b8830
 
 
 
 
e2b20b6
92b8830
 
e2b20b6
 
 
 
 
41242e5
e2b20b6
 
41242e5
e2b20b6
 
 
 
41242e5
e2b20b6
 
92b8830
 
e2b20b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41242e5
6adb396
e2b20b6
 
 
 
 
 
 
 
 
 
 
6adb396
e2b20b6
 
 
6adb396
e2b20b6
 
41242e5
e2b20b6
 
 
 
6adb396
92b8830
 
e2b20b6
 
41242e5
e2b20b6
 
 
 
 
 
 
 
 
 
6adb396
 
92b8830
e2b20b6
 
67fc043
e2b20b6
92b8830
19b0e95
 
6adb396
41242e5
 
92b8830
 
 
19b0e95
 
 
 
e2b20b6
 
 
8482b1a
 
 
e2b20b6
92b8830
19b0e95
 
92b8830
41242e5
 
 
 
 
 
27a16d2
e2b20b6
41242e5
27a16d2
41242e5
e2b20b6
27a16d2
 
 
e2b20b6
6adb396
e2b20b6
6adb396
 
e2b20b6
41242e5
6adb396
27a16d2
 
41242e5
27a16d2
92b8830
 
e2b20b6
 
 
 
92b8830
 
0966a25
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
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Consulta con DistilBERT Multilingual</title>
</head>
<body>

    <h1>Consulta con DistilBERT Multilingual</h1>

    <!-- Cargar archivo y mostrar texto -->
    <input type="file" id="fileInput" accept=".txt,.pdf,.doc,.docx" multiple />
    <br><br>

    <textarea id="textOutput" rows="10" cols="100" placeholder="El texto extraído aparecerá aquí..." readonly></textarea>
    <br><br>

    <!-- Caja de preguntas -->
    <input type="text" id="questionInput" placeholder="Escribe tu pregunta aquí" />
    <button onclick="askQuestion()">Hacer Pregunta</button>
    
    <h3>Respuesta:</h3>
    <p id="response"></p>

    <script>
        // Función para extraer texto de archivos PDF, TXT y DOCX
        async function handleFileUpload(event) {
            const files = event.target.files;
            let allText = "";

            for (let file of files) {
                const fileType = file.type;

                if (fileType === "application/pdf") {
                    allText += await extractTextFromPDF(file);
                } else if (fileType === "text/plain") {
                    allText += await extractTextFromTXT(file);
                } else if (fileType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
                    allText += await extractTextFromDOCX(file);
                } else {
                    alert("Archivo no compatible. Solo se aceptan PDF, TXT y DOCX.");
                }
            }

            // Mostrar el texto extraído en el textarea
            document.getElementById("textOutput").value = allText;
        }

        // Extraer texto de PDF
        async function extractTextFromPDF(file) {
            const pdf = await pdfjsLib.getDocument(URL.createObjectURL(file)).promise;
            let text = "";
            for (let i = 0; i < pdf.numPages; i++) {
                const page = await pdf.getPage(i + 1);
                const content = await page.getTextContent();
                text += content.items.map(item => item.str).join(" ") + "\n";
            }
            return text;
        }

        // Extraer texto de TXT
        async function extractTextFromTXT(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function(event) {
                    resolve(event.target.result);
                };
                reader.onerror = function(error) {
                    reject(error);
                };
                reader.readAsText(file);
            });
        }

        // Extraer texto de DOCX
        async function extractTextFromDOCX(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const doc = new window.Docxtemplater(new window.PizZip(event.target.result));
                    const text = doc.getFullText(); // Extrae todo el texto
                    resolve(text);
                };
                reader.onerror = function(error) {
                    reject(error);
                };
                reader.readAsBinaryString(file);
            });
        }

        // Detectar cuando se suben archivos
        document.getElementById("fileInput").addEventListener("change", handleFileUpload);

        // Función para hacer la consulta
        async function askQuestion() {
            const question = document.getElementById("questionInput").value.trim(); // Trim para eliminar espacios innecesarios
            const context = document.getElementById("textOutput").value.trim();  // Trim para eliminar espacios innecesarios

            if (!question || !context) {
                alert("Por favor, asegúrate de que hay texto y una pregunta.");
                return;
            }

            // Asegurarse de que el texto sea una cadena de texto y no un array u objeto
            const questionString = String(question); 
            const contextString = String(context);

            // Mostrar mensaje de espera si el modelo se está cargando
            const modelUrl = "https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased";
            const token = window.huggingface.variables["API_KEY_2"];
            console.log("key : " + token);
            console.log("texte : " + contextString);
            console.log("pregunta : " + questionString);
            // Datos a enviar al modelo
            const data = {
                question: questionString, // Pregunta como cadena de texto
                context: contextString     // Contexto como cadena de texto
            };

            const headers = {
                "Authorization": `Bearer ${token}`,
                "Content-Type": "application/json"
            };

            try {
                // Realizar la consulta a la API de Hugging Face
                const response = await fetch(modelUrl, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(data) // Convierte los datos a JSON
                });

                const result = await response.json();

                if (response.ok) {
                    // Mostrar la respuesta obtenida
                    document.getElementById('response').innerText = result.answer;
                } else {
                    // Mostrar mensaje de error
                    document.getElementById('response').innerText = `Error: ${result.error}`;
                }
            } catch (error) {
                console.error('Error al hacer la consulta:', error);
                document.getElementById('response').innerText = `Error al procesar la solicitud: ${error.message}`;
            }
        }
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.20.0/docxtemplater.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pizzip/3.0.6/pizzip.min.js"></script>
</body>
</html>