Spaces:
Runtime error
Runtime error
fcernafukuzaki
commited on
Commit
•
bb55334
1
Parent(s):
9a9f123
Upload 3 files
Browse files- app.py +114 -0
- demo-inmobiliaria.json +0 -0
- requirements.txt +7 -0
app.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import gradio as gr
|
3 |
+
from pathlib import Path
|
4 |
+
import os
|
5 |
+
import pandas as pd
|
6 |
+
import openai
|
7 |
+
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, ServiceContext
|
8 |
+
from langchain.chat_models import ChatOpenAI
|
9 |
+
import textwrap
|
10 |
+
|
11 |
+
# Procesar datos de PDF
|
12 |
+
from langchain.document_loaders import PyPDFLoader
|
13 |
+
from langchain.text_splitter import CharacterTextSplitter
|
14 |
+
|
15 |
+
#import gradio as gr
|
16 |
+
from openai.embeddings_utils import get_embedding
|
17 |
+
from openai.embeddings_utils import cosine_similarity
|
18 |
+
|
19 |
+
|
20 |
+
# API KEY OPENAI
|
21 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
22 |
+
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
23 |
+
|
24 |
+
|
25 |
+
class ChatBotInmobiliaria():
|
26 |
+
def __init__(self):
|
27 |
+
self.embedding_engine = "text-embedding-ada-002"
|
28 |
+
self.model_name = "gpt-3.5-turbo"
|
29 |
+
self.index = None
|
30 |
+
|
31 |
+
def create_dataset(self, directory_path, filepath_dataset):
|
32 |
+
# directory_path: Directorio donde se ubican los archivos PDF.
|
33 |
+
# filepath_dataset: Nombre del archivo JSON vectorizado.
|
34 |
+
if directory_path != None:
|
35 |
+
#Leer los PDFs
|
36 |
+
pdf = SimpleDirectoryReader(directory_path).load_data()
|
37 |
+
#Definir e instanciar el modelo
|
38 |
+
modelo = LLMPredictor(llm=ChatOpenAI(temperature=0, model_name=self.model_name))
|
39 |
+
#Indexar el contenido de los PDFs
|
40 |
+
service_context = ServiceContext.from_defaults(llm_predictor=modelo)
|
41 |
+
self.index = GPTSimpleVectorIndex.from_documents(pdf, service_context = service_context)
|
42 |
+
self.__save_model(filepath_dataset)
|
43 |
+
|
44 |
+
def __save_model(self, filepath):
|
45 |
+
#Guardar el índice a disco para no tener que repetir cada vez
|
46 |
+
#Recordar que necesistaríamos persistir el drive para que lo mantenga
|
47 |
+
self.index.save_to_disk(filepath)
|
48 |
+
|
49 |
+
def load_dataset(self, filepath):
|
50 |
+
#Cargar el índice del disco
|
51 |
+
self.index = GPTSimpleVectorIndex.load_from_disk(filepath)
|
52 |
+
|
53 |
+
def ask(self, question=""):
|
54 |
+
if len(question) == 0:
|
55 |
+
print("Debe de ingresar una pregunta.")
|
56 |
+
try:
|
57 |
+
return self.index.query(question)
|
58 |
+
except Exception as e:
|
59 |
+
print(e)
|
60 |
+
return "Hubo un error."
|
61 |
+
|
62 |
+
def ask(dataset, pregunta):
|
63 |
+
if dataset is None:
|
64 |
+
return ""
|
65 |
+
path_file = dataset.name
|
66 |
+
extension = os.path.splitext(path_file)[1]
|
67 |
+
dir_name = str(Path(path_file).parent)
|
68 |
+
|
69 |
+
if extension.lower() == ".pdf":
|
70 |
+
chatbot = ChatBotInmobiliaria()
|
71 |
+
DATASET_JSON = "dataset_file.json"
|
72 |
+
chatbot.create_dataset(dir_name, DATASET_JSON)
|
73 |
+
chatbot.load_dataset(DATASET_JSON)
|
74 |
+
chatbot.load_dataset(path_file)
|
75 |
+
return chatbot.ask(question=pregunta)
|
76 |
+
elif extension.lower() == ".json":
|
77 |
+
chatbot = ChatBotInmobiliaria()
|
78 |
+
chatbot.load_dataset(path_file)
|
79 |
+
print("otro paso")
|
80 |
+
return chatbot.ask(question=pregunta)
|
81 |
+
|
82 |
+
|
83 |
+
|
84 |
+
# Gradio
|
85 |
+
|
86 |
+
description ="""
|
87 |
+
<p>
|
88 |
+
<center>
|
89 |
+
Demo Inmobiliaria, el objetivo es responder preguntas a través de OpenAI previamente entrenado con un archivo PDF.
|
90 |
+
<img src="https://raw.githubusercontent.com/All-Aideas/sea_apirest/main/logo.png" alt="logo" width="250"/>
|
91 |
+
</center>
|
92 |
+
</p>
|
93 |
+
"""
|
94 |
+
|
95 |
+
article = "<p style='text-align: center'><a href='http://allaideas.com/index.html' target='_blank'>Demo Inmobiliaria: Link para más info</a> </p>"
|
96 |
+
|
97 |
+
in1 = gr.inputs.File(label="Archivo PDF")
|
98 |
+
in2 = gr.inputs.Textbox(label="Pregunta")
|
99 |
+
out1 = gr.outputs.Textbox(label="Respuesta")
|
100 |
+
|
101 |
+
examples = [["demo-inmobiliaria.json", "¿Qué regulaciones tengo para comprar una vivienda?"]]
|
102 |
+
|
103 |
+
demo = gr.Interface(
|
104 |
+
fn=ask,
|
105 |
+
inputs=[in1, in2],
|
106 |
+
outputs=out1,
|
107 |
+
title="Demo Inmobiliaria",
|
108 |
+
description=description,
|
109 |
+
article=article,
|
110 |
+
enable_queue=True,
|
111 |
+
examples=examples,
|
112 |
+
)
|
113 |
+
|
114 |
+
demo.launch(debug=True)
|
demo-inmobiliaria.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
plotly
|
3 |
+
scikit-learn
|
4 |
+
PyPDF2
|
5 |
+
openai
|
6 |
+
langchain
|
7 |
+
llama-index==0.5.25
|