File size: 4,493 Bytes
ce79bba
 
 
 
 
 
42dc88d
 
 
 
 
6d97a28
 
ce79bba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3524a2f
 
ce79bba
 
3524a2f
ce79bba
 
3524a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce79bba
 
 
 
6d97a28
42dc88d
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
111
112
113
114
115
116
117
118
119
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modelo de Preguntas y Respuestas sobre un PDF</title>
    
    <!-- Cargar pdf.js desde un CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
    <script>
        // Configuraci贸n del worker de pdf.js
        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 sobre un PDF</h1>
    
    <input type="file" id="pdfInput" />
    <button onclick="procesarPDF()">Cargar PDF</button>

    <h2>Preguntar sobre el PDF</h2>
    <input type="text" id="inputPregunta" placeholder="Escribe tu pregunta aqu铆">
    <button onclick="responderPregunta()">Hacer pregunta</button>

    <h3>Respuesta:</h3>
    <div id="respuesta"></div>

    <script>
        // Variable global para almacenar el texto del PDF
        let textoPDF = "";

        // Cargar y procesar el archivo PDF
        async function procesarPDF() {
            const archivo = document.getElementById("pdfInput").files[0];
            if (archivo) {
                const archivoPDF = await leerPDF(archivo);
                textoPDF = archivoPDF.join(" ");
                alert("PDF cargado y procesado.");
            }
        }

        // Leer y extraer el texto del archivo PDF
        async function leerPDF(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 texto = [];
                    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(" ");
                        texto.push(textoPagina);
                    }
                    resolve(texto);
                };
                lector.onerror = reject;
                lector.readAsArrayBuffer(archivo);
            });
        }

        // Funci贸n para responder una pregunta utilizando el texto del PDF
        async function responderPregunta() {
            const pregunta = document.getElementById("inputPregunta").value;
            if (!textoPDF) {
                alert("Por favor, cargue un PDF primero.");
                return;
            }

            // Enviar la pregunta y el texto del PDF a la API de Hugging Face para obtener la respuesta
            const respuesta = await obtenerRespuestaDeModelo(pregunta, textoPDF);

            // Mostrar la respuesta
            document.getElementById("respuesta").innerText = "Respuesta: " + respuesta;
        }

        // Funci贸n para obtener respuesta utilizando el modelo BERT de Hugging Face
        async function obtenerRespuestaDeModelo(pregunta, contexto) {
            const endpoint = "https://api-inference.huggingface.co/models/deepset/roberta-large-squad2"; // Usar el modelo BERT o RoBERTa preentrenado
            const token = 'tu_token_de_huggingface'; // Sustituye con tu token de Hugging Face

            const requestData = {
                inputs: {
                    question: pregunta,
                    context: contexto
                }
            };

            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                const data = await response.json();

                // Extraer la respuesta del modelo
                if (data && data.answer) {
                    return data.answer;
                } else {
                    return "No se pudo encontrar una respuesta.";
                }

            } catch (error) {
                console.error("Error al obtener la respuesta de Hugging Face:", error);
                return "Error al obtener la respuesta.";
            }
        }
    </script>
</body>
</html>