Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Imports
|
2 |
+
from langchain.document_loaders import PyPDFLoader
|
3 |
+
import os
|
4 |
+
from langchain.chains import RetrievalQA, ConversationalRetrievalChain
|
5 |
+
from langchain.indexes import VectorstoreIndexCreator
|
6 |
+
from langchain.text_splitter import CharacterTextSplitter, TokenTextSplitter
|
7 |
+
from langchain.embeddings import OpenAIEmbeddings, HuggingFaceEmbeddings
|
8 |
+
from langchain.vectorstores import Chroma
|
9 |
+
from langchain import HuggingFacePipeline
|
10 |
+
from langchain.chat_models import ChatOpenAI
|
11 |
+
from dotenv import load_dotenv
|
12 |
+
from langchain.memory import ConversationBufferMemory, ConversationTokenBufferMemory
|
13 |
+
import gradio as gr
|
14 |
+
|
15 |
+
# Funcion de carga de la api key
|
16 |
+
def process_key(api_key):
|
17 |
+
os.environ['OPENAI_API_KEY'] = api_key
|
18 |
+
|
19 |
+
def load_pdf(file):
|
20 |
+
name_file = file.name
|
21 |
+
print(file.name)
|
22 |
+
loader = PyPDFLoader(file.name)
|
23 |
+
documents = loader.load()
|
24 |
+
print(documents)
|
25 |
+
# Creo el objeto que permite dividir el texto en chunks
|
26 |
+
text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=64)
|
27 |
+
# Esto lo que hace es dividir el texto en chunks de 2048 caracteres con un overlap de 128 caracteres
|
28 |
+
texts = text_splitter.split_documents(documents)
|
29 |
+
# Genero el objeto que crea los embeddings
|
30 |
+
# Nota: Estos embeddings son gratuitos a diferencia de los de OpenAI
|
31 |
+
embeddings = HuggingFaceEmbeddings()
|
32 |
+
# Defino el modelo de lenguaje
|
33 |
+
llm = ChatOpenAI(model='gpt-3.5-turbo', temperature=0.0, max_tokens=1000)
|
34 |
+
# Creo la base de datos de vectores
|
35 |
+
global vectorstore
|
36 |
+
vectorstore = Chroma.from_documents(texts, embeddings)
|
37 |
+
# Defino la memoria
|
38 |
+
|
39 |
+
global memory
|
40 |
+
# La definicion de Memoria no es trivial, es bastante compleja de hecho se deben especificar bien todos los parameteros para que no de error
|
41 |
+
memory = ConversationTokenBufferMemory(llm=llm,
|
42 |
+
memory_key="chat_history",
|
43 |
+
input_key='question',
|
44 |
+
output_key='answer',
|
45 |
+
max_token_limit=1000,
|
46 |
+
return_messages=False)
|
47 |
+
# Defino la cadena de qa
|
48 |
+
global qa
|
49 |
+
qa = ConversationalRetrievalChain.from_llm(llm,
|
50 |
+
vectorstore.as_retriever(search_kwargs={'k': 3}), # Este parametro especifica cuantos chunks se van a recuperar
|
51 |
+
return_source_documents=True,
|
52 |
+
verbose=True,
|
53 |
+
chain_type='stuff',
|
54 |
+
memory=memory,
|
55 |
+
max_tokens_limit=2500,
|
56 |
+
get_chat_history=lambda h: h)
|
57 |
+
return 'Done'
|
58 |
+
|
59 |
+
# Funcion que ejecuta LLM y responde la pregunta
|
60 |
+
def answer_question(question):
|
61 |
+
result = qa(inputs={'question': question})
|
62 |
+
pages = [x.metadata['page'] for i, x in enumerate(result['source_documents'])]
|
63 |
+
return result['answer'], pages
|
64 |
+
|
65 |
+
# Funcion que pega las respuestas anteriores en el objeto Chat bot
|
66 |
+
def bot(history):
|
67 |
+
res = qa(
|
68 |
+
{
|
69 |
+
'question': history[-1][0],
|
70 |
+
'chat_history': history[:-1]
|
71 |
+
}
|
72 |
+
)
|
73 |
+
history[-1][1] = res['answer']
|
74 |
+
return history
|
75 |
+
|
76 |
+
# Agrego el texto a la historia del chat
|
77 |
+
def add_text(history, text):
|
78 |
+
history = history + [(text, None)]
|
79 |
+
return history, ""
|
80 |
+
|
81 |
+
# Analizar como parsea las ecuaciones
|
82 |
+
with gr.Blocks() as demo:
|
83 |
+
with gr.Tab(label='Load PDF'):
|
84 |
+
with gr.Row():
|
85 |
+
with gr.Column():
|
86 |
+
open_ai_key = gr.Textbox(label='Ingresa tu api key de Open AI', type='password')
|
87 |
+
with gr.Row():
|
88 |
+
with gr.Column(scale=0.4):
|
89 |
+
api_key_button = gr.Button('Enviar', variant='primary')
|
90 |
+
with gr.Row():
|
91 |
+
pdf_file = gr.File(label='PDF file')
|
92 |
+
# Esta linea esta para probar si el calculo se realiza
|
93 |
+
emb = gr.Textbox(label='Calculo de Embeddings, por favor espere...')
|
94 |
+
# send_pdf = gr.Button(label='Load PDF').style(full_width=False)
|
95 |
+
with gr.Row():
|
96 |
+
with gr.Column(scale=0.50):
|
97 |
+
send_pdf = gr.Button(label='Load PDF')
|
98 |
+
send_pdf.click(load_pdf, pdf_file, emb)
|
99 |
+
with gr.Tab(label='Galicia QA Demo'):
|
100 |
+
chatbot = gr.Chatbot([],
|
101 |
+
elem_id="chatbot",
|
102 |
+
label='Document GPT').style(height=500)
|
103 |
+
with gr.Row():
|
104 |
+
with gr.Column(scale=0.80):
|
105 |
+
txt = gr.Textbox(
|
106 |
+
show_label=False,
|
107 |
+
placeholder="Enter text and press enter",
|
108 |
+
).style(container=False)
|
109 |
+
|
110 |
+
with gr.Column(scale=0.10):
|
111 |
+
submit_btn = gr.Button(
|
112 |
+
'Submit',
|
113 |
+
variant='primary'
|
114 |
+
)
|
115 |
+
|
116 |
+
with gr.Column(scale=0.10):
|
117 |
+
clear_btn = gr.Button(
|
118 |
+
'Clear',
|
119 |
+
variant='stop'
|
120 |
+
)
|
121 |
+
# Tanto el submit (hacer enter en el campo de texto) como el submit_btn hacen la misma accion
|
122 |
+
txt.submit(fn=add_text, inputs=[chatbot, txt], outputs=[chatbot, txt] # Cuando envio el submit hago esta funcion
|
123 |
+
).then(fn=bot, inputs=chatbot, outputs=chatbot) # Luego hago esta otra funcion
|
124 |
+
|
125 |
+
submit_btn.click(fn=add_text, inputs=[chatbot, txt], outputs=[chatbot, txt]
|
126 |
+
).then(fn=bot, inputs=chatbot, outputs=chatbot)
|
127 |
+
|
128 |
+
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
129 |
+
|
130 |
+
api_key_button.click(fn=process_key, inputs=[open_ai_key], outputs=None)
|
131 |
+
|
132 |
+
demo.launch(inline=False)
|