File size: 7,776 Bytes
92b8830
 
 
 
 
6adb396
 
 
 
 
 
 
 
92b8830
 
6adb396
92b8830
6adb396
 
 
92b8830
6adb396
 
92b8830
6adb396
 
 
 
 
 
 
 
 
 
92b8830
 
 
6adb396
 
 
92b8830
6adb396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92b8830
 
 
6adb396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92b8830
 
6adb396
 
 
 
92b8830
 
6adb396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92b8830
6adb396
92b8830
 
6adb396
 
 
 
 
92b8830
 
 
6adb396
 
 
92b8830
 
6adb396
 
92b8830
 
 
27a16d2
6adb396
27a16d2
 
6adb396
27a16d2
 
 
 
 
 
6adb396
 
 
 
 
 
27a16d2
 
6adb396
27a16d2
92b8830
 
 
 
d7b6703
27a16d2
6adb396
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
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preguntas y Respuestas con DistilBERT Multilingual</title>
    <style>
        textarea {
            width: 100%;
            height: 300px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h1>Preguntas sobre un Documento</h1>

    <!-- Formulario para cargar archivos (permitir carga múltiple) -->
    <input type="file" id="fileInput" accept=".pdf,.txt,.docx" multiple>
    <button onclick="processFiles()">Cargar y Analizar Archivos</button>

    <!-- Área de texto para la pregunta -->
    <br><br>
    <label for="question">Pregunta:</label>
    <input type="text" id="question" placeholder="Escribe tu pregunta aquí" />

    <!-- Botón para enviar la pregunta -->
    <button onclick="askQuestion()">Enviar Pregunta</button>

    <!-- Área para mostrar el texto extraído de los archivos -->
    <h3>Texto Extraído:</h3>
    <textarea id="extractedText" readonly></textarea>

    <!-- Área para mostrar la respuesta -->
    <h3>Respuesta:</h3>
    <div id="response"></div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/es5/build/pdf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jszip.min.js"></script>

    <script>
        // Global variable to hold extracted text
        let extractedText = '';

        // Function to process the uploaded files (PDF, TXT, DOCX)
        function processFiles() {
            const fileInput = document.getElementById('fileInput');
            const files = fileInput.files;
            if (files.length === 0) {
                alert('Por favor, selecciona al menos un archivo.');
                return;
            }

            extractedText = ''; // Reset the extracted text
            let filePromises = [];

            // Process each file based on its type
            for (let file of files) {
                const fileExtension = file.name.split('.').pop().toLowerCase();
                const reader = new FileReader();

                const promise = new Promise((resolve, reject) => {
                    reader.onload = function(event) {
                        const fileContent = event.target.result;

                        // Extract text based on the file type
                        if (fileExtension === 'pdf') {
                            extractTextFromPDF(fileContent, resolve);
                        } else if (fileExtension === 'txt') {
                            extractTextFromTXT(fileContent, resolve);
                        } else if (fileExtension === 'docx') {
                            extractTextFromDOCX(fileContent, resolve);
                        } else {
                            reject(`Formato de archivo no soportado: ${file.name}`);
                        }
                    };

                    reader.readAsArrayBuffer(file);
                });

                filePromises.push(promise);
            }

            // Wait for all file promises to finish
            Promise.all(filePromises)
                .then(() => {
                    // Display extracted text in the textarea
                    document.getElementById('extractedText').value = extractedText;
                    alert('Texto extraído de los archivos.');
                })
                .catch((error) => {
                    console.error('Error al procesar los archivos:', error);
                    alert('Hubo un error al procesar los archivos.');
                });
        }

        // Function to extract text from a PDF file
        function extractTextFromPDF(fileContent, resolve) {
            const loadingTask = pdfjsLib.getDocument({ data: fileContent });
            loadingTask.promise.then(function(pdf) {
                let text = '';
                const numPages = pdf.numPages;
                let pagePromises = [];

                for (let i = 1; i <= numPages; i++) {
                    pagePromises.push(pdf.getPage(i).then(function(page) {
                        return page.getTextContent().then(function(textContent) {
                            text += textContent.items.map(item => item.str).join(' ') + '\n';
                        });
                    }));
                }

                Promise.all(pagePromises).then(function() {
                    extractedText += text + '\n'; // Add the extracted text
                    resolve();
                });
            }).catch(function(error) {
                console.error('Error al extraer texto del PDF:', error);
                resolve();
            });
        }

        // Function to extract text from a TXT file
        function extractTextFromTXT(fileContent, resolve) {
            extractedText += fileContent + '\n'; // Add the extracted text
            resolve();
        }

        // Function to extract text from a DOCX file
        function extractTextFromDOCX(fileContent, resolve) {
            const zip = new JSZip();
            zip.loadAsync(fileContent).then(function(zip) {
                zip.file('word/document.xml').async('string').then(function(content) {
                    const parser = new DOMParser();
                    const xmlDoc = parser.parseFromString(content, 'text/xml');
                    const texts = xmlDoc.getElementsByTagName('w:t');
                    extractedText += Array.from(texts).map(t => t.textContent).join(' ') + '\n';
                    resolve();
                }).catch(function(error) {
                    console.error('Error al extraer texto del DOCX:', error);
                    resolve();
                });
            });
        }

        // Function to validate inputs and send the question to Hugging Face API
        async function askQuestion() {
            const question = document.getElementById('question').value;
            const context = extractedText;

            // Validate if question and context are non-empty strings
            if (typeof question !== 'string' || typeof context !== 'string' || question.trim() === '' || context.trim() === '') {
                alert('Por favor, ingresa una pregunta y asegúrate de que el contexto no esté vacío.');
                return;
            }

            const cucu = window.huggingface.variables["API_KEY_2"];
            console.log("key : " + cucu);
            // Prepare the request data
            const data = {
                inputs: {
                    question: question,  // Should be a string
                    context: context     // Should be a string
                }
            };

            try {
                const response = await fetch('https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased', {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer ' + cucu', // Replace with your Hugging Face API key
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();
                if (response.ok) {
                    document.getElementById('response').innerText = result.answer;
                } else {
                    console.error('Error en la respuesta:', result);
                    alert(`Hubo un error al procesar la solicitud: ${JSON.stringify(result)}`);
                }
            } catch (error) {
                console.error('Error al hacer la consulta:', error);
                alert('Hubo un error al procesar la solicitud.');
            }
        }
    </script>
</body>
</html>