mundo2333 commited on
Commit
04d3842
·
1 Parent(s): 76aa528

Upload streamlit app to ask ChatGpt about PDF

Browse files
Files changed (5) hide show
  1. README.md +43 -12
  2. app.py +57 -0
  3. archivos.txt +0 -0
  4. requirements.txt +6 -0
  5. utils.py +92 -0
README.md CHANGED
@@ -1,12 +1,43 @@
1
- ---
2
- title: Tarea
3
- emoji: 💻
4
- colorFrom: blue
5
- colorTo: indigo
6
- sdk: streamlit
7
- sdk_version: 1.29.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # 🧮🗨️ Pinecone y ChatGPT | Tutorial Base de Datos Vectorial desde 0
3
+ ### Convierte a ChatGPT en tu Asistente Personal de Búsqueda de Documentos
4
+
5
+ 🚀 [Tutorial en Español | Youtube](https://youtu.be/adq0BFxQ4C0)
6
+
7
+ ¿Qué es una base de datos vectorial? En este taller, exploraremos Pinecone, una de las bases de datos vectoriales líderes en la nube. Este tipo de bases de datos ha ganado una gran popularidad en los últimos meses. ¿Son realmente útiles? Lo comprobaremos en el tutorial paso a paso.
8
+
9
+ Además, ¿sabías que ChatGPT puede mantener conversaciones con documentos? En este taller de Python, descubriremos cómo hacerlo posible gracias a Pinecone. Olvídate de las limitaciones, ahora podrás conversar y explorar tus documentos de una manera completamente nueva.
10
+
11
+
12
+ Para desarrollar esta aplicación necesitaremos:
13
+ * Cuenta en Pinecone
14
+ * ChatGPT API
15
+ * Streamlit
16
+
17
+
18
+ ## ¿Cómo funciona?
19
+ 1. Divide documento en cachos (o chunks)
20
+ 2. Crea los embeddings de los cachos de texto
21
+ 3. Guarda los cachos y los embeddings en Pinecone
22
+ 4. Busca los cachos más similares a la pregunta del usuario gracias a los embeddings.
23
+ 5. Pasa los cachos más similares junto a la pregunta a ChatGPT que genera la respuesta
24
+
25
+
26
+ ## Instalación
27
+ ¡Usar este código es fácil! Aquí están los pasos:
28
+ 1. Clone o descargue el repositorio en su máquina local.
29
+ 2. Instale las bibliotecas requeridas ejecutando el siguiente comando en su terminal:
30
+ ```console
31
+ pip install -r requirements.txt
32
+ ```
33
+ 3. Obtenga una clave API de OpenAI para usar su API ChatGPT.
34
+ 4. Obtenga una clave API de Pinecone.
35
+ 5. Ejecute la aplicación con el siguiente comando:
36
+ ```console
37
+ streamlit run app.py
38
+ ```
39
+ 6. Suba un documento a la aplicación.
40
+ 7. Escriba su pregunta y disfrute de la magia.
41
+
42
+
43
+ 🎥 [Más vídeos en mi canal de Youtube](https://www.youtube.com/@NechuBM)
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from utils import *
4
+ from langchain.vectorstores import Pinecone
5
+ from langchain.embeddings import HuggingFaceEmbeddings
6
+ from langchain.chat_models import ChatOpenAI
7
+ from langchain.chains.question_answering import load_qa_chain
8
+
9
+ FILE_LIST = "archivos.txt"
10
+ OPENAI_API_KEY = "Añadir OpenAI API Key"
11
+
12
+ st.set_page_config('preguntaDOC')
13
+ st.header("Pregunta a tu PDF")
14
+
15
+ with st.sidebar:
16
+ archivos = load_name_files(FILE_LIST)
17
+ files_uploaded = st.file_uploader(
18
+ "Carga tu archivo",
19
+ type="pdf",
20
+ accept_multiple_files=True
21
+ )
22
+
23
+ if st.button('Procesar'):
24
+ for pdf in files_uploaded:
25
+ if pdf is not None and pdf.name not in archivos:
26
+ archivos.append(pdf.name)
27
+ text_to_pinecone(pdf)
28
+
29
+ archivos = save_name_files(FILE_LIST, archivos)
30
+
31
+ if len(archivos)>0:
32
+ st.write('Archivos Cargados:')
33
+ lista_documentos = st.empty()
34
+ with lista_documentos.container():
35
+ for arch in archivos:
36
+ st.write(arch)
37
+ if st.button('Borrar Documentos'):
38
+ archivos = []
39
+ clean_files(FILE_LIST)
40
+ lista_documentos.empty()
41
+
42
+
43
+ if len(archivos)>0:
44
+ user_question = st.text_input("Pregunta: ")
45
+ if user_question:
46
+ os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
47
+ embeddings = HuggingFaceEmbeddings(
48
+ model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
49
+ )
50
+ vstore = Pinecone.from_existing_index(INDEX_NAME, embeddings)
51
+
52
+ docs = vstore.similarity_search(user_question, 3)
53
+ llm = ChatOpenAI(model_name='gpt-3.5-turbo')
54
+ chain = load_qa_chain(llm, chain_type="stuff")
55
+ respuesta = chain.run(input_documents=docs, question=user_question)
56
+
57
+ st.write(respuesta)
archivos.txt ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openai
2
+ langchain
3
+ streamlit
4
+ pypdf
5
+ pinecone-client
6
+ sentence_transformers
utils.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import streamlit as st
4
+
5
+ import pinecone
6
+ import tempfile
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain.document_loaders import PyPDFLoader
9
+ from langchain.vectorstores import Pinecone
10
+ from langchain.embeddings import HuggingFaceEmbeddings
11
+
12
+
13
+ FILE_LIST = "archivos.txt"
14
+ PINECONE_API_KEY = "Añadir Pinecone API Key"
15
+ PINECONE_ENV = "Añadir Pinecone Env"
16
+ INDEX_NAME = 'taller'
17
+
18
+ pinecone.init(
19
+ api_key=PINECONE_API_KEY,
20
+ environment=PINECONE_ENV
21
+ )
22
+
23
+
24
+ def save_name_files(path, new_files):
25
+
26
+ old_files = load_name_files(path)
27
+
28
+ with open(path, "a") as file:
29
+ for item in new_files:
30
+ if item not in old_files:
31
+ file.write(item + "\n")
32
+ old_files.append(item)
33
+
34
+ return old_files
35
+
36
+
37
+ def load_name_files(path):
38
+
39
+ archivos = []
40
+ with open(path, "r") as file:
41
+ for line in file:
42
+ archivos.append(line.strip())
43
+
44
+ return archivos
45
+
46
+
47
+ def clean_files(path):
48
+ with open(path, "w") as file:
49
+ pass
50
+ index = pinecone.Index(INDEX_NAME)
51
+ index.delete(delete_all=True)
52
+
53
+ return True
54
+
55
+
56
+ def text_to_pinecone(pdf):
57
+
58
+ temp_dir = tempfile.TemporaryDirectory()
59
+ temp_filepath = os.path.join(temp_dir.name, pdf.name)
60
+ with open(temp_filepath, "wb") as f:
61
+ f.write(pdf.getvalue())
62
+
63
+ loader = PyPDFLoader(temp_filepath)
64
+ text = loader.load()
65
+
66
+ with st.spinner(f'Creando embedding fichero: {pdf.name}'):
67
+ create_embeddings(pdf.name, text)
68
+
69
+ return True
70
+
71
+
72
+ def create_embeddings(file_name, text):
73
+ print(f"Creando embeddings del archivo: {file_name}")
74
+
75
+ text_splitter = RecursiveCharacterTextSplitter(
76
+ chunk_size=800,
77
+ chunk_overlap=100,
78
+ length_function=len
79
+ )
80
+
81
+ chunks = text_splitter.split_documents(text)
82
+
83
+ embeddings = HuggingFaceEmbeddings(
84
+ model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
85
+ )
86
+
87
+ Pinecone.from_documents(
88
+ chunks,
89
+ embeddings,
90
+ index_name=INDEX_NAME)
91
+
92
+ return True