eduardmtz commited on
Commit
6adb396
·
verified ·
1 Parent(s): c9e56cc

Update test5.html

Browse files
Files changed (1) hide show
  1. test5.html +144 -95
test5.html CHANGED
@@ -3,139 +3,187 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Preguntas sobre Documentos</title>
7
- <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
8
- <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
9
- <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.2/mammoth.browser.min.js"></script>
 
 
 
 
10
  </head>
11
  <body>
12
- <h1>Sube un archivo y haz preguntas en español o catalán</h1>
13
 
14
- <input type="file" id="file-input" />
15
- <br><br>
 
16
 
 
 
17
  <label for="question">Pregunta:</label>
18
- <input type="text" id="question" placeholder="Escribe tu pregunta aquí">
19
- <button onclick="askQuestion()">Hacer Pregunta</button>
20
-
 
 
 
 
 
 
 
21
  <h3>Respuesta:</h3>
22
  <div id="response"></div>
23
 
 
 
 
24
  <script>
25
- // Especificar la ruta del worker de PDF.js
26
- pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';
27
-
28
- let documentText = ''; // Para almacenar el texto extraído de los documentos
29
-
30
- // Función para leer archivos PDF
31
- async function readPDF(file) {
32
- const reader = new FileReader();
33
- reader.onload = async function(event) {
34
- const loadingTask = pdfjsLib.getDocument(event.target.result);
35
- loadingTask.promise.then(function(pdf) {
36
- let text = '';
37
- const numPages = pdf.numPages;
38
- for (let pageNum = 1; pageNum <= numPages; pageNum++) {
39
- pdf.getPage(pageNum).then(function(page) {
40
- page.getTextContent().then(function(textContent) {
41
- textContent.items.forEach(function(item) {
42
- text += item.str + ' ';
43
- });
44
- documentText = text; // Guardamos el texto
45
- });
46
- });
47
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  });
49
- };
50
- reader.readAsArrayBuffer(file);
51
  }
52
 
53
- // Función para leer archivos de texto (TXT)
54
- function readTXT(file) {
55
- const reader = new FileReader();
56
- reader.onload = function(event) {
57
- documentText = event.target.result; // Guardamos el texto
58
- };
59
- reader.readAsText(file);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  }
61
 
62
- // Función para leer archivos de Word (DOCX)
63
- function readWord(file) {
64
- const reader = new FileReader();
65
- reader.onload = function(event) {
66
- mammoth.convertToHtml({ arrayBuffer: event.target.result })
67
- .then(function(result) {
68
- documentText = result.value; // Guardamos el texto
69
- })
70
- .catch(function(err) {
71
- console.log(err);
72
- });
73
- };
74
- reader.readAsArrayBuffer(file);
75
  }
76
 
77
- // Lógica para cargar el archivo seleccionado
78
- document.getElementById('file-input').addEventListener('change', function(event) {
79
- const file = event.target.files[0];
80
- const fileType = file.type;
81
-
82
- if (fileType === 'application/pdf') {
83
- readPDF(file);
84
- } else if (fileType === 'text/plain') {
85
- readTXT(file);
86
- } else if (fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
87
- readWord(file);
88
- } else {
89
- alert('Tipo de archivo no soportado');
90
- }
91
- });
 
92
 
93
- // Función para hacer preguntas al modelo de Hugging Face
94
  async function askQuestion() {
95
  const question = document.getElementById('question').value;
96
- if (!documentText || !question) {
97
- alert('Asegúrate de que se haya cargado un archivo y que hayas ingresado una pregunta.');
 
 
 
98
  return;
99
  }
100
 
101
- // Usamos la API de Hugging Face para el modelo multilingüe de preguntas y respuestas
102
- //const modelUrl = 'https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased-distilled-squad';
103
- const modelUrl = 'https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased'; // Usa el modelo DistilBERT multilingüe
104
-
105
-
106
- // Preparamos los datos para la consulta
107
  const data = {
108
  inputs: {
109
- question: question,
110
- context: documentText
111
  }
112
  };
113
 
114
- console.log("Enviando datos: ", data); // Verificación de los datos enviados
115
- const cucu = window.huggingface.variables["API_KEY_2"];
116
- console.log("key : " + cucu);
117
  try {
118
- // Hacemos la petición a la API de Hugging Face
119
- const response = await fetch(modelUrl, {
120
  method: 'POST',
121
  headers: {
122
- 'Authorization': 'Bearer ' + cucu, // Sustituye por tu API key de Hugging Face
123
  'Content-Type': 'application/json'
124
  },
125
  body: JSON.stringify(data)
126
  });
127
 
128
- if (!response.ok) {
129
- throw new Error(`Error: ${response.statusText} - ${await response.text()}`);
130
- }
131
-
132
  const result = await response.json();
133
- const answer = result?.answer || 'No pude encontrar una respuesta.';
134
- document.getElementById('response').innerHTML = answer;
135
-
 
 
 
136
  } catch (error) {
137
  console.error('Error al hacer la consulta:', error);
138
- alert('Hubo un error al procesar la solicitud: ' + error.message);
139
  }
140
  }
141
  </script>
@@ -143,3 +191,4 @@
143
  </html>
144
 
145
 
 
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Preguntas y Respuestas con DistilBERT Multilingual</title>
7
+ <style>
8
+ textarea {
9
+ width: 100%;
10
+ height: 300px;
11
+ margin-top: 10px;
12
+ }
13
+ </style>
14
  </head>
15
  <body>
16
+ <h1>Preguntas sobre un Documento</h1>
17
 
18
+ <!-- Formulario para cargar archivos (permitir carga múltiple) -->
19
+ <input type="file" id="fileInput" accept=".pdf,.txt,.docx" multiple>
20
+ <button onclick="processFiles()">Cargar y Analizar Archivos</button>
21
 
22
+ <!-- Área de texto para la pregunta -->
23
+ <br><br>
24
  <label for="question">Pregunta:</label>
25
+ <input type="text" id="question" placeholder="Escribe tu pregunta aquí" />
26
+
27
+ <!-- Botón para enviar la pregunta -->
28
+ <button onclick="askQuestion()">Enviar Pregunta</button>
29
+
30
+ <!-- Área para mostrar el texto extraído de los archivos -->
31
+ <h3>Texto Extraído:</h3>
32
+ <textarea id="extractedText" readonly></textarea>
33
+
34
+ <!-- Área para mostrar la respuesta -->
35
  <h3>Respuesta:</h3>
36
  <div id="response"></div>
37
 
38
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/es5/build/pdf.min.js"></script>
39
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jszip.min.js"></script>
40
+
41
  <script>
42
+ // Global variable to hold extracted text
43
+ let extractedText = '';
44
+
45
+ // Function to process the uploaded files (PDF, TXT, DOCX)
46
+ function processFiles() {
47
+ const fileInput = document.getElementById('fileInput');
48
+ const files = fileInput.files;
49
+ if (files.length === 0) {
50
+ alert('Por favor, selecciona al menos un archivo.');
51
+ return;
52
+ }
53
+
54
+ extractedText = ''; // Reset the extracted text
55
+ let filePromises = [];
56
+
57
+ // Process each file based on its type
58
+ for (let file of files) {
59
+ const fileExtension = file.name.split('.').pop().toLowerCase();
60
+ const reader = new FileReader();
61
+
62
+ const promise = new Promise((resolve, reject) => {
63
+ reader.onload = function(event) {
64
+ const fileContent = event.target.result;
65
+
66
+ // Extract text based on the file type
67
+ if (fileExtension === 'pdf') {
68
+ extractTextFromPDF(fileContent, resolve);
69
+ } else if (fileExtension === 'txt') {
70
+ extractTextFromTXT(fileContent, resolve);
71
+ } else if (fileExtension === 'docx') {
72
+ extractTextFromDOCX(fileContent, resolve);
73
+ } else {
74
+ reject(`Formato de archivo no soportado: ${file.name}`);
75
+ }
76
+ };
77
+
78
+ reader.readAsArrayBuffer(file);
79
+ });
80
+
81
+ filePromises.push(promise);
82
+ }
83
+
84
+ // Wait for all file promises to finish
85
+ Promise.all(filePromises)
86
+ .then(() => {
87
+ // Display extracted text in the textarea
88
+ document.getElementById('extractedText').value = extractedText;
89
+ alert('Texto extraído de los archivos.');
90
+ })
91
+ .catch((error) => {
92
+ console.error('Error al procesar los archivos:', error);
93
+ alert('Hubo un error al procesar los archivos.');
94
  });
 
 
95
  }
96
 
97
+ // Function to extract text from a PDF file
98
+ function extractTextFromPDF(fileContent, resolve) {
99
+ const loadingTask = pdfjsLib.getDocument({ data: fileContent });
100
+ loadingTask.promise.then(function(pdf) {
101
+ let text = '';
102
+ const numPages = pdf.numPages;
103
+ let pagePromises = [];
104
+
105
+ for (let i = 1; i <= numPages; i++) {
106
+ pagePromises.push(pdf.getPage(i).then(function(page) {
107
+ return page.getTextContent().then(function(textContent) {
108
+ text += textContent.items.map(item => item.str).join(' ') + '\n';
109
+ });
110
+ }));
111
+ }
112
+
113
+ Promise.all(pagePromises).then(function() {
114
+ extractedText += text + '\n'; // Add the extracted text
115
+ resolve();
116
+ });
117
+ }).catch(function(error) {
118
+ console.error('Error al extraer texto del PDF:', error);
119
+ resolve();
120
+ });
121
  }
122
 
123
+ // Function to extract text from a TXT file
124
+ function extractTextFromTXT(fileContent, resolve) {
125
+ extractedText += fileContent + '\n'; // Add the extracted text
126
+ resolve();
 
 
 
 
 
 
 
 
 
127
  }
128
 
129
+ // Function to extract text from a DOCX file
130
+ function extractTextFromDOCX(fileContent, resolve) {
131
+ const zip = new JSZip();
132
+ zip.loadAsync(fileContent).then(function(zip) {
133
+ zip.file('word/document.xml').async('string').then(function(content) {
134
+ const parser = new DOMParser();
135
+ const xmlDoc = parser.parseFromString(content, 'text/xml');
136
+ const texts = xmlDoc.getElementsByTagName('w:t');
137
+ extractedText += Array.from(texts).map(t => t.textContent).join(' ') + '\n';
138
+ resolve();
139
+ }).catch(function(error) {
140
+ console.error('Error al extraer texto del DOCX:', error);
141
+ resolve();
142
+ });
143
+ });
144
+ }
145
 
146
+ // Function to validate inputs and send the question to Hugging Face API
147
  async function askQuestion() {
148
  const question = document.getElementById('question').value;
149
+ const context = extractedText;
150
+
151
+ // Validate if question and context are non-empty strings
152
+ if (typeof question !== 'string' || typeof context !== 'string' || question.trim() === '' || context.trim() === '') {
153
+ alert('Por favor, ingresa una pregunta y asegúrate de que el contexto no esté vacío.');
154
  return;
155
  }
156
 
157
+ const cucu = window.huggingface.variables["API_KEY_2"];
158
+ console.log("key : " + cucu);
159
+ // Prepare the request data
 
 
 
160
  const data = {
161
  inputs: {
162
+ question: question, // Should be a string
163
+ context: context // Should be a string
164
  }
165
  };
166
 
 
 
 
167
  try {
168
+ const response = await fetch('https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased', {
 
169
  method: 'POST',
170
  headers: {
171
+ 'Authorization': 'Bearer ' + cucu', // Replace with your Hugging Face API key
172
  'Content-Type': 'application/json'
173
  },
174
  body: JSON.stringify(data)
175
  });
176
 
 
 
 
 
177
  const result = await response.json();
178
+ if (response.ok) {
179
+ document.getElementById('response').innerText = result.answer;
180
+ } else {
181
+ console.error('Error en la respuesta:', result);
182
+ alert(`Hubo un error al procesar la solicitud: ${JSON.stringify(result)}`);
183
+ }
184
  } catch (error) {
185
  console.error('Error al hacer la consulta:', error);
186
+ alert('Hubo un error al procesar la solicitud.');
187
  }
188
  }
189
  </script>
 
191
  </html>
192
 
193
 
194
+