Spaces:
Runtime error
Runtime error
Jose Alvaro Luna G
commited on
Commit
路
c5446a2
1
Parent(s):
e5da8b5
feat: app init
Browse files- extract_text.py +21 -0
- main.py +99 -4
- requirements.txt +9 -0
extract_text.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# extract_text.py
|
2 |
+
from pdfminer.high_level import extract_text
|
3 |
+
from docx import Document
|
4 |
+
import pytesseract
|
5 |
+
from PIL import Image
|
6 |
+
|
7 |
+
def extract_text_from_image(file_path):
|
8 |
+
image = Image.open(file_path)
|
9 |
+
text = pytesseract.image_to_string(image)
|
10 |
+
return text
|
11 |
+
|
12 |
+
def extract_text_from_docx(file_path):
|
13 |
+
doc = Document(file_path)
|
14 |
+
full_text = []
|
15 |
+
for para in doc.paragraphs:
|
16 |
+
full_text.append(para.text)
|
17 |
+
return '\n'.join(full_text)
|
18 |
+
|
19 |
+
def extract_text_from_pdf(file_path):
|
20 |
+
text = extract_text(file_path)
|
21 |
+
return text
|
main.py
CHANGED
@@ -1,7 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
|
3 |
-
|
4 |
-
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import torch
|
3 |
+
from transformers import (
|
4 |
+
DPRContextEncoder, DPRContextEncoderTokenizerFast,
|
5 |
+
DPRQuestionEncoder, DPRQuestionEncoderTokenizerFast,
|
6 |
+
BartForConditionalGeneration, BartTokenizer
|
7 |
+
)
|
8 |
+
from datasets import Dataset
|
9 |
+
import faiss
|
10 |
+
import numpy as np
|
11 |
import gradio as gr
|
12 |
|
13 |
+
# Importar funciones de extracci贸n
|
14 |
+
from extract_text import extract_text_from_pdf, extract_text_from_docx, extract_text_from_image
|
15 |
|
16 |
+
# Inicializar modelos y variables globales
|
17 |
+
ctx_encoder = DPRContextEncoder.from_pretrained('facebook/dpr-ctx_encoder-single-nq-base')
|
18 |
+
ctx_tokenizer = DPRContextEncoderTokenizerFast.from_pretrained('facebook/dpr-ctx_encoder-single-nq-base')
|
19 |
+
|
20 |
+
q_encoder = DPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base')
|
21 |
+
q_tokenizer = DPRQuestionEncoderTokenizerFast.from_pretrained('facebook/dpr-question_encoder-single-nq-base')
|
22 |
+
|
23 |
+
generator = BartForConditionalGeneration.from_pretrained('facebook/bart-large')
|
24 |
+
gen_tokenizer = BartTokenizer.from_pretrained('facebook/bart-large')
|
25 |
+
|
26 |
+
# Inicializar dataset y 铆ndice
|
27 |
+
dataset = Dataset.from_dict({'text': []})
|
28 |
+
embeddings = np.empty((0, ctx_encoder.config.hidden_size), dtype='float32')
|
29 |
+
index = faiss.IndexFlatIP(ctx_encoder.config.hidden_size)
|
30 |
+
|
31 |
+
# Funci贸n para actualizar el 铆ndice con nuevo texto
|
32 |
+
def actualizar_indice(nuevo_texto):
|
33 |
+
global dataset, embeddings, index
|
34 |
+
|
35 |
+
# A帽adir nuevo documento al dataset
|
36 |
+
dataset = dataset.add_item({'text': nuevo_texto})
|
37 |
+
|
38 |
+
# Codificar el nuevo documento
|
39 |
+
inputs = ctx_tokenizer(nuevo_texto, truncation=True, padding='longest', return_tensors='pt')
|
40 |
+
embedding = ctx_encoder(**inputs).pooler_output.detach().numpy()
|
41 |
+
|
42 |
+
# Actualizar embeddings y 铆ndice
|
43 |
+
embeddings = np.vstack([embeddings, embedding])
|
44 |
+
index.add(embedding)
|
45 |
+
|
46 |
+
# Funci贸n para recuperar documentos relevantes
|
47 |
+
def retrieve_docs(question, k=5):
|
48 |
+
inputs = q_tokenizer(question, return_tensors='pt')
|
49 |
+
question_embedding = q_encoder(**inputs).pooler_output.detach().numpy()
|
50 |
+
|
51 |
+
distances, indices = index.search(question_embedding, k)
|
52 |
+
retrieved_texts = [dataset[i]['text'] for i in indices[0]]
|
53 |
+
return retrieved_texts
|
54 |
+
|
55 |
+
# Funci贸n para generar respuesta
|
56 |
+
def generate_answer(question):
|
57 |
+
retrieved_docs = retrieve_docs(question)
|
58 |
+
context = ' '.join(retrieved_docs)
|
59 |
+
|
60 |
+
input_text = f"Pregunta: {question} Contexto: {context}"
|
61 |
+
inputs = gen_tokenizer([input_text], max_length=1024, return_tensors='pt', truncation=True)
|
62 |
+
summary_ids = generator.generate(inputs['input_ids'], num_beams=4, max_length=100, early_stopping=True)
|
63 |
+
answer = gen_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
64 |
+
return answer
|
65 |
+
|
66 |
+
# Funci贸n principal de la aplicaci贸n
|
67 |
+
def responder(archivo, pregunta):
|
68 |
+
texto_extraido = ''
|
69 |
+
if archivo is not None:
|
70 |
+
file_path = archivo.name
|
71 |
+
if file_path.endswith('.pdf'):
|
72 |
+
texto_extraido = extract_text_from_pdf(file_path)
|
73 |
+
elif file_path.endswith('.docx'):
|
74 |
+
texto_extraido = extract_text_from_docx(file_path)
|
75 |
+
elif file_path.lower().endswith(('.png', '.jpg', '.jpeg')):
|
76 |
+
texto_extraido = extract_text_from_image(file_path)
|
77 |
+
else:
|
78 |
+
return "Formato de archivo no soportado."
|
79 |
+
|
80 |
+
# Actualizar el 铆ndice con el nuevo texto
|
81 |
+
actualizar_indice(texto_extraido)
|
82 |
+
|
83 |
+
# Generar respuesta
|
84 |
+
respuesta = generate_answer(pregunta)
|
85 |
+
return respuesta
|
86 |
+
else:
|
87 |
+
return "Por favor, sube un archivo."
|
88 |
+
|
89 |
+
# Configurar la interfaz de Gradio
|
90 |
+
interfaz = gr.Interface(
|
91 |
+
fn=responder,
|
92 |
+
inputs=[
|
93 |
+
gr.inputs.File(label="Sube un archivo (PDF, DOCX, Imagen)"),
|
94 |
+
gr.inputs.Textbox(lines=2, placeholder="Escribe tu pregunta aqu铆...")
|
95 |
+
],
|
96 |
+
outputs="text",
|
97 |
+
title="Aplicaci贸n RAG con Extracci贸n de Texto",
|
98 |
+
description="Sube un archivo y haz una pregunta sobre su contenido."
|
99 |
+
)
|
100 |
+
|
101 |
+
if __name__ == "__main__":
|
102 |
+
interfaz.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
transformers
|
2 |
+
datasets
|
3 |
+
faiss-cpu
|
4 |
+
gradio
|
5 |
+
pytesseract
|
6 |
+
Pillow
|
7 |
+
pdfminer.six
|
8 |
+
python-docx
|
9 |
+
torch
|