File size: 4,284 Bytes
3d7962f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!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 desde PDFs</title>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/qna"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
    <script>
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';
    </script>
</head>
<body>
    <h1>Modelo de Preguntas y Respuestas a partir de PDFs</h1>

    <!-- Carga de PDFs -->
    <h2>Cargar PDFs</h2>
    <input type="file" id="pdfInput" multiple accept=".pdf" />
    <button onclick="cargarPDFs()">Cargar PDFs</button>
    <div id="statusCarga"></div>

    <!-- Preguntas -->
    <h2>Realizar una pregunta</h2>
    <input type="text" id="preguntaInput" placeholder="Escribe tu pregunta aqu铆" />
    <button onclick="realizarPregunta()">Preguntar</button>
    <div>
        <h3>Respuesta:</h3>
        <p id="respuesta"></p>
    </div>

    <script>
        // Variable global para almacenar el texto extra铆do de los PDFs
        let contextoGlobal = "";

        // Carga y procesamiento de PDFs
        async function cargarPDFs() {
            const archivos = document.getElementById("pdfInput").files;
            if (archivos.length === 0) {
                alert("Por favor, selecciona uno o m谩s archivos PDF.");
                return;
            }

            const textos = [];
            for (const archivo of archivos) {
                const texto = await extraerTextoPDF(archivo);
                textos.push(texto);
            }

            // Unir todo el texto en un contexto global
            contextoGlobal = textos.join(" ");
            document.getElementById("statusCarga").innerText = "PDFs cargados y procesados correctamente.";
        }

        // Funci贸n para extraer texto de un archivo PDF
        async function extraerTextoPDF(archivo) {
            const lector = new FileReader();
            return new Promise((resolve, reject) => {
                lector.onload = async function (e) {
                    const arrayBuffer = e.target.result;
                    const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
                    let textoCompleto = "";

                    for (let i = 1; i <= pdf.numPages; i++) {
                        const pagina = await pdf.getPage(i);
                        const contenido = await pagina.getTextContent();
                        const textoPagina = contenido.items.map(item => item.str).join(" ");
                        textoCompleto += textoPagina + "\n";
                    }
                    resolve(textoCompleto);
                };
                lector.onerror = reject;
                lector.readAsArrayBuffer(archivo);
            });
        }

        // Modelo de Preguntas y Respuestas usando TensorFlow.js
        let modelo = null;

        // Funci贸n para realizar una pregunta
        async function realizarPregunta() {
            const pregunta = document.getElementById("preguntaInput").value;
            if (!contextoGlobal) {
                alert("Primero debes cargar los PDFs para generar el contexto.");
                return;
            }
            if (!pregunta) {
                alert("Por favor, escribe una pregunta.");
                return;
            }

            if (!modelo) {
                document.getElementById("respuesta").innerText = "Cargando modelo, por favor espera...";
                modelo = await qna.load(); // Cargar el modelo QnA basado en DistilBERT
            }

            // Realizar la pregunta
            const respuestas = await modelo.findAnswers(pregunta, contextoGlobal);

            // Mostrar la mejor respuesta o un mensaje si no se encontr贸 ninguna
            if (respuestas.length > 0) {
                document.getElementById("respuesta").innerText = respuestas[0].text;
            } else {
                document.getElementById("respuesta").innerText = "No se encontr贸 una respuesta adecuada.";
            }
        }
    </script>
</body>
</html>