www / test5.html
eduardmtz's picture
Update test5.html
8482b1a verified
<!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>