eduardmtz commited on
Commit
41242e5
verified
1 Parent(s): 91ff9c1

Update test5.html

Browse files
Files changed (1) hide show
  1. test5.html +110 -166
test5.html CHANGED
@@ -3,211 +3,156 @@
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
- <!-- Cargar la librer铆a PDF.js -->
39
- <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
40
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jszip.min.js"></script>
41
-
42
  <script>
43
- // Configuraci贸n de PDF.js (Especificar la ubicaci贸n del archivo workerSrc)
44
- pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';
45
-
46
- // Global variable to hold extracted text
47
- let extractedText = '';
48
- let modelReady = false;
49
 
50
- // Function to process the uploaded files (PDF, TXT, DOCX)
51
  function processFiles() {
52
  const fileInput = document.getElementById('fileInput');
53
- const files = fileInput.files;
54
- if (files.length === 0) {
55
- alert('Por favor, selecciona al menos un archivo.');
56
- return;
57
- }
58
-
59
- extractedText = ''; // Reset the extracted text
60
- let filePromises = [];
61
 
62
- // Process each file based on its type
63
- for (let file of files) {
64
- const fileExtension = file.name.split('.').pop().toLowerCase();
65
  const reader = new FileReader();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- const promise = new Promise((resolve, reject) => {
68
- reader.onload = function(event) {
69
- const fileContent = event.target.result;
70
-
71
- // Extract text based on the file type
72
- if (fileExtension === 'pdf') {
73
- extractTextFromPDF(fileContent, resolve);
74
- } else if (fileExtension === 'txt') {
75
- extractTextFromTXT(fileContent, resolve);
76
- } else if (fileExtension === 'docx') {
77
- extractTextFromDOCX(fileContent, resolve);
78
- } else {
79
- reject(`Formato de archivo no soportado: ${file.name}`);
80
- }
81
- };
82
-
83
  reader.readAsArrayBuffer(file);
84
- });
85
-
86
- filePromises.push(promise);
87
- }
88
-
89
- // Wait for all file promises to finish
90
- Promise.all(filePromises)
91
- .then(() => {
92
- // Display extracted text in the textarea
93
- document.getElementById('extractedText').value = extractedText;
94
- alert('Texto extra铆do de los archivos.');
95
- })
96
- .catch((error) => {
97
- console.error('Error al procesar los archivos:', error);
98
- alert('Hubo un error al procesar los archivos.');
99
- });
100
- }
101
-
102
- // Function to extract text from a PDF file
103
- function extractTextFromPDF(fileContent, resolve) {
104
- const loadingTask = pdfjsLib.getDocument({ data: fileContent });
105
- loadingTask.promise.then(function(pdf) {
106
- let text = '';
107
- const numPages = pdf.numPages;
108
- let pagePromises = [];
109
-
110
- for (let i = 1; i <= numPages; i++) {
111
- pagePromises.push(pdf.getPage(i).then(function(page) {
112
- return page.getTextContent().then(function(textContent) {
113
- // Concatenate text extracted from each page
114
- text += textContent.items.map(item => item.str).join(' ') + '\n';
115
- });
116
- }));
117
  }
118
-
119
- Promise.all(pagePromises).then(function() {
120
- extractedText += text + '\n'; // Add the extracted text
121
- resolve();
122
- });
123
- }).catch(function(error) {
124
- console.error('Error al extraer texto del PDF:', error);
125
- resolve();
126
  });
127
  }
128
 
129
- // Function to extract text from a TXT file
130
- function extractTextFromTXT(fileContent, resolve) {
131
- extractedText += fileContent + '\n'; // Add the extracted text
132
- resolve();
133
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
- // Function to extract text from a DOCX file
136
- function extractTextFromDOCX(fileContent, resolve) {
137
- const zip = new JSZip();
138
- zip.loadAsync(fileContent).then(function(zip) {
139
- zip.file('word/document.xml').async('string').then(function(content) {
140
- const parser = new DOMParser();
141
- const xmlDoc = parser.parseFromString(content, 'text/xml');
142
- const texts = xmlDoc.getElementsByTagName('w:t');
143
- extractedText += Array.from(texts).map(t => t.textContent).join(' ') + '\n';
144
- resolve();
145
- }).catch(function(error) {
146
- console.error('Error al extraer texto del DOCX:', error);
147
- resolve();
148
- });
149
  });
150
  }
151
 
152
- // Function to check if the model is ready
153
- async function checkModelReady() {
154
- try {
155
- const response = await fetch('https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased', {
156
- method: 'GET',
157
- headers: {
158
- 'Authorization': 'Bearer your_huggingface_api_key' // Replace with your Hugging Face API key
 
 
 
 
 
 
 
 
 
 
 
 
159
  }
160
  });
161
-
162
- const result = await response.json();
163
-
164
- if (result.error && result.error.includes('currently loading')) {
165
- const estimatedTime = result.estimated_time || 20;
166
- alert(`El modelo est谩 cargando. Estimaci贸n de tiempo restante: ${Math.round(estimatedTime)} segundos.`);
167
- return false;
168
- }
169
-
170
- modelReady = true;
171
- return true;
172
- } catch (error) {
173
- console.error('Error al verificar si el modelo est谩 listo:', error);
174
- return false;
175
- }
176
  }
177
 
178
- // Function to validate inputs and send the question to Hugging Face API
179
  async function askQuestion() {
180
  const question = document.getElementById('question').value;
181
- const context = extractedText;
182
 
183
- // Validate if question and context are non-empty strings
184
- if (typeof question !== 'string' || typeof context !== 'string' || question.trim() === '' || context.trim() === '') {
185
- alert('Por favor, ingresa una pregunta y aseg煤rate de que el contexto no est茅 vac铆o.');
186
  return;
187
  }
188
 
189
- // Check if the model is ready
190
- const modelReady = await checkModelReady();
191
- if (!modelReady) {
192
- return; // Don't continue if the model isn't ready
193
- }
194
-
195
- // Prepare the request data
196
  const data = {
197
  inputs: {
198
- question: question, // Should be a string
199
- context: context // Should be a string
200
  }
201
  };
202
- const cucu = window.huggingface.variables["API_KEY_2"];
 
 
 
203
  console.log("key : " + cucu);
 
 
 
 
 
204
  try {
205
- const response = await fetch('https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased', {
206
  method: 'POST',
207
- headers: {
208
- 'Authorization': 'Bearer ' + cucu, // Replace with your Hugging Face API key
209
- 'Content-Type': 'application/json'
210
- },
211
  body: JSON.stringify(data)
212
  });
213
 
@@ -215,12 +160,11 @@
215
  if (response.ok) {
216
  document.getElementById('response').innerText = result.answer;
217
  } else {
218
- console.error('Error en la respuesta:', result);
219
- alert(`Hubo un error al procesar la solicitud: ${JSON.stringify(result)}`);
220
  }
221
  } catch (error) {
222
  console.error('Error al hacer la consulta:', error);
223
- alert('Hubo un error al procesar la solicitud.');
224
  }
225
  }
226
  </script>
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Extracci贸n de Texto y Preguntas con Modelo Multiling眉e</title>
7
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
8
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
9
  <style>
10
+ body { font-family: Arial, sans-serif; margin: 20px; }
11
+ #output { margin-top: 20px; }
12
+ textarea { width: 100%; height: 300px; }
 
 
13
  </style>
14
  </head>
15
  <body>
16
+ <h1>Sube tu archivo (PDF, TXT, DOCX) y haz preguntas</h1>
 
 
17
  <input type="file" id="fileInput" accept=".pdf,.txt,.docx" multiple>
 
 
 
18
  <br><br>
19
+ <button onclick="processFiles()">Cargar y procesar archivos</button>
20
+ <br><br>
21
+
22
+ <textarea id="output" placeholder="Texto extra铆do del archivo..."></textarea>
23
+ <br><br>
24
+
25
  <label for="question">Pregunta:</label>
26
+ <input type="text" id="question" placeholder="Escribe tu pregunta aqu铆...">
27
+ <br><br>
28
+
29
+ <button onclick="askQuestion()">Preguntar</button>
30
+
 
 
 
 
 
 
31
  <div id="response"></div>
32
 
 
 
 
 
33
  <script>
34
+ // Funci贸n para limpiar el texto extra铆do
35
+ function cleanText(text) {
36
+ return text.replace(/\s+/g, ' ').trim(); // Elimina espacios y saltos de l铆nea innecesarios
37
+ }
 
 
38
 
39
+ // Funci贸n para procesar los archivos cargados
40
  function processFiles() {
41
  const fileInput = document.getElementById('fileInput');
42
+ const output = document.getElementById('output');
43
+ let extractedText = '';
 
 
 
 
 
 
44
 
45
+ Array.from(fileInput.files).forEach(file => {
 
 
46
  const reader = new FileReader();
47
+ reader.onload = function(e) {
48
+ const fileType = file.name.split('.').pop().toLowerCase();
49
+
50
+ if (fileType === 'txt') {
51
+ extractedText += cleanText(e.target.result) + '\n';
52
+ } else if (fileType === 'pdf') {
53
+ extractTextFromPDF(e.target.result).then(text => {
54
+ extractedText += cleanText(text) + '\n';
55
+ output.value = extractedText;
56
+ });
57
+ } else if (fileType === 'docx') {
58
+ extractTextFromDOCX(e.target.result).then(text => {
59
+ extractedText += cleanText(text) + '\n';
60
+ output.value = extractedText;
61
+ });
62
+ }
63
+ };
64
 
65
+ if (file.type === 'application/pdf') {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  reader.readAsArrayBuffer(file);
67
+ } else {
68
+ reader.readAsText(file);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  }
 
 
 
 
 
 
 
 
70
  });
71
  }
72
 
73
+ // Funci贸n para extraer texto de un archivo PDF
74
+ function extractTextFromPDF(pdfData) {
75
+ return new Promise((resolve, reject) => {
76
+ const loadingTask = pdfjsLib.getDocument({data: pdfData});
77
+ loadingTask.promise.then(pdf => {
78
+ let text = '';
79
+ let pageNumber = 1;
80
+
81
+ function extractPageText(pageNum) {
82
+ pdf.getPage(pageNum).then(page => {
83
+ page.getTextContent().then(content => {
84
+ content.items.forEach(item => {
85
+ text += item.str + ' ';
86
+ });
87
+
88
+ if (pageNum < pdf.numPages) {
89
+ extractPageText(pageNum + 1);
90
+ } else {
91
+ resolve(text);
92
+ }
93
+ });
94
+ });
95
+ }
96
 
97
+ extractPageText(pageNumber);
98
+ }, reject);
 
 
 
 
 
 
 
 
 
 
 
 
99
  });
100
  }
101
 
102
+ // Funci贸n para extraer texto de un archivo DOCX
103
+ function extractTextFromDOCX(docxData) {
104
+ return new Promise((resolve, reject) => {
105
+ JSZip.loadAsync(docxData).then(function(zip) {
106
+ const xmlFile = zip.file("word/document.xml");
107
+ if (!xmlFile) {
108
+ reject("Archivo XML no encontrado.");
109
+ } else {
110
+ xmlFile.async("string").then(function(xmlText) {
111
+ const parser = new DOMParser();
112
+ const xmlDoc = parser.parseFromString(xmlText, "text/xml");
113
+ let text = '';
114
+ const paragraphs = xmlDoc.getElementsByTagName('w:t');
115
+
116
+ for (let i = 0; i < paragraphs.length; i++) {
117
+ text += paragraphs[i].textContent + ' ';
118
+ }
119
+ resolve(text);
120
+ });
121
  }
122
  });
123
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  }
125
 
126
+ // Funci贸n para hacer preguntas al modelo de Hugging Face
127
  async function askQuestion() {
128
  const question = document.getElementById('question').value;
129
+ const context = document.getElementById('output').value;
130
 
131
+ if (!question || !context) {
132
+ alert("Por favor, aseg煤rate de que hay texto y una pregunta.");
 
133
  return;
134
  }
135
 
 
 
 
 
 
 
 
136
  const data = {
137
  inputs: {
138
+ question: question,
139
+ context: context
140
  }
141
  };
142
+
143
+ const modelUrl = "https://api-inference.huggingface.co/models/distilbert-base-multilingual-cased";
144
+ const cucu = window.huggingface.variables["API_KEY_2"];
145
+ const token = window.huggingface.variables["API_KEY_2"];
146
  console.log("key : " + cucu);
147
+ const headers = {
148
+ "Authorization": `Bearer ${token}`,
149
+ "Content-Type": "application/json"
150
+ };
151
+
152
  try {
153
+ const response = await fetch(modelUrl, {
154
  method: 'POST',
155
+ headers: headers,
 
 
 
156
  body: JSON.stringify(data)
157
  });
158
 
 
160
  if (response.ok) {
161
  document.getElementById('response').innerText = result.answer;
162
  } else {
163
+ document.getElementById('response').innerText = `Error: ${result.error}`;
 
164
  }
165
  } catch (error) {
166
  console.error('Error al hacer la consulta:', error);
167
+ document.getElementById('response').innerText = `Error al procesar la solicitud: ${error.message}`;
168
  }
169
  }
170
  </script>