Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,202 +1,212 @@
|
|
1 |
-
# app.py
|
2 |
-
|
3 |
-
import os
|
4 |
-
import sys
|
5 |
-
import logging
|
6 |
-
from getpass import getpass
|
7 |
-
from langchain.embeddings import OpenAIEmbeddings
|
8 |
-
from langchain.vectorstores import Chroma
|
9 |
-
from langchain.chat_models import ChatOpenAI
|
10 |
-
from langchain.chains.question_answering import load_qa_chain
|
11 |
-
from langchain.prompts import ChatPromptTemplate
|
12 |
-
import gradio as gr
|
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 |
-
return "
|
116 |
-
|
117 |
-
#
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
return "
|
151 |
-
|
152 |
-
#
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
#
|
178 |
-
|
179 |
-
#
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
import logging
|
6 |
+
from getpass import getpass
|
7 |
+
from langchain.embeddings import OpenAIEmbeddings
|
8 |
+
from langchain.vectorstores import Chroma
|
9 |
+
from langchain.chat_models import ChatOpenAI
|
10 |
+
from langchain.chains.question_answering import load_qa_chain
|
11 |
+
from langchain.prompts import ChatPromptTemplate
|
12 |
+
import gradio as gr
|
13 |
+
|
14 |
+
|
15 |
+
zip_file = '/content/vectors (2).zip' # Replace with your zip file path
|
16 |
+
|
17 |
+
# Step 2: Unzip the file
|
18 |
+
!unzip -q "{zip_file}" -d "/content/properties_vectors"
|
19 |
+
|
20 |
+
print("Unzipping completed.")
|
21 |
+
|
22 |
+
|
23 |
+
|
24 |
+
# Setup logging
|
25 |
+
logging.basicConfig(level=logging.INFO)
|
26 |
+
logger = logging.getLogger(__name__)
|
27 |
+
|
28 |
+
# Function to get the absolute path
|
29 |
+
def get_absolute_path(relative_path):
|
30 |
+
if getattr(sys, 'frozen', False):
|
31 |
+
# If the application is run as a bundle, the PyInstaller bootloader
|
32 |
+
# extends the sys module by a flag frozen=True and sets the app
|
33 |
+
# path into variable _MEIPASS'.
|
34 |
+
base_path = sys._MEIPASS
|
35 |
+
else:
|
36 |
+
base_path = os.path.abspath(".")
|
37 |
+
return os.path.join(base_path, relative_path)
|
38 |
+
|
39 |
+
# Retrieve OpenAI API key from environment variable or prompt
|
40 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
41 |
+
if not openai_api_key:
|
42 |
+
openai_api_key = getpass("Enter your OpenAI API key2: ")
|
43 |
+
os.environ["OPENAI_API_KEY"] = openai_api_key
|
44 |
+
|
45 |
+
# Initialize embeddings
|
46 |
+
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
|
47 |
+
|
48 |
+
# Function to list available vector store directories
|
49 |
+
def list_vectorstore_directories(base_path='vectorstores'):
|
50 |
+
"""
|
51 |
+
Lists all subdirectories in the base_path which are potential vector store directories.
|
52 |
+
"""
|
53 |
+
directories = []
|
54 |
+
try:
|
55 |
+
for entry in os.listdir(base_path):
|
56 |
+
full_path = os.path.join(base_path, entry)
|
57 |
+
print(full_path)
|
58 |
+
print(full_path)
|
59 |
+
if os.path.isdir(full_path):
|
60 |
+
# Check if the directory contains Chroma vector store files
|
61 |
+
required_files = ['chroma.sqlite3']
|
62 |
+
if all(os.path.exists(os.path.join(full_path, file)) for file in required_files):
|
63 |
+
directories.append(full_path)
|
64 |
+
except Exception as e:
|
65 |
+
logger.error(f"Error listing directories in '{base_path}': {e}")
|
66 |
+
return directories
|
67 |
+
|
68 |
+
# Function to load selected vector stores
|
69 |
+
def load_selected_vectorstores(selected_dirs):
|
70 |
+
"""
|
71 |
+
Loads Chroma vector stores from the selected directories.
|
72 |
+
"""
|
73 |
+
vectorstores = []
|
74 |
+
for directory in selected_dirs:
|
75 |
+
try:
|
76 |
+
vectorstore = Chroma(
|
77 |
+
persist_directory=directory,
|
78 |
+
embedding_function=embeddings
|
79 |
+
)
|
80 |
+
vectorstores.append(vectorstore)
|
81 |
+
logger.info(f"Loaded vectorstore from '{directory}'.")
|
82 |
+
except Exception as e:
|
83 |
+
logger.error(f"Error loading vectorstore from '{directory}': {e}")
|
84 |
+
return vectorstores
|
85 |
+
|
86 |
+
# Function to create a combined retriever
|
87 |
+
def create_combined_retriever(vectorstores, search_kwargs={"k": 20}):
|
88 |
+
retrievers = [vs.as_retriever(search_kwargs=search_kwargs) for vs in vectorstores]
|
89 |
+
|
90 |
+
class CombinedRetriever:
|
91 |
+
def __init__(self, retrievers):
|
92 |
+
self.retrievers = retrievers
|
93 |
+
|
94 |
+
def get_relevant_documents(self, query):
|
95 |
+
docs = []
|
96 |
+
for retriever in self.retrievers:
|
97 |
+
try:
|
98 |
+
docs.extend(retriever.get_relevant_documents(query))
|
99 |
+
except Exception as e:
|
100 |
+
logger.error(f"Error retrieving documents: {e}")
|
101 |
+
# Remove duplicates based on content and source
|
102 |
+
unique_docs = { (doc.page_content, doc.metadata.get('source', '')): doc for doc in docs }
|
103 |
+
return list(unique_docs.values())
|
104 |
+
|
105 |
+
return CombinedRetriever(retrievers)
|
106 |
+
|
107 |
+
# Define the QA function
|
108 |
+
def answer_question(selected_dirs, question):
|
109 |
+
if not selected_dirs:
|
110 |
+
return "Please select at least one vector store directory."
|
111 |
+
|
112 |
+
# Load the selected vector stores
|
113 |
+
vectorstores = load_selected_vectorstores(selected_dirs)
|
114 |
+
if not vectorstores:
|
115 |
+
return "No vector stores loaded. Please check the selected directories."
|
116 |
+
|
117 |
+
# Create combined retriever
|
118 |
+
combined_retriever = create_combined_retriever(vectorstores, search_kwargs={"k": 20})
|
119 |
+
|
120 |
+
# Load the LLM
|
121 |
+
try:
|
122 |
+
llm = ChatOpenAI(model_name="gpt-4o")
|
123 |
+
except Exception as e:
|
124 |
+
logger.error(f"Error loading LLM: {e}")
|
125 |
+
return "Error loading the language model. Please check your OpenAI API key and access."
|
126 |
+
|
127 |
+
# Define the prompt template
|
128 |
+
template = """
|
129 |
+
You are an AI assistant specialized in extracting precise information from legal documents.
|
130 |
+
Special emphasis on documents but refer outside if necessary.
|
131 |
+
Always include the source filename and page number in your response.
|
132 |
+
If multiple documents are the always prefer the lastest date ones.
|
133 |
+
If ammendment documents are the always prefer the ammendments.
|
134 |
+
|
135 |
+
Context:
|
136 |
+
{context}
|
137 |
+
|
138 |
+
Question: {input}
|
139 |
+
|
140 |
+
Answer:
|
141 |
+
"""
|
142 |
+
|
143 |
+
prompt = ChatPromptTemplate.from_template(template)
|
144 |
+
|
145 |
+
# Create QA chain
|
146 |
+
try:
|
147 |
+
qa_chain = load_qa_chain(llm, chain_type="stuff", prompt=prompt)
|
148 |
+
except Exception as e:
|
149 |
+
logger.error(f"Error creating QA chain: {e}")
|
150 |
+
return "Error initializing the QA system."
|
151 |
+
|
152 |
+
# Retrieve documents
|
153 |
+
try:
|
154 |
+
retrieved_docs = combined_retriever.get_relevant_documents(question)
|
155 |
+
except Exception as e:
|
156 |
+
logger.error(f"Error retrieving documents: {e}")
|
157 |
+
return "Error retrieving documents."
|
158 |
+
|
159 |
+
if not retrieved_docs:
|
160 |
+
return "No relevant documents found for the question."
|
161 |
+
|
162 |
+
# Modify the retrieved documents to include metadata within the content
|
163 |
+
for doc in retrieved_docs:
|
164 |
+
source = doc.metadata.get("source", "Unknown Source")
|
165 |
+
page_number = doc.metadata.get("page_number", "Unknown Page")
|
166 |
+
doc.page_content = f"Source: {source}\nPage: {page_number}\nContent: {doc.page_content}"
|
167 |
+
|
168 |
+
# Generate response using the QA chain
|
169 |
+
try:
|
170 |
+
response = qa_chain.run(input_documents=retrieved_docs, input=question)
|
171 |
+
except Exception as e:
|
172 |
+
logger.error(f"Error generating response: {e}")
|
173 |
+
return "Error generating the response."
|
174 |
+
|
175 |
+
return response
|
176 |
+
|
177 |
+
# Set Up the Gradio Interface
|
178 |
+
|
179 |
+
# Get absolute path for vectorstores
|
180 |
+
vectorstores_path = get_absolute_path('/content/properties_vectors/vectors')
|
181 |
+
|
182 |
+
# List available vector store directories
|
183 |
+
available_dirs = list_vectorstore_directories(vectorstores_path)
|
184 |
+
|
185 |
+
# if not available_dirs:
|
186 |
+
# available_dirs = [
|
187 |
+
# "/content/trinity"
|
188 |
+
# # Add other directories as needed
|
189 |
+
# ]
|
190 |
+
|
191 |
+
# Define Gradio interface
|
192 |
+
iface = gr.Interface(
|
193 |
+
fn=answer_question,
|
194 |
+
inputs=[
|
195 |
+
gr.CheckboxGroup(
|
196 |
+
choices=available_dirs,
|
197 |
+
label="Select Vector Store Directories"
|
198 |
+
),
|
199 |
+
gr.Textbox(
|
200 |
+
lines=2,
|
201 |
+
placeholder="Enter your question here...",
|
202 |
+
label="Your Question"
|
203 |
+
)
|
204 |
+
],
|
205 |
+
outputs=gr.Textbox(label="Response"),
|
206 |
+
title="Vector Store QA Assistant",
|
207 |
+
description="Select one or more vector store directories and ask your question. The assistant will retrieve relevant documents and provide an answer.",
|
208 |
+
allow_flagging="never"
|
209 |
+
)
|
210 |
+
|
211 |
+
# Launch the interface
|
212 |
+
iface.launch(debug=True)
|