Spaces:
Running
Running
Update test5.html
Browse files- 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
|
7 |
-
<
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
10 |
</head>
|
11 |
<body>
|
12 |
-
<h1>
|
13 |
|
14 |
-
|
15 |
-
<
|
|
|
16 |
|
|
|
|
|
17 |
<label for="question">Pregunta:</label>
|
18 |
-
<input type="text" id="question" placeholder="Escribe tu pregunta aquí"
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
<h3>Respuesta:</h3>
|
22 |
<div id="response"></div>
|
23 |
|
|
|
|
|
|
|
24 |
<script>
|
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 |
-
reader.readAsArrayBuffer(file);
|
51 |
}
|
52 |
|
53 |
-
//
|
54 |
-
function
|
55 |
-
const
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
}
|
61 |
|
62 |
-
//
|
63 |
-
function
|
64 |
-
|
65 |
-
|
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 |
-
//
|
78 |
-
|
79 |
-
const
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
92 |
|
93 |
-
//
|
94 |
async function askQuestion() {
|
95 |
const question = document.getElementById('question').value;
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
98 |
return;
|
99 |
}
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
// Preparamos los datos para la consulta
|
107 |
const data = {
|
108 |
inputs: {
|
109 |
-
question: question,
|
110 |
-
context:
|
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 |
-
|
119 |
-
const response = await fetch(modelUrl, {
|
120 |
method: 'POST',
|
121 |
headers: {
|
122 |
-
'Authorization': 'Bearer ' + cucu,
|
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 |
-
|
134 |
-
|
135 |
-
|
|
|
|
|
|
|
136 |
} catch (error) {
|
137 |
console.error('Error al hacer la consulta:', error);
|
138 |
-
alert('Hubo un error al procesar la solicitud
|
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 |
+
|