Nischal Subedi
commited on
Commit
·
b9756ef
1
Parent(s):
f46b871
Add Tenant-Rights-Bot files
Browse files- README.md +24 -14
- app.py +280 -50
- requirements.txt +15 -1
- vector_db.py +191 -0
README.md
CHANGED
@@ -1,14 +1,24 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Tenant Rights Bot
|
2 |
+
|
3 |
+
A Gradio app to answer questions about landlord-tenant laws across U.S. states, grounded in legal statutes.
|
4 |
+
|
5 |
+
## How to Use
|
6 |
+
1. Enter your OpenAI API key (get one from [OpenAI](https://platform.openai.com/api-keys)).
|
7 |
+
2. Select a U.S. state from the dropdown.
|
8 |
+
3. Ask your question about landlord-tenant laws (e.g., "What are the eviction rules in California?").
|
9 |
+
4. View the response, which will include citations to relevant statutes.
|
10 |
+
|
11 |
+
## Features
|
12 |
+
- Answers are grounded in state-specific legal statutes.
|
13 |
+
- Supports all U.S. states with data from a comprehensive landlord-tenant law document.
|
14 |
+
- Provides practical examples to help users understand the laws.
|
15 |
+
|
16 |
+
## Requirements
|
17 |
+
- An OpenAI API key is required to use the app.
|
18 |
+
- The app uses the `gpt-3.5-turbo` model for generating answers.
|
19 |
+
|
20 |
+
## License
|
21 |
+
This project is licensed under the [OpenRAIL License](https://huggingface.co/spaces/license/OpenRAIL).
|
22 |
+
|
23 |
+
## Note
|
24 |
+
This app is for informational purposes only and is not a substitute for legal advice. Always consult a legal professional for specific legal issues.
|
app.py
CHANGED
@@ -1,64 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
6 |
-
"""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
|
26 |
-
|
|
|
27 |
|
28 |
-
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
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 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
from typing import Dict, List, Optional
|
4 |
+
import logging
|
5 |
+
from functools import lru_cache
|
6 |
import gradio as gr
|
7 |
+
from langchain_openai import ChatOpenAI
|
8 |
+
from langchain.prompts import PromptTemplate
|
9 |
+
from langchain.chains import LLMChain
|
10 |
+
from vector_db import VectorDatabase
|
11 |
+
import re
|
12 |
|
13 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
|
|
|
|
|
14 |
|
15 |
+
class RAGSystem:
|
16 |
+
def __init__(self, vector_db: Optional[VectorDatabase] = None):
|
17 |
+
logging.info("Initializing RAGSystem")
|
18 |
+
|
19 |
+
self.vector_db = vector_db if vector_db else VectorDatabase()
|
20 |
+
|
21 |
+
# LLM and chain will be initialized later with user-provided API key
|
22 |
+
self.llm = None
|
23 |
+
self.chain = None
|
24 |
+
|
25 |
+
# Prompt template for statute-grounded answers
|
26 |
+
self.prompt_template = PromptTemplate(
|
27 |
+
input_variables=["query", "context", "state", "statutes"],
|
28 |
+
template="""You are a legal assistant specializing in tenant rights and landlord-tenant laws. Your goal is to provide accurate, detailed, and helpful answers that are explicitly grounded in the statutes provided in the context. Only use general knowledge to supplement the answer if the context lacks sufficient detail to fully answer the question, and clearly indicate when you are doing so.
|
29 |
|
30 |
+
Instructions:
|
31 |
+
- Use the context information and the provided statutes as the primary source to answer the question.
|
32 |
+
- Explicitly cite the relevant statute(s) (e.g., (AS § 34.03.220(a)(2))) in your answer to ground your response in the legal text.
|
33 |
+
- If multiple statutes are relevant, cite all that apply.
|
34 |
+
- If the context does not contain a relevant statute to answer the question, state that no specific statute was found and provide a general answer, clearly marking it as general knowledge.
|
35 |
+
- Provide detailed answers with practical examples or scenarios when possible.
|
36 |
+
- Use bullet points or numbered lists for clarity when applicable.
|
37 |
+
- Maintain a professional and neutral tone.
|
38 |
+
- Do not include a "Sources" section in the answer.
|
39 |
|
40 |
+
Question: {query}
|
41 |
+
State: {state}
|
|
|
|
|
|
|
42 |
|
43 |
+
Statutes found in context:
|
44 |
+
{statutes}
|
45 |
|
46 |
+
Context information:
|
47 |
+
{context}
|
48 |
|
49 |
+
Answer:"""
|
50 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
+
def initialize_llm(self, openai_api_key: str):
|
53 |
+
"""Initialize the LLM and chain with the provided API key."""
|
54 |
+
if not openai_api_key:
|
55 |
+
raise ValueError("OpenAI API key is required.")
|
56 |
+
|
57 |
+
try:
|
58 |
+
self.llm = ChatOpenAI(
|
59 |
+
temperature=0.2,
|
60 |
+
openai_api_key=openai_api_key,
|
61 |
+
model_name="gpt-3.5-turbo",
|
62 |
+
max_tokens=1500,
|
63 |
+
request_timeout=30
|
64 |
+
)
|
65 |
+
logging.info("OpenAI LLM initialized successfully")
|
66 |
+
|
67 |
+
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
68 |
+
logging.info("LLMChain created successfully")
|
69 |
+
except Exception as e:
|
70 |
+
logging.error(f"Failed to initialize OpenAI LLM: {str(e)}")
|
71 |
+
raise
|
72 |
|
73 |
+
def extract_statutes(self, context: str) -> str:
|
74 |
+
"""
|
75 |
+
Extract statute citations from the context using a regex pattern.
|
76 |
+
Returns a string of statutes, one per line, or a message if none are found.
|
77 |
+
"""
|
78 |
+
statute_pattern = r'\([A-Za-z0-9§\.\s-]+\)'
|
79 |
+
statutes = re.findall(statute_pattern, context)
|
80 |
+
if statutes:
|
81 |
+
return "\n".join(statutes)
|
82 |
+
return "No statutes found in the context."
|
83 |
|
84 |
+
@lru_cache(maxsize=100)
|
85 |
+
def process_query(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
|
86 |
+
logging.info(f"Processing query: '{query}' for state: {state}")
|
87 |
+
|
88 |
+
if not state:
|
89 |
+
return {
|
90 |
+
"answer": "Please select a state to proceed with your query.",
|
91 |
+
"sources": [],
|
92 |
+
"context_used": "N/A",
|
93 |
+
"statutes_found": "N/A"
|
94 |
+
}
|
95 |
+
|
96 |
+
if not openai_api_key:
|
97 |
+
return {
|
98 |
+
"answer": "Please provide an OpenAI API key to proceed.",
|
99 |
+
"sources": [],
|
100 |
+
"context_used": "N/A",
|
101 |
+
"statutes_found": "N/A"
|
102 |
+
}
|
103 |
+
|
104 |
+
# Initialize LLM with the provided API key if not already initialized
|
105 |
+
if not self.llm or not self.chain:
|
106 |
+
try:
|
107 |
+
self.initialize_llm(openai_api_key)
|
108 |
+
except Exception as e:
|
109 |
+
return {
|
110 |
+
"answer": f"Failed to initialize LLM with the provided API key: {str(e)}",
|
111 |
+
"sources": [],
|
112 |
+
"context_used": "N/A",
|
113 |
+
"statutes_found": "N/A"
|
114 |
+
}
|
115 |
+
|
116 |
+
try:
|
117 |
+
results = self.vector_db.query(query, state=state, n_results=n_results)
|
118 |
+
logging.info("Vector database query successful")
|
119 |
+
except Exception as e:
|
120 |
+
logging.error(f"Vector database query failed: {str(e)}")
|
121 |
+
return {
|
122 |
+
"answer": "An error occurred while querying the database. Please try again.",
|
123 |
+
"sources": [],
|
124 |
+
"context_used": "N/A",
|
125 |
+
"statutes_found": "N/A"
|
126 |
+
}
|
127 |
+
|
128 |
+
context_parts = []
|
129 |
+
sources = []
|
130 |
+
|
131 |
+
if results["document_results"]["documents"]:
|
132 |
+
for i, doc in enumerate(results["document_results"]["documents"][0]):
|
133 |
+
metadata = results["document_results"]["metadatas"][0][i]
|
134 |
+
context_parts.append(f"[{metadata['state']} - Chunk {metadata.get('chunk_id', 'N/A')}] {doc}")
|
135 |
+
sources.append({
|
136 |
+
"text": doc[:100] + "..." if len(doc) > 100 else doc,
|
137 |
+
"state": metadata["state"],
|
138 |
+
"chunk_id": str(metadata.get("chunk_id", "N/A")),
|
139 |
+
"source_file": metadata.get("source", "Unknown")
|
140 |
+
})
|
141 |
+
|
142 |
+
if results["state_results"]["documents"]:
|
143 |
+
for i, doc in enumerate(results["state_results"]["documents"][0]):
|
144 |
+
metadata = results["state_results"]["metadatas"][0][i]
|
145 |
+
context_parts.append(f"[{metadata['state']} - Summary] {doc}")
|
146 |
+
sources.append({
|
147 |
+
"text": doc[:100] + "..." if len(doc) > 100 else doc,
|
148 |
+
"state": metadata["state"],
|
149 |
+
"type": metadata.get("type", "summary"),
|
150 |
+
"source_file": "state_summary"
|
151 |
+
})
|
152 |
+
|
153 |
+
context = "\n\n---\n\n".join(context_parts) if context_parts else "No relevant context found."
|
154 |
+
|
155 |
+
if not context_parts:
|
156 |
+
logging.info("No relevant context found for query")
|
157 |
+
return {
|
158 |
+
"answer": "I don't have sufficient information in my database to answer this question accurately. However, I can provide some general information about tenant rights.",
|
159 |
+
"sources": [],
|
160 |
+
"context_used": context,
|
161 |
+
"statutes_found": "N/A"
|
162 |
+
}
|
163 |
+
|
164 |
+
# Extract statutes from the context
|
165 |
+
statutes = self.extract_statutes(context)
|
166 |
+
|
167 |
+
try:
|
168 |
+
answer = self.chain.invoke({
|
169 |
+
"query": query,
|
170 |
+
"context": context,
|
171 |
+
"state": state,
|
172 |
+
"statutes": statutes
|
173 |
+
})
|
174 |
+
logging.info("LLM generated answer successfully")
|
175 |
+
except Exception as e:
|
176 |
+
logging.error(f"LLM processing failed: {str(e)}")
|
177 |
+
return {
|
178 |
+
"answer": "An error occurred while generating the answer. Please try again.",
|
179 |
+
"sources": sources,
|
180 |
+
"context_used": context,
|
181 |
+
"statutes_found": statutes
|
182 |
+
}
|
183 |
+
|
184 |
+
return {
|
185 |
+
"answer": answer['text'].strip(),
|
186 |
+
"sources": sources,
|
187 |
+
"context_used": context,
|
188 |
+
"statutes_found": statutes
|
189 |
+
}
|
190 |
+
|
191 |
+
def get_states(self) -> List[str]:
|
192 |
+
try:
|
193 |
+
states = self.vector_db.get_states()
|
194 |
+
logging.info(f"Retrieved {len(states)} states from database")
|
195 |
+
return states
|
196 |
+
except Exception as e:
|
197 |
+
logging.error(f"Failed to get states: {str(e)}")
|
198 |
+
return []
|
199 |
|
200 |
+
def load_pdf(self, pdf_path: str) -> int:
|
201 |
+
try:
|
202 |
+
num_states = self.vector_db.process_and_load_pdf(pdf_path)
|
203 |
+
logging.info(f"Loaded PDF with {num_states} states")
|
204 |
+
return num_states
|
205 |
+
except Exception as e:
|
206 |
+
logging.error(f"Failed to load PDF: {str(e)}")
|
207 |
+
return 0
|
208 |
+
|
209 |
+
def gradio_interface(self) -> gr.Interface:
|
210 |
+
def query_interface(api_key: str, query: str, state: str) -> str:
|
211 |
+
if not api_key:
|
212 |
+
return "Please provide an OpenAI API key to proceed."
|
213 |
+
if not state:
|
214 |
+
return "Please select a state to proceed with your query."
|
215 |
+
result = self.process_query(query, state=state, openai_api_key=api_key)
|
216 |
+
return f"**Answer:**\n{result['answer']}\n\n**Statutes Found:**\n{result['statutes_found']}"
|
217 |
+
|
218 |
+
states = self.get_states()
|
219 |
+
|
220 |
+
example_queries = [
|
221 |
+
["sk-abc123", "What is the rent due date law?", "California"],
|
222 |
+
["sk-abc123", "What are the rules for security deposit returns?", "New York"],
|
223 |
+
["sk-abc123", "Can a landlord enter without notice?", "Texas"],
|
224 |
+
["sk-abc123", "What are the eviction notice requirements?", "Florida"],
|
225 |
+
["sk-abc123", "Are there rent control laws?", "Oregon"]
|
226 |
+
]
|
227 |
+
|
228 |
+
interface = gr.Interface(
|
229 |
+
fn=query_interface,
|
230 |
+
inputs=[
|
231 |
+
gr.Textbox(
|
232 |
+
label="Enter your OpenAI API Key",
|
233 |
+
type="password",
|
234 |
+
placeholder="e.g., sk-abc123"
|
235 |
+
),
|
236 |
+
gr.Textbox(
|
237 |
+
label="Enter your question about Landlord-Tenant laws",
|
238 |
+
placeholder="e.g., What are the eviction rules?",
|
239 |
+
lines=2
|
240 |
+
),
|
241 |
+
gr.Dropdown(
|
242 |
+
label="Select a state (required)",
|
243 |
+
choices=states,
|
244 |
+
value=None,
|
245 |
+
allow_custom_value=False
|
246 |
+
)
|
247 |
+
],
|
248 |
+
outputs=gr.Markdown(
|
249 |
+
label="Response",
|
250 |
+
elem_classes="output-markdown"
|
251 |
+
),
|
252 |
+
title="🏠 Landlord-Tenant Rights Bot",
|
253 |
+
description="Ask questions about tenant rights and landlord-tenant laws based on state-specific legal documents. Provide your OpenAI API key, select a state, and enter your question below. You can get an API key from [OpenAI](https://platform.openai.com/api-keys).",
|
254 |
+
examples=example_queries,
|
255 |
+
theme=gr.themes.Soft(),
|
256 |
+
css="""
|
257 |
+
.output-markdown {
|
258 |
+
background-color: #f8f9fa;
|
259 |
+
padding: 20px;
|
260 |
+
border-radius: 10px;
|
261 |
+
border: 1px solid #e0e0e0;
|
262 |
+
font-size: 16px;
|
263 |
+
line-height: 1.6;
|
264 |
+
}
|
265 |
+
.gr-button-primary {
|
266 |
+
background-color: #4a90e2;
|
267 |
+
border: none;
|
268 |
+
padding: 10px 20px;
|
269 |
+
font-weight: bold;
|
270 |
+
}
|
271 |
+
.gr-button-primary:hover {
|
272 |
+
background-color: #357abd;
|
273 |
+
}
|
274 |
+
.gr-form {
|
275 |
+
max-width: 800px;
|
276 |
+
margin: 0 auto;
|
277 |
+
}
|
278 |
+
"""
|
279 |
+
)
|
280 |
+
return interface
|
281 |
|
282 |
if __name__ == "__main__":
|
283 |
+
try:
|
284 |
+
rag = RAGSystem()
|
285 |
+
|
286 |
+
pdf_path = "data/tenant-landlord.pdf"
|
287 |
+
rag.load_pdf(pdf_path)
|
288 |
+
|
289 |
+
interface = rag.gradio_interface()
|
290 |
+
interface.launch(share=True)
|
291 |
+
|
292 |
+
except Exception as e:
|
293 |
+
logging.error(f"Main execution failed: {str(e)}")
|
294 |
+
raise
|
requirements.txt
CHANGED
@@ -1 +1,15 @@
|
|
1 |
-
huggingface_hub==0.25.2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
huggingface_hub==0.25.2
|
2 |
+
gradio==4.44.0
|
3 |
+
langchain==0.3.1
|
4 |
+
langchain-openai==0.2.0 # Add this for the new OpenAI integration
|
5 |
+
openai==1.40.0
|
6 |
+
chromadb==0.5.5
|
7 |
+
sentence-transformers==3.0.1
|
8 |
+
torch==2.2.2
|
9 |
+
python-dotenv==1.0.1
|
10 |
+
tiktoken==0.7.0
|
11 |
+
numpy==1.26.4
|
12 |
+
pandas==2.2.2
|
13 |
+
huggingface_hub==0.23.4
|
14 |
+
pymupdf==1.24.9langchain_community
|
15 |
+
langchain_community
|
vector_db.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import fitz # PyMuPDF
|
3 |
+
import re
|
4 |
+
import chromadb
|
5 |
+
from chromadb.utils import embedding_functions
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
import logging
|
9 |
+
|
10 |
+
# Set up logging
|
11 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
12 |
+
|
13 |
+
class VectorDatabase:
|
14 |
+
"""Vector database for storing and retrieving tenant rights information from PDF."""
|
15 |
+
|
16 |
+
def __init__(self, persist_directory="./data/chroma_db"):
|
17 |
+
"""Initialize the vector database."""
|
18 |
+
logging.info("Initializing VectorDatabase")
|
19 |
+
logging.info(f"NumPy version: {np.__version__}")
|
20 |
+
logging.info(f"PyTorch version: {torch.__version__}")
|
21 |
+
|
22 |
+
self.persist_directory = persist_directory
|
23 |
+
os.makedirs(persist_directory, exist_ok=True)
|
24 |
+
|
25 |
+
try:
|
26 |
+
logging.info("Creating embedding function")
|
27 |
+
self.embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
|
28 |
+
model_name="all-MiniLM-L6-v2"
|
29 |
+
)
|
30 |
+
|
31 |
+
logging.info("Initializing ChromaDB client")
|
32 |
+
self.client = chromadb.PersistentClient(path=persist_directory)
|
33 |
+
|
34 |
+
logging.info("Setting up collections")
|
35 |
+
self.document_collection = self._get_or_create_collection("tenant_documents")
|
36 |
+
self.state_collection = self._get_or_create_collection("tenant_states")
|
37 |
+
except Exception as e:
|
38 |
+
logging.error(f"Initialization failed: {str(e)}")
|
39 |
+
raise
|
40 |
+
|
41 |
+
def _get_or_create_collection(self, name):
|
42 |
+
"""Get or create a collection with the given name."""
|
43 |
+
try:
|
44 |
+
return self.client.get_collection(
|
45 |
+
name=name,
|
46 |
+
embedding_function=self.embedding_function
|
47 |
+
)
|
48 |
+
except Exception:
|
49 |
+
return self.client.create_collection(
|
50 |
+
name=name,
|
51 |
+
embedding_function=self.embedding_function
|
52 |
+
)
|
53 |
+
|
54 |
+
def extract_pdf_content(self, pdf_path):
|
55 |
+
"""Extract content from PDF file and identify state sections."""
|
56 |
+
logging.info(f"Extracting content from PDF: {pdf_path}")
|
57 |
+
|
58 |
+
if not os.path.exists(pdf_path):
|
59 |
+
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
|
60 |
+
|
61 |
+
doc = fitz.open(pdf_path)
|
62 |
+
full_text = ""
|
63 |
+
for page_num in range(len(doc)):
|
64 |
+
page = doc.load_page(page_num)
|
65 |
+
full_text += page.get_text("text") + "\n"
|
66 |
+
doc.close()
|
67 |
+
|
68 |
+
state_pattern = r"(?m)^\s*([A-Z][a-z]+(?:\s[A-Z][a-z]+)*)\s+Landlord(?:-|\s)Tenant\s+(?:Law|Laws)"
|
69 |
+
state_matches = list(re.finditer(state_pattern, full_text))
|
70 |
+
|
71 |
+
if not state_matches:
|
72 |
+
logging.info("No state sections found. Treating as single document.")
|
73 |
+
return {"Full Document": full_text.strip()}
|
74 |
+
|
75 |
+
state_sections = {}
|
76 |
+
for i, match in enumerate(state_matches):
|
77 |
+
state_name = match.group(1).strip()
|
78 |
+
start_pos = match.end()
|
79 |
+
end_pos = state_matches[i + 1].start() if i + 1 < len(state_matches) else len(full_text)
|
80 |
+
state_text = full_text[start_pos:end_pos].strip()
|
81 |
+
if state_text:
|
82 |
+
state_sections[state_name] = state_text
|
83 |
+
|
84 |
+
logging.info(f"Extracted content for {len(state_sections)} states")
|
85 |
+
return state_sections
|
86 |
+
|
87 |
+
def process_and_load_pdf(self, pdf_path):
|
88 |
+
"""Process PDF and load content into vector database."""
|
89 |
+
state_sections = self.extract_pdf_content(pdf_path)
|
90 |
+
|
91 |
+
doc_ids = self.document_collection.get()["ids"]
|
92 |
+
state_ids = self.state_collection.get()["ids"]
|
93 |
+
|
94 |
+
if doc_ids:
|
95 |
+
self.document_collection.delete(ids=doc_ids)
|
96 |
+
if state_ids:
|
97 |
+
self.state_collection.delete(ids=state_ids)
|
98 |
+
|
99 |
+
document_ids, document_texts, document_metadatas = [], [], []
|
100 |
+
state_ids, state_texts, state_metadatas = [], [], []
|
101 |
+
|
102 |
+
for state, text in state_sections.items():
|
103 |
+
state_id = f"state_{state.lower().replace(' ', '_')}"
|
104 |
+
summary = text[:1000].strip() if len(text) > 1000 else text
|
105 |
+
state_ids.append(state_id)
|
106 |
+
state_texts.append(summary)
|
107 |
+
state_metadatas.append({"state": state, "type": "summary"})
|
108 |
+
|
109 |
+
chunks = self._chunk_text(text, chunk_size=1000, overlap=200)
|
110 |
+
for i, chunk in enumerate(chunks):
|
111 |
+
doc_id = f"doc_{state.lower().replace(' ', '_')}_{i}"
|
112 |
+
document_ids.append(doc_id)
|
113 |
+
document_texts.append(chunk)
|
114 |
+
document_metadatas.append({
|
115 |
+
"state": state,
|
116 |
+
"chunk_id": i,
|
117 |
+
"total_chunks": len(chunks),
|
118 |
+
"source": os.path.basename(pdf_path)
|
119 |
+
})
|
120 |
+
|
121 |
+
if document_ids:
|
122 |
+
self.document_collection.add(
|
123 |
+
ids=document_ids,
|
124 |
+
documents=document_texts,
|
125 |
+
metadatas=document_metadatas
|
126 |
+
)
|
127 |
+
if state_ids:
|
128 |
+
self.state_collection.add(
|
129 |
+
ids=state_ids,
|
130 |
+
documents=state_texts,
|
131 |
+
metadatas=state_metadatas
|
132 |
+
)
|
133 |
+
|
134 |
+
logging.info(f"Loaded {len(document_ids)} document chunks and {len(state_ids)} state summaries")
|
135 |
+
return len(state_sections)
|
136 |
+
|
137 |
+
def _chunk_text(self, text, chunk_size=1000, overlap=200):
|
138 |
+
"""Split text into overlapping chunks."""
|
139 |
+
if not text:
|
140 |
+
return []
|
141 |
+
|
142 |
+
chunks = []
|
143 |
+
start = 0
|
144 |
+
text_length = len(text)
|
145 |
+
|
146 |
+
while start < text_length:
|
147 |
+
end = min(start + chunk_size, text_length)
|
148 |
+
if end < text_length:
|
149 |
+
last_period = text.rfind(".", start, end)
|
150 |
+
last_newline = text.rfind("\n", start, end)
|
151 |
+
split_point = max(last_period, last_newline)
|
152 |
+
if split_point > start:
|
153 |
+
end = split_point + 1
|
154 |
+
chunks.append(text[start:end].strip())
|
155 |
+
start = end - overlap if end - overlap > start else end
|
156 |
+
|
157 |
+
return chunks
|
158 |
+
|
159 |
+
def query(self, query_text, state=None, n_results=5):
|
160 |
+
"""Query the vector database for relevant tenant rights information."""
|
161 |
+
state_filter = {"state": state} if state else None
|
162 |
+
|
163 |
+
document_results = self.document_collection.query(
|
164 |
+
query_texts=[query_text],
|
165 |
+
n_results=n_results,
|
166 |
+
where=state_filter
|
167 |
+
)
|
168 |
+
state_results = self.state_collection.query(
|
169 |
+
query_texts=[query_text],
|
170 |
+
n_results=n_results,
|
171 |
+
where=state_filter
|
172 |
+
)
|
173 |
+
|
174 |
+
return {"document_results": document_results, "state_results": state_results}
|
175 |
+
|
176 |
+
def get_states(self):
|
177 |
+
"""Get a list of all states in the database."""
|
178 |
+
results = self.state_collection.get()
|
179 |
+
states = {meta["state"] for meta in results["metadatas"] if meta}
|
180 |
+
return sorted(list(states))
|
181 |
+
|
182 |
+
if __name__ == "__main__":
|
183 |
+
try:
|
184 |
+
db = VectorDatabase()
|
185 |
+
pdf_path = "data/tenant-landlord.pdf"
|
186 |
+
db.process_and_load_pdf(pdf_path)
|
187 |
+
states = db.get_states()
|
188 |
+
print(f"Available states: {states}")
|
189 |
+
except Exception as e:
|
190 |
+
logging.error(f"Script execution failed: {str(e)}")
|
191 |
+
raise
|