Nischal Subedi
commited on
Commit
·
a0d3ba4
1
Parent(s):
9fea218
UI update
Browse files
app.py
CHANGED
@@ -1,997 +1 @@
|
|
1 |
-
|
2 |
-
import logging
|
3 |
-
from typing import Dict, List, Optional
|
4 |
-
from functools import lru_cache
|
5 |
-
import re
|
6 |
-
|
7 |
-
import gradio as gr
|
8 |
-
|
9 |
-
try:
|
10 |
-
# Assuming vector_db.py exists in the same directory or is installed
|
11 |
-
from vector_db import VectorDatabase
|
12 |
-
except ImportError:
|
13 |
-
print("Error: Could not import VectorDatabase from vector_db.py.")
|
14 |
-
print("Please ensure vector_db.py exists in the same directory and is correctly defined.")
|
15 |
-
# Exit if critical dependency is missing at import time
|
16 |
-
exit(1)
|
17 |
-
|
18 |
-
try:
|
19 |
-
from langchain_openai import ChatOpenAI
|
20 |
-
except ImportError:
|
21 |
-
print("Error: langchain-openai not found. Please install it: pip install langchain-openai")
|
22 |
-
# Exit if critical dependency is missing at import time
|
23 |
-
exit(1)
|
24 |
-
|
25 |
-
from langchain.prompts import PromptTemplate
|
26 |
-
from langchain.chains import LLMChain
|
27 |
-
|
28 |
-
# Suppress warnings for cleaner console output
|
29 |
-
import warnings
|
30 |
-
warnings.filterwarnings("ignore", category=SyntaxWarning)
|
31 |
-
warnings.filterwarnings("ignore", category=UserWarning, message=".*You are using gradio version.*")
|
32 |
-
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
33 |
-
|
34 |
-
# Enhanced logging configuration
|
35 |
-
logging.basicConfig(
|
36 |
-
level=logging.INFO,
|
37 |
-
format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
|
38 |
-
)
|
39 |
-
|
40 |
-
# --- RAGSystem Class (Processing Logic - KEPT INTACT AS REQUESTED) ---
|
41 |
-
class RAGSystem:
|
42 |
-
def __init__(self, vector_db: Optional[VectorDatabase] = None):
|
43 |
-
logging.info("Initializing RAGSystem")
|
44 |
-
self.vector_db = vector_db if vector_db else VectorDatabase()
|
45 |
-
self.llm = None
|
46 |
-
self.chain = None
|
47 |
-
self.prompt_template_str = """You are a legal assistant specializing in tenant rights and landlord-tenant laws. Your goal is to provide accurate, detailed, and helpful answers grounded in legal authority. Use the provided statutes as the primary source when available. If no relevant statutes are found in the context, rely on your general knowledge to provide a pertinent and practical response, clearly indicating when you are doing so and prioritizing state-specific information over federal laws for state-specific queries.
|
48 |
-
Instructions:
|
49 |
-
* Use the context and statutes as the primary basis for your answer when available.
|
50 |
-
* For state-specific queries, prioritize statutes or legal principles from the specified state over federal laws.
|
51 |
-
* Cite relevant statutes (e.g., (AS § 34.03.220(a)(2))) explicitly in your answer when applicable.
|
52 |
-
* If multiple statutes apply, list all relevant ones.
|
53 |
-
* If no specific statute is found in the context, state this clearly (e.g., 'No specific statute was found in the provided context'), then provide a general answer based on common legal principles or practices, marked as such.
|
54 |
-
* Include practical examples or scenarios to enhance clarity and usefulness.
|
55 |
-
* Use bullet points or numbered lists for readability when appropriate.
|
56 |
-
* Maintain a professional and neutral tone.
|
57 |
-
Question: {query}
|
58 |
-
State: {state}
|
59 |
-
Statutes from context:
|
60 |
-
{statutes}
|
61 |
-
Context information:
|
62 |
-
--- START CONTEXT ---
|
63 |
-
{context}
|
64 |
-
--- END CONCONTEXT ---
|
65 |
-
Answer:"""
|
66 |
-
self.prompt_template = PromptTemplate(
|
67 |
-
input_variables=["query", "context", "state", "statutes"],
|
68 |
-
template=self.prompt_template_str
|
69 |
-
)
|
70 |
-
logging.info("RAGSystem initialized.")
|
71 |
-
|
72 |
-
def extract_statutes(self, text: str) -> str:
|
73 |
-
statute_pattern = r'\b(?:[A-Z]{2,}\.?\s+(?:Rev\.\s+)?Stat\.?|Code(?:\s+Ann\.?)?|Ann\.?\s+Laws|Statutes|CCP|USC|ILCS|Civ\.\s+Code|Penal\s+Code|Gen\.\s+Oblig\.\s+Law|R\.?S\.?|P\.?L\.?)\s+§\s*[\d\-]+(?:\.\d+)?(?:[\(\w\.\)]+)?|Title\s+\d+\s+USC\s+§\s*\d+(?:-\d+)?\b'
|
74 |
-
statutes = re.findall(statute_pattern, text, re.IGNORECASE)
|
75 |
-
valid_statutes = []
|
76 |
-
for statute in statutes:
|
77 |
-
statute = statute.strip()
|
78 |
-
if '§' in statute and any(char.isdigit() for char in statute):
|
79 |
-
if not re.match(r'^\([\w\.]+\)$', statute) and 'http' not in statute:
|
80 |
-
if len(statute) > 5:
|
81 |
-
valid_statutes.append(statute)
|
82 |
-
|
83 |
-
if valid_statutes:
|
84 |
-
seen = set()
|
85 |
-
unique_statutes = [s for s in valid_statutes if not (s.rstrip('.,;') in seen or seen.add(s.rstrip('.,;')))]
|
86 |
-
logging.info(f"Extracted {len(unique_statutes)} unique statutes.")
|
87 |
-
return "\n".join(f"- {s}" for s in unique_statutes)
|
88 |
-
|
89 |
-
logging.info("No statutes found matching the pattern in the context.")
|
90 |
-
return "No specific statutes found in the provided context."
|
91 |
-
|
92 |
-
@lru_cache(maxsize=50)
|
93 |
-
def process_query_cached(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
|
94 |
-
logging.info(f"Processing query (cache key: '{query}'|'{state}'|key_hidden) with n_results={n_results}")
|
95 |
-
|
96 |
-
if not state or state is None: # Removed "Select a state..." from error check as it's not a choice
|
97 |
-
logging.warning("No valid state provided for query.")
|
98 |
-
return {"answer": "<div class='error-message'>Error: Please select a valid state.</div>", "context_used": "N/A - Invalid Input"}
|
99 |
-
if not query or not query.strip():
|
100 |
-
logging.warning("No query provided.")
|
101 |
-
return {"answer": "<div class='error-message'>Error: Please enter your question.</div>", "context_used": "N/A - Invalid Input"}
|
102 |
-
if not openai_api_key or not openai_api_key.strip() or not openai_api_key.startswith("sk-"):
|
103 |
-
logging.warning("No valid OpenAI API key provided.")
|
104 |
-
return {"answer": "<div class='error-message'>Error: Please provide a valid OpenAI API key (starting with 'sk-'). Get one from <a href='https://platform.openai.com/api-keys' target='_blank'>OpenAI</a>.</div>", "context_used": "N/A - Invalid Input"}
|
105 |
-
|
106 |
-
try:
|
107 |
-
logging.info("Initializing temporary LLM and Chain for this query...")
|
108 |
-
temp_llm = ChatOpenAI(
|
109 |
-
temperature=0.2, openai_api_key=openai_api_key, model_name="gpt-3.5-turbo",
|
110 |
-
max_tokens=1500, request_timeout=45
|
111 |
-
)
|
112 |
-
temp_chain = LLMChain(llm=temp_llm, prompt=self.prompt_template)
|
113 |
-
logging.info("Temporary LLM and Chain initialized successfully.")
|
114 |
-
except Exception as e:
|
115 |
-
logging.error(f"LLM Initialization failed: {str(e)}", exc_info=True)
|
116 |
-
error_msg = "Error: Failed to initialize AI model. Please check your network connection and API key validity."
|
117 |
-
if "authentication" in str(e).lower():
|
118 |
-
error_msg = "Error: OpenAI API Key is invalid or expired. Please check your key."
|
119 |
-
return {"answer": f"<div class='error-message'>{error_msg}</div><div class='error-details'>Details: {str(e)}</div>", "context_used": "N/A - LLM Init Failed"}
|
120 |
-
|
121 |
-
context = "No relevant context found."
|
122 |
-
statutes_from_context = "Statute retrieval skipped due to context issues."
|
123 |
-
try:
|
124 |
-
logging.info(f"Querying Vector DB for query: '{query[:50]}...' in state '{state}'...")
|
125 |
-
results = self.vector_db.query(query, state=state, n_results=n_results)
|
126 |
-
logging.info(f"Vector DB query successful for state '{state}'. Processing results...")
|
127 |
-
|
128 |
-
context_parts = []
|
129 |
-
doc_results = results.get("document_results", {})
|
130 |
-
docs = doc_results.get("documents", [[]])[0]
|
131 |
-
metadatas = doc_results.get("metadatas", [[]])[0]
|
132 |
-
if docs and metadatas and len(docs) == len(metadatas):
|
133 |
-
logging.info(f"Found {len(docs)} document chunks.")
|
134 |
-
for i, doc_content in enumerate(docs):
|
135 |
-
metadata = metadatas[i]
|
136 |
-
state_label = metadata.get('state', 'Unknown State')
|
137 |
-
chunk_id = metadata.get('chunk_id', 'N/A')
|
138 |
-
context_parts.append(f"**Source: Document Chunk {chunk_id} (State: {state_label})**\n{doc_content}")
|
139 |
-
|
140 |
-
state_results_data = results.get("state_results", {})
|
141 |
-
state_docs = state_results_data.get("documents", [[]])[0]
|
142 |
-
state_metadatas = state_results_data.get("metadatas", [[]])[0]
|
143 |
-
if state_docs and state_metadatas and len(state_docs) == len(state_metadatas):
|
144 |
-
logging.info(f"Found {len(state_docs)} state summary documents.")
|
145 |
-
for i, state_doc_content in enumerate(state_docs):
|
146 |
-
metadata = state_metadatas[i]
|
147 |
-
state_label = metadata.get('state', state)
|
148 |
-
context_parts.append(f"**Source: State Summary (State: {state_label})**\n{state_doc_content}")
|
149 |
-
|
150 |
-
if context_parts:
|
151 |
-
context = "\n\n---\n\n".join(context_parts)
|
152 |
-
logging.info(f"Constructed context with {len(context)} chars.")
|
153 |
-
try:
|
154 |
-
statutes_from_context = self.extract_statutes(context)
|
155 |
-
except Exception as e:
|
156 |
-
logging.error(f"Error extracting statutes: {e}", exc_info=True)
|
157 |
-
statutes_from_context = "Error extracting statutes from context."
|
158 |
-
else:
|
159 |
-
logging.warning("No relevant context parts found from vector DB query.")
|
160 |
-
context = "No relevant context could be retrieved from the knowledge base for this query and state. The AI will answer from its general knowledge."
|
161 |
-
statutes_from_context = "No specific statutes found as no context was retrieved."
|
162 |
-
|
163 |
-
except Exception as e:
|
164 |
-
logging.error(f"Vector DB query/context processing failed: {str(e)}", exc_info=True)
|
165 |
-
context = f"Warning: Error retrieving documents from the knowledge base ({str(e)}). The AI will attempt to answer from its general knowledge, which may be less specific or accurate."
|
166 |
-
statutes_from_context = "Statute retrieval skipped due to error retrieving context."
|
167 |
-
|
168 |
-
try:
|
169 |
-
logging.info("Invoking LLMChain with constructed input...")
|
170 |
-
llm_input = {"query": query, "context": context, "state": state, "statutes": statutes_from_context}
|
171 |
-
answer_dict = temp_chain.invoke(llm_input)
|
172 |
-
answer_text = answer_dict.get('text', '').strip()
|
173 |
-
|
174 |
-
if not answer_text:
|
175 |
-
logging.warning("LLM returned an empty answer.")
|
176 |
-
answer_text = "<div class='error-message'><span class='error-icon'>⚠️</span>The AI model returned an empty response. This might be due to the query, context limitations, or temporary issues. Please try rephrasing your question or try again later.</div>"
|
177 |
-
else:
|
178 |
-
logging.info("LLM generated answer successfully.")
|
179 |
-
|
180 |
-
return {"answer": answer_text, "context_used": context}
|
181 |
-
|
182 |
-
except Exception as e:
|
183 |
-
logging.error(f"LLM processing failed: {str(e)}", exc_info=True)
|
184 |
-
error_message = "Error: AI answer generation failed."
|
185 |
-
details = f"Details: {str(e)}"
|
186 |
-
if "authentication" in str(e).lower():
|
187 |
-
error_message = "Error: Authentication failed. Please double-check your OpenAI API key."
|
188 |
-
details = ""
|
189 |
-
elif "rate limit" in str(e).lower():
|
190 |
-
error_message = "Error: You've exceeded your OpenAI API rate limit or quota. Please check your usage and plan limits, or wait and try again."
|
191 |
-
details = ""
|
192 |
-
elif "context length" in str(e).lower():
|
193 |
-
error_message = "Error: The request was too long for the AI model. This can happen with very complex questions or extensive retrieved context."
|
194 |
-
details = "Try simplifying your question or asking about a more specific aspect."
|
195 |
-
elif "timeout" in str(e).lower():
|
196 |
-
error_message = "Error: The request to the AI model timed out. The service might be busy."
|
197 |
-
details = "Please try again in a few moments."
|
198 |
-
|
199 |
-
formatted_error = f"<div class='error-message'><span class='error-icon'>❌</span>{error_message}</div>"
|
200 |
-
if details:
|
201 |
-
formatted_error += f"<div class='error-details'>{details}</div>"
|
202 |
-
|
203 |
-
return {"answer": formatted_error, "context_used": context}
|
204 |
-
|
205 |
-
def process_query(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
|
206 |
-
return self.process_query_cached(query.strip(), state, openai_api_key.strip(), n_results)
|
207 |
-
|
208 |
-
def get_states(self) -> List[str]:
|
209 |
-
try:
|
210 |
-
states = self.vector_db.get_states()
|
211 |
-
if not states:
|
212 |
-
logging.warning("No states retrieved from vector_db. Returning empty list.")
|
213 |
-
return []
|
214 |
-
valid_states = sorted(list(set(s for s in states if s and isinstance(s, str) and s != "Select a state...")))
|
215 |
-
logging.info(f"Retrieved {len(valid_states)} unique, valid states from VectorDatabase.")
|
216 |
-
return valid_states
|
217 |
-
except Exception as e:
|
218 |
-
logging.error(f"Failed to get states from VectorDatabase: {str(e)}", exc_info=True)
|
219 |
-
return ["Error: Could not load states"]
|
220 |
-
|
221 |
-
def load_pdf(self, pdf_path: str) -> int:
|
222 |
-
if not os.path.exists(pdf_path):
|
223 |
-
logging.error(f"PDF file not found at path: {pdf_path}")
|
224 |
-
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
|
225 |
-
try:
|
226 |
-
logging.info(f"Attempting to load/verify data from PDF: {pdf_path}")
|
227 |
-
# Assuming process_and_load_pdf is part of VectorDatabase and correctly implemented
|
228 |
-
num_states_processed = self.vector_db.process_and_load_pdf(pdf_path)
|
229 |
-
doc_count = self.vector_db.document_collection.count()
|
230 |
-
state_count = self.vector_db.state_collection.count()
|
231 |
-
total_items = doc_count + state_count
|
232 |
-
|
233 |
-
if total_items > 0:
|
234 |
-
logging.info(f"Vector DB contains {total_items} items ({doc_count} docs, {state_count} states). PDF processed or data already existed.")
|
235 |
-
current_states = self.get_states()
|
236 |
-
return len(current_states) if current_states and "Error" not in current_states[0] else 0
|
237 |
-
else:
|
238 |
-
logging.warning(f"PDF processing completed, but the vector database appears empty. Check PDF content and processing logs.")
|
239 |
-
return 0
|
240 |
-
|
241 |
-
except Exception as e:
|
242 |
-
logging.error(f"Failed to load or process PDF '{pdf_path}': {str(e)}", exc_info=True)
|
243 |
-
raise RuntimeError(f"Failed to process PDF '{pdf_path}': {e}") from e
|
244 |
-
|
245 |
-
# --- GRADIO INTERFACE (NEW UI DESIGN) ---
|
246 |
-
def gradio_interface(self):
|
247 |
-
def query_interface_wrapper(api_key: str, query: str, state: str) -> str:
|
248 |
-
if not api_key or not api_key.strip() or not api_key.startswith("sk-"):
|
249 |
-
return "<div class='error-message'><span class='error-icon'></span>Please provide a valid OpenAI API key (starting with 'sk-'). <a href='https://platform.openai.com/api-keys' target='_blank'>OpenAI</a>.</div>"
|
250 |
-
if not state or state is None:
|
251 |
-
return "<div class='error-message'><span class='error-icon'></span>Please select a valid state from the list.</div>"
|
252 |
-
if not query or not query.strip():
|
253 |
-
return "<div class='error-message'><span class='error-icon'></span>Please enter your question in the text box.</div>"
|
254 |
-
result = self.process_query(query=query, state=state, openai_api_key=api_key)
|
255 |
-
answer = result.get("answer", "<div class='error-message'><span class='error-icon'>⚠️</span>An unexpected error occurred.</div>")
|
256 |
-
if "<div class='error-message'>" in answer:
|
257 |
-
return answer
|
258 |
-
else:
|
259 |
-
formatted_response_content = f"<div class='response-header'><span class='response-icon'>📜</span>Response for {state}</div><hr class='divider'>{answer}"
|
260 |
-
return f"<div class='animated-output-content'>{formatted_response_content}</div>"
|
261 |
-
|
262 |
-
try:
|
263 |
-
available_states_list = self.get_states()
|
264 |
-
print(f"DEBUG: States loaded for selection: {available_states_list}")
|
265 |
-
radio_choices = available_states_list if available_states_list and "Error" not in available_states_list[0] else ["Error: States unavailable"]
|
266 |
-
initial_value_radio = None
|
267 |
-
except Exception as e:
|
268 |
-
print(f"DEBUG: Error loading states for selection: {e}")
|
269 |
-
radio_choices = ["Error: Critical failure loading states"]
|
270 |
-
initial_value_radio = None
|
271 |
-
example_queries_base = [
|
272 |
-
["What are the rules for security deposit returns?", "California"],
|
273 |
-
["Can a landlord enter my apartment without notice?", "New York"],
|
274 |
-
["My landlord hasn't made necessary repairs. What can I do?", "Texas"],
|
275 |
-
["How much notice must a landlord give to raise rent?", "Florida"],
|
276 |
-
["What is an implied warranty of habitability?", "Illinois"]
|
277 |
-
]
|
278 |
-
example_queries = []
|
279 |
-
if available_states_list and "Error" not in available_states_list[0] and len(available_states_list) > 0:
|
280 |
-
loaded_states_set = set(available_states_list)
|
281 |
-
example_queries = [ex for ex in example_queries_base if ex[1] in loaded_states_set]
|
282 |
-
if not example_queries:
|
283 |
-
example_queries.append(["What basic rights do tenants have?", available_states_list[0] if available_states_list else "California"])
|
284 |
-
else:
|
285 |
-
example_queries.append(["What basic rights do tenants have?", "California"])
|
286 |
-
|
287 |
-
custom_css = """
|
288 |
-
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Poppins:wght@600;700;800&display=swap');
|
289 |
-
:root {
|
290 |
-
--primary-color: #FF8C00;
|
291 |
-
--primary-hover: #E07B00;
|
292 |
-
--background-primary: hsl(30, 100%, 99.9%);
|
293 |
-
--background-secondary: hsl(30, 100%, 96%);
|
294 |
-
--text-primary: #4A3C32;
|
295 |
-
--text-secondary: #8C7B6F;
|
296 |
-
--border-color: hsl(30, 70%, 85%);
|
297 |
-
--border-focus: #FF8C00;
|
298 |
-
--shadow-sm: 0 1px 3px rgba(0,0,0,0.08);
|
299 |
-
--shadow-md: 0 4px 10px rgba(0,0,0,0.1);
|
300 |
-
--shadow-lg: 0 10px 20px rgba(0,0,0,0.15);
|
301 |
-
--error-bg: #FFF0E0;
|
302 |
-
--error-border: #FFD2B2;
|
303 |
-
--error-text: #E05C00;
|
304 |
-
}
|
305 |
-
@media (prefers-color-scheme: dark) {
|
306 |
-
body {
|
307 |
-
--primary-color: #FFA500;
|
308 |
-
--primary-hover: #CC8400;
|
309 |
-
--background-primary: #2C2C2C;
|
310 |
-
--background-secondary: #1F1F1F;
|
311 |
-
--text-primary: #F0F0F0;
|
312 |
-
--text-secondary: #B0B0B0;
|
313 |
-
--border-color: #555555;
|
314 |
-
--border-focus: #FFA500;
|
315 |
-
--shadow-sm: 0 1px 3px rgba(0,0,0,0.3);
|
316 |
-
--shadow-md: 0 4px 10px rgba(0,0,0,0.4);
|
317 |
-
--shadow-lg: 0 10px 20px rgba(0,0,0,0.5);
|
318 |
-
--error-bg: #400000;
|
319 |
-
--error-border: #800000;
|
320 |
-
--error-text: #FF6666;
|
321 |
-
}
|
322 |
-
}
|
323 |
-
body, html {
|
324 |
-
background-color: var(--background-secondary) !important;
|
325 |
-
color: var(--text-primary) !important;
|
326 |
-
transition: background-color 0.3s, color 0.3s;
|
327 |
-
}
|
328 |
-
.gradio-container {
|
329 |
-
max-width: 900px !important;
|
330 |
-
margin: 0 auto !important;
|
331 |
-
padding: 1.5rem !important;
|
332 |
-
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
|
333 |
-
background-color: var(--background-secondary) !important;
|
334 |
-
box-shadow: none !important;
|
335 |
-
color: var(--text-primary) !important;
|
336 |
-
}
|
337 |
-
.main-dashboard-container > * {
|
338 |
-
background-color: var(--background-primary) !important;
|
339 |
-
}
|
340 |
-
.app-header-wrapper {
|
341 |
-
background: linear-gradient(145deg, var(--background-primary) 0%, var(--background-secondary) 100%) !important;
|
342 |
-
border: 2px solid var(--border-color) !important;
|
343 |
-
border-radius: 16px !important;
|
344 |
-
padding: 2.5rem 1.5rem !important;
|
345 |
-
margin-bottom: 1.5rem !important;
|
346 |
-
box-shadow: var(--shadow-md) !important;
|
347 |
-
position: relative;
|
348 |
-
overflow: hidden;
|
349 |
-
text-align: center !important;
|
350 |
-
color: var(--text-primary) !important;
|
351 |
-
}
|
352 |
-
.app-header-wrapper::before {
|
353 |
-
content: '';
|
354 |
-
position: absolute;
|
355 |
-
top: 0;
|
356 |
-
left: 0;
|
357 |
-
width: 100%;
|
358 |
-
height: 100%;
|
359 |
-
background: radial-gradient(circle at top left, rgba(255,140,0,0.3) 0%, transparent 60%), radial-gradient(circle at bottom right, rgba(255,140,0,0.3) 0%, transparent 60%);
|
360 |
-
z-index: 0;
|
361 |
-
opacity: 0.8;
|
362 |
-
pointer-events: none;
|
363 |
-
}
|
364 |
-
.app-header-logo {
|
365 |
-
font-size: 8.5rem !important;
|
366 |
-
margin-bottom: 0.75rem !important;
|
367 |
-
display: block !important;
|
368 |
-
color: var(--primary-color) !important;
|
369 |
-
position: relative;
|
370 |
-
z-index: 1;
|
371 |
-
animation: float-icon 3s ease-in-out infinite alternate;
|
372 |
-
}
|
373 |
-
@keyframes float-icon {
|
374 |
-
0% { transform: translateY(0px); }
|
375 |
-
50% { transform: translateY(-5px); }
|
376 |
-
100% { transform: translateY(0px); }
|
377 |
-
}
|
378 |
-
.app-header-title {
|
379 |
-
font-family: 'Poppins', sans-serif !important;
|
380 |
-
font-size: 3rem !important;
|
381 |
-
font-weight: 800 !important;
|
382 |
-
color: var(--text-primary) !important;
|
383 |
-
margin: 0 0 0.75rem 0 !important;
|
384 |
-
line-height: 1.1 !important;
|
385 |
-
letter-spacing: -0.03em !important;
|
386 |
-
position: relative;
|
387 |
-
z-index: 1;
|
388 |
-
display: inline-block;
|
389 |
-
max-width: 100%;
|
390 |
-
}
|
391 |
-
.app-header-tagline {
|
392 |
-
font-size: 1.25rem !important;
|
393 |
-
color: var(--text-secondary) !important;
|
394 |
-
font-weight: 400 !important;
|
395 |
-
margin: 0 !important;
|
396 |
-
max-width: 700px;
|
397 |
-
display: inline-block;
|
398 |
-
position: relative;
|
399 |
-
z-index: 1;
|
400 |
-
}
|
401 |
-
.main-dashboard-container {
|
402 |
-
display: flex !important;
|
403 |
-
flex-direction: column !important;
|
404 |
-
gap: 1.25rem !important;
|
405 |
-
}
|
406 |
-
.dashboard-card-section {
|
407 |
-
background-color: var(--background-primary) !important;
|
408 |
-
border: 2px solid var(--border-color) !important;
|
409 |
-
border-radius: 12px !important;
|
410 |
-
padding: 0 !important;
|
411 |
-
box-shadow: var(--shadow-sm) !important;
|
412 |
-
transition: all 0.3s ease-out !important;
|
413 |
-
cursor: default;
|
414 |
-
color: var(--text-primary) !important;
|
415 |
-
}
|
416 |
-
.dashboard-card-section:hover {
|
417 |
-
box-shadow: var(--shadow-md) !important;
|
418 |
-
transform: translateY(-3px) !important;
|
419 |
-
}
|
420 |
-
.full-width-center {
|
421 |
-
display: flex !important;
|
422 |
-
justify-content: center !important;
|
423 |
-
align-items: center !important;
|
424 |
-
width: 100% !important;
|
425 |
-
flex-direction: column !important;
|
426 |
-
background-color: transparent !important;
|
427 |
-
}
|
428 |
-
.section-title-gradient-bar {
|
429 |
-
background-color: var(--background-secondary) !important;
|
430 |
-
padding: 1.25rem 1.75rem !important;
|
431 |
-
border-top-left-radius: 10px !important;
|
432 |
-
border-top-right-radius: 10px !important;
|
433 |
-
margin-bottom: 0 !important;
|
434 |
-
text-align: center !important;
|
435 |
-
box-sizing: border-box;
|
436 |
-
width: 100%;
|
437 |
-
color: var(--text-primary) !important;
|
438 |
-
}
|
439 |
-
.section-title {
|
440 |
-
font-family: 'Poppins', sans-serif !important;
|
441 |
-
font-size: 1.7rem !important;
|
442 |
-
font-weight: 700 !important;
|
443 |
-
color: var(--text-primary) !important;
|
444 |
-
margin: 0 !important;
|
445 |
-
padding-bottom: 0 !important;
|
446 |
-
border-bottom: 2px solid var(--border-color) !important;
|
447 |
-
line-height: 1.1 !important;
|
448 |
-
display: inline-block !important;
|
449 |
-
text-align: center !important;
|
450 |
-
letter-spacing: -0.01em !important;
|
451 |
-
}
|
452 |
-
.dashboard-card-content-area {
|
453 |
-
padding: 0 1.75rem 1.75rem 1.75rem !important;
|
454 |
-
background-color: var(--background-primary) !important;
|
455 |
-
box-sizing: border-box;
|
456 |
-
width: 100%;
|
457 |
-
color: var(--text-primary) !important;
|
458 |
-
}
|
459 |
-
.dashboard-card-section p {
|
460 |
-
line-height: 1.7 !important;
|
461 |
-
color: var(--text-primary) !important;
|
462 |
-
font-size: 1rem !important;
|
463 |
-
text-align: left !important;
|
464 |
-
background-color: transparent !important;
|
465 |
-
margin: 0 !important;
|
466 |
-
padding: 0 !important;
|
467 |
-
white-space: normal !important;
|
468 |
-
}
|
469 |
-
.dashboard-card-section strong, .dashboard-card-section b {
|
470 |
-
font-weight: 700 !important;
|
471 |
-
color: var(--primary-color) !important;
|
472 |
-
}
|
473 |
-
.gr-block, .gr-box, .gr-prose, .gr-form, .gr-panel,
|
474 |
-
.gr-columns, .gr-column,
|
475 |
-
.gradio-html, .gradio-markdown, .gradio-textbox, .gradio-radio, .gradio-button {
|
476 |
-
background-color: transparent !important;
|
477 |
-
color: var(--text-primary) !important;
|
478 |
-
white-space: normal !important;
|
479 |
-
overflow-wrap: break-word;
|
480 |
-
word-break: break-word;
|
481 |
-
}
|
482 |
-
.gradio-textbox textarea,
|
483 |
-
.gradio-textbox input,
|
484 |
-
.gradio-radio label,
|
485 |
-
.placeholder {
|
486 |
-
background-color: var(--background-primary) !important;
|
487 |
-
color: var(--text-primary) !important;
|
488 |
-
}
|
489 |
-
.gradio-textbox {
|
490 |
-
margin-bottom: 0.5rem !important;
|
491 |
-
}
|
492 |
-
.gradio-textbox textarea,
|
493 |
-
.gradio-textbox input {
|
494 |
-
border: 2px solid var(--border-color) !important;
|
495 |
-
border-radius: 8px !important;
|
496 |
-
padding: 0.85rem 1rem !important;
|
497 |
-
font-size: 0.98rem !important;
|
498 |
-
font-family: 'Inter', sans-serif !important;
|
499 |
-
color: var(--text-primary) !important;
|
500 |
-
transition: border-color 0.2s ease, box-shadow 0.2s ease !important;
|
501 |
-
box-shadow: var(--shadow-sm) !important;
|
502 |
-
}
|
503 |
-
.gradio-textbox .scroll-hide {
|
504 |
-
background-color: var(--background-primary) !important;
|
505 |
-
}
|
506 |
-
.gradio-textbox textarea:focus,
|
507 |
-
.gradio-textbox input:focus {
|
508 |
-
outline: none !important;
|
509 |
-
border-color: var(--border-focus) !important;
|
510 |
-
box-shadow: 0 0 0 4px rgba(255, 140, 0, 0.2) !important;
|
511 |
-
}
|
512 |
-
.gradio-radio {
|
513 |
-
padding: 0 !important;
|
514 |
-
margin-top: 1rem !important;
|
515 |
-
}
|
516 |
-
.gradio-radio input[type="radio"] {
|
517 |
-
display: none !important;
|
518 |
-
}
|
519 |
-
.gradio-radio label {
|
520 |
-
display: flex !important;
|
521 |
-
justify-content: center !important;
|
522 |
-
align-items: center !important;
|
523 |
-
padding: 0.75rem 1rem !important;
|
524 |
-
border: 2px solid var(--border-color) !important;
|
525 |
-
border-radius: 8px !important;
|
526 |
-
color: var(--text-primary) !important;
|
527 |
-
font-weight: 500 !important;
|
528 |
-
cursor: pointer !important;
|
529 |
-
transition: all 0.2s ease-out !important;
|
530 |
-
box-shadow: var(--shadow-sm) !important;
|
531 |
-
margin: 0.2rem 0 !important;
|
532 |
-
width: 100 !important;
|
533 |
-
box-sizing: border-box !important;
|
534 |
-
}
|
535 |
-
.gradio-radio label span.text-lg {
|
536 |
-
font-weight: 600 !important;
|
537 |
-
color: var(--text-primary) !important;
|
538 |
-
font-size: 0.98rem !important;
|
539 |
-
}
|
540 |
-
.gradio-radio label:hover {
|
541 |
-
background-color: var(--background-secondary) !important;
|
542 |
-
border-color: var(--primary-color) !important;
|
543 |
-
box-shadow: var(--shadow-md) !important;
|
544 |
-
transform: translateY(-2px) !important;
|
545 |
-
}
|
546 |
-
.gradio-radio input[type="radio"]:checked + label {
|
547 |
-
background-color: var(--primary-color) !important;
|
548 |
-
color: var(--text-primary) !important;
|
549 |
-
border-color: var(--primary-hover) !important;
|
550 |
-
box-shadow: var(--shadow-md) !important;
|
551 |
-
transform: translateY(-1px) !important;
|
552 |
-
}
|
553 |
-
.gradio-radio input[type="radio"]:checked + label span.text-lg {
|
554 |
-
color: var(--text-primary) !important;
|
555 |
-
}
|
556 |
-
.gradio-radio .gr-form {
|
557 |
-
padding: 0 !important;
|
558 |
-
}
|
559 |
-
.gradio-textbox label,
|
560 |
-
.gradio-radio > label {
|
561 |
-
font-weight: 600 !important;
|
562 |
-
color: var(--text-primary) !important;
|
563 |
-
font-size: 1rem !important;
|
564 |
-
margin-bottom: 0.6rem !important;
|
565 |
-
display: block !important;
|
566 |
-
text-align: left !important;
|
567 |
-
}
|
568 |
-
.gr-prose {
|
569 |
-
font-size: 0.9rem !important;
|
570 |
-
color: var(--text-secondary) !important;
|
571 |
-
margin-top: 0.4rem !important;
|
572 |
-
text-align: left !important;
|
573 |
-
background-color: transparent !important;
|
574 |
-
}
|
575 |
-
.input-column {
|
576 |
-
display: flex !important;
|
577 |
-
flex-direction: column !important;
|
578 |
-
gap: 1.25rem !important;
|
579 |
-
margin-bottom: 0.5rem !important;
|
580 |
-
}
|
581 |
-
.input-field {
|
582 |
-
flex: none !important;
|
583 |
-
width: 100% !important;
|
584 |
-
}
|
585 |
-
.button-row {
|
586 |
-
display: flex !important;
|
587 |
-
gap: 1rem !important;
|
588 |
-
justify-content: flex-end !important;
|
589 |
-
margin-top: 1.5rem !important;
|
590 |
-
}
|
591 |
-
.gradio-button {
|
592 |
-
padding: 0.85rem 1.8rem !important;
|
593 |
-
border-radius: 9px !important;
|
594 |
-
font-weight: 600 !important;
|
595 |
-
font-size: 1rem !important;
|
596 |
-
transition: all 0.2s ease-out !important;
|
597 |
-
cursor: pointer !important;
|
598 |
-
border: 2px solid transparent !important;
|
599 |
-
text-align: center !important;
|
600 |
-
color: var(--text-primary) !important;
|
601 |
-
}
|
602 |
-
.gr-button-primary {
|
603 |
-
background-color: var(--primary-color) !important;
|
604 |
-
color: white !important;
|
605 |
-
box-shadow: var(--shadow-sm) !important;
|
606 |
-
}
|
607 |
-
.gr-button-primary:hover {
|
608 |
-
background-color: var(--primary-hover) !important;
|
609 |
-
box-shadow: var(--shadow-md) !important;
|
610 |
-
transform: translateY(-2px) !important;
|
611 |
-
}
|
612 |
-
.gr-button-primary:active {
|
613 |
-
transform: translateY(1px) !important;
|
614 |
-
box-shadow: none !important;
|
615 |
-
}
|
616 |
-
.gr-button-secondary {
|
617 |
-
background-color: transparent !important;
|
618 |
-
color: var(--text-primary) !important;
|
619 |
-
border-color: var(--border-color) !important;
|
620 |
-
}
|
621 |
-
.gr-button-secondary:hover {
|
622 |
-
background-color: var(--background-secondary) !important;
|
623 |
-
border-color: var(--primary-color) !important;
|
624 |
-
transform: translateY(-2px) !important;
|
625 |
-
}
|
626 |
-
.gr-button-secondary:active {
|
627 |
-
transform: translateY(1px) !important;
|
628 |
-
box-shadow: none !important;
|
629 |
-
}
|
630 |
-
.output-content-wrapper {
|
631 |
-
background-color: var(--background-primary) !important;
|
632 |
-
border: 2px solid var(--border-color) !important;
|
633 |
-
border-radius: 8px !important;
|
634 |
-
padding: 1.5rem !important;
|
635 |
-
min-height: 150px !important;
|
636 |
-
color: var(--text-primary) !important;
|
637 |
-
display: flex;
|
638 |
-
flex-direction: column;
|
639 |
-
justify-content: center;
|
640 |
-
align-items: center;
|
641 |
-
}
|
642 |
-
.animated-output-content {
|
643 |
-
opacity: 0;
|
644 |
-
animation: fadeInAndSlideUp 0.7s ease-out forwards;
|
645 |
-
width: 100%;
|
646 |
-
white-space: pre-wrap;
|
647 |
-
overflow-wrap: break-word;
|
648 |
-
word-break: break-word;
|
649 |
-
text-align: left !important;
|
650 |
-
color: var(--text-primary) !important;
|
651 |
-
}
|
652 |
-
@keyframes fadeInAndSlideUp {
|
653 |
-
from { opacity: 0; transform: translateY(15px); }
|
654 |
-
to { opacity: 1; transform: translateY(0); }
|
655 |
-
}
|
656 |
-
.response-header {
|
657 |
-
font-size: 1.3rem !important;
|
658 |
-
font-weight: 700 !important;
|
659 |
-
color: var(--primary-color) !important;
|
660 |
-
margin-bottom: 0.75rem !important;
|
661 |
-
display: flex !important;
|
662 |
-
align-items: center !important;
|
663 |
-
gap: 0.6rem !important;
|
664 |
-
text-align: left !important;
|
665 |
-
width: 100%;
|
666 |
-
justify-content: flex-start;
|
667 |
-
}
|
668 |
-
.response-icon {
|
669 |
-
font-size: 1.5rem !important;
|
670 |
-
color: var(--primary-color) !important;
|
671 |
-
}
|
672 |
-
.divider {
|
673 |
-
border: none !important;
|
674 |
-
border-top: 1px dashed var(--border-color) !important;
|
675 |
-
margin: 1rem 0 !important;
|
676 |
-
}
|
677 |
-
.error-message {
|
678 |
-
background-color: var(--error-bg) !important;
|
679 |
-
border: 2px solid var(--error-border) !important;
|
680 |
-
color: var(--error-text) !important;
|
681 |
-
padding: 1.25rem !important;
|
682 |
-
border-radius: 8px !important;
|
683 |
-
display: flex !important;
|
684 |
-
align-items: flex-start !important;
|
685 |
-
gap: 0.8rem !important;
|
686 |
-
font-size: 0.95rem !important;
|
687 |
-
font-weight: 500 !important;
|
688 |
-
line-height: 1.6 !important;
|
689 |
-
text-align: left !important;
|
690 |
-
width: 100%;
|
691 |
-
box-sizing: border-box;
|
692 |
-
}
|
693 |
-
.error-message a {
|
694 |
-
color: var(--error-text) !important;
|
695 |
-
text-decoration: underline !important;
|
696 |
-
}
|
697 |
-
.error-icon {
|
698 |
-
font-size: 1.4rem !important;
|
699 |
-
line-height: 1 !important;
|
700 |
-
margin-top: 0.1rem !important;
|
701 |
-
}
|
702 |
-
.error-details {
|
703 |
-
font-size: 0.85rem !important;
|
704 |
-
color: var(--error-text) !important;
|
705 |
-
margin-top: 0.5rem !important;
|
706 |
-
opacity: 0.8;
|
707 |
-
}
|
708 |
-
.placeholder {
|
709 |
-
background-color: var(--background-primary) !important;
|
710 |
-
border: 2px dashed var(--border-color) !important;
|
711 |
-
border-radius: 8px !important;
|
712 |
-
padding: 2.5rem 1.5rem !important;
|
713 |
-
text-align: center !important;
|
714 |
-
color: var(--text-secondary) !important;
|
715 |
-
font-style: italic !important;
|
716 |
-
font-size: 1.1rem !important;
|
717 |
-
width: 100%;
|
718 |
-
box-sizing: border-box;
|
719 |
-
}
|
720 |
-
.examples-section .gr-samples-table {
|
721 |
-
border: 2px solid var(--border-color) !important;
|
722 |
-
border-radius: 8px !important;
|
723 |
-
overflow: hidden !important;
|
724 |
-
margin-top: 1rem !important;
|
725 |
-
}
|
726 |
-
.examples-section .gr-samples-table th,
|
727 |
-
.examples-section .gr-samples-table td {
|
728 |
-
padding: 0.9rem !important;
|
729 |
-
border: none !important;
|
730 |
-
font-size: 0.95rem !important;
|
731 |
-
text-align: left !important;
|
732 |
-
color: var(--text-primary) !important;
|
733 |
-
}
|
734 |
-
.examples-section .gr-samples-table th {
|
735 |
-
background-color: var(--background-secondary) !important;
|
736 |
-
font-weight: 700 !important;
|
737 |
-
color: var(--text-primary) !important;
|
738 |
-
}
|
739 |
-
.examples-section .gr-samples-table td {
|
740 |
-
background-color: var(--background-primary) !important;
|
741 |
-
color: var(--text-primary) !important;
|
742 |
-
border-top: 1px solid var(--border-color) !important;
|
743 |
-
cursor: pointer !important;
|
744 |
-
transition: background 0.2s ease, transform 0.1s ease !important;
|
745 |
-
}
|
746 |
-
.examples-section .gr-samples-table tr:hover td {
|
747 |
-
background-color: var(--background-secondary) !important;
|
748 |
-
transform: translateX(5px);
|
749 |
-
}
|
750 |
-
.gr-examples .gr-label,
|
751 |
-
.gr-examples .label-wrap,
|
752 |
-
.gr-examples .gr-accordion-header {
|
753 |
-
display: none !important;
|
754 |
-
}
|
755 |
-
.app-footer-wrapper {
|
756 |
-
background: linear-gradient(145deg, var(--background-primary) 0%, var(--background-secondary) 100%) !important;
|
757 |
-
border: 2px solid var(--border-color) !important;
|
758 |
-
border-radius: 12px !important;
|
759 |
-
padding: 1.75rem !important;
|
760 |
-
margin-top: 1.5rem !important;
|
761 |
-
margin-bottom: 1.5rem !important;
|
762 |
-
text-align: center !important;
|
763 |
-
color: var(--text-primary) !important;
|
764 |
-
}
|
765 |
-
.app-footer p {
|
766 |
-
margin: 0 !important;
|
767 |
-
max-width: 90% !important;
|
768 |
-
font-size: 0.95rem !important;
|
769 |
-
color: var(--text-secondary) !important;
|
770 |
-
line-height: 1.6 !important;
|
771 |
-
background-color: transparent !important;
|
772 |
-
text-align: center !important;
|
773 |
-
white-space: normal !important;
|
774 |
-
}
|
775 |
-
.app-footer strong, .app-footer b {
|
776 |
-
font-weight: 700 !important;
|
777 |
-
color: var(--primary-color) !important;
|
778 |
-
}
|
779 |
-
.app-footer a {
|
780 |
-
color: var(--primary-color) !important;
|
781 |
-
text-decoration: underline !important;
|
782 |
-
font-weight: 600 !important;
|
783 |
-
}
|
784 |
-
.app-footer a:hover {
|
785 |
-
text-decoration: none !important;
|
786 |
-
}
|
787 |
-
@media (max-width: 768px) {
|
788 |
-
.gradio-container {
|
789 |
-
padding: 1rem !important;
|
790 |
-
}
|
791 |
-
.app-header-title {
|
792 |
-
font-size: 2.2rem !important;
|
793 |
-
}
|
794 |
-
.app-header-tagline {
|
795 |
-
font-size: 1rem !important;
|
796 |
-
}
|
797 |
-
.section-title {
|
798 |
-
font-size: 1.4rem !important;
|
799 |
-
}
|
800 |
-
.input-column {
|
801 |
-
flex-direction: column !important;
|
802 |
-
}
|
803 |
-
.button-row {
|
804 |
-
flex-direction: column !important;
|
805 |
-
}
|
806 |
-
.gradio-button {
|
807 |
-
width: 100% !important;
|
808 |
-
}
|
809 |
-
.dashboard-card-section {
|
810 |
-
}
|
811 |
-
.section-title-gradient-bar {
|
812 |
-
padding: 0.1rem 1rem !important;
|
813 |
-
}
|
814 |
-
.dashboard-card-content-area {
|
815 |
-
padding: 0 1rem 1rem 1rem !important;
|
816 |
-
}
|
817 |
-
.output-content-wrapper {
|
818 |
-
min-height: 120px !important;
|
819 |
-
}
|
820 |
-
.placeholder {
|
821 |
-
padding: 1.5rem 1rem !important;
|
822 |
-
font-size: 1rem !important;
|
823 |
-
}
|
824 |
-
}
|
825 |
-
"""
|
826 |
-
|
827 |
-
with gr.Blocks(css=custom_css, title="Landlord-Tenant Rights Assistant") as demo:
|
828 |
-
with gr.Group(elem_classes="app-header-wrapper"):
|
829 |
-
gr.Markdown(
|
830 |
-
"""
|
831 |
-
<span class='app-header-logo'>⚖️</span>
|
832 |
-
<h1 class='app-header-title'>Landlord-Tenant Rights Assistant</h1>
|
833 |
-
<p class='app-header-tagline'>Empowering You with State-Specific Legal Insights</p>
|
834 |
-
""",
|
835 |
-
elem_classes="full-width-center"
|
836 |
-
)
|
837 |
-
|
838 |
-
with gr.Column(elem_classes="main-dashboard-container"):
|
839 |
-
with gr.Group(elem_classes="dashboard-card-section"):
|
840 |
-
gr.Markdown("<h3 class='section-title'>How This Assistant Works</h3>", elem_classes="full-width-center section-title-gradient-bar")
|
841 |
-
with gr.Column(elem_classes="dashboard-card-content-area"):
|
842 |
-
gr.Markdown(
|
843 |
-
"""
|
844 |
-
This AI-powered assistant helps navigate complex landlord-tenant laws. Simply ask a question about your state's regulations, and it will provide detailed, legally-grounded insights.
|
845 |
-
"""
|
846 |
-
)
|
847 |
-
|
848 |
-
with gr.Group(elem_classes="dashboard-card-section"):
|
849 |
-
gr.Markdown("<h3 class='section-title'>OpenAI API Key</h3>", elem_classes="full-width-center section-title-gradient-bar")
|
850 |
-
with gr.Column(elem_classes="dashboard-card-content-area"):
|
851 |
-
api_key_input = gr.Textbox(
|
852 |
-
label="API Key",
|
853 |
-
type="password",
|
854 |
-
placeholder="Enter your OpenAI API key (e.g., sk-...)",
|
855 |
-
lines=1,
|
856 |
-
elem_classes=["input-field-group"]
|
857 |
-
)
|
858 |
-
gr.Markdown(
|
859 |
-
"Required to process your query. Get one from OpenAI: [platform.openai.com/api-keys](https://platform.openai.com/api-keys)",
|
860 |
-
elem_classes="gr-prose"
|
861 |
-
)
|
862 |
-
|
863 |
-
with gr.Group(elem_classes="dashboard-card-section"):
|
864 |
-
gr.Markdown("<h3 class='section-title'>Ask Your Question</h3>", elem_classes="full-width-center section-title-gradient-bar")
|
865 |
-
with gr.Column(elem_classes="dashboard-card-content-area"):
|
866 |
-
with gr.Column(elem_classes="input-column"):
|
867 |
-
with gr.Column(elem_classes="input-field", scale=1):
|
868 |
-
query_input = gr.Textbox(
|
869 |
-
label="Your Question",
|
870 |
-
placeholder="E.g., What are the rules for security deposit returns in my state?",
|
871 |
-
lines=8,
|
872 |
-
max_lines=15,
|
873 |
-
elem_classes=["input-field-group"]
|
874 |
-
)
|
875 |
-
with gr.Column(elem_classes="input-field", scale=1):
|
876 |
-
state_input = gr.Radio(
|
877 |
-
label="Select State",
|
878 |
-
choices=radio_choices,
|
879 |
-
value=initial_value_radio,
|
880 |
-
elem_classes=["input-field-group", "gradio-radio-custom"],
|
881 |
-
interactive=True
|
882 |
-
)
|
883 |
-
with gr.Row(elem_classes="button-row"):
|
884 |
-
clear_button = gr.Button("Clear", variant="secondary", elem_classes=["gr-button-secondary"])
|
885 |
-
submit_button = gr.Button("Submit Query", variant="primary", elem_classes=["gr-button-primary"])
|
886 |
-
|
887 |
-
with gr.Group(elem_classes="dashboard-card-section"):
|
888 |
-
gr.Markdown("<h3 class='section-title'>Legal Assistant's Response</h3>", elem_classes="full-width-center section-title-gradient-bar")
|
889 |
-
with gr.Column(elem_classes="dashboard-card-content-area"):
|
890 |
-
output = gr.HTML(
|
891 |
-
value="<div class='placeholder'>The answer will appear here after submitting your query.</div>",
|
892 |
-
elem_classes="output-content-wrapper"
|
893 |
-
)
|
894 |
-
|
895 |
-
with gr.Group(elem_classes="dashboard-card-section examples-section"):
|
896 |
-
gr.Markdown("<h3 class='section-title'>Example Questions</h3>", elem_classes="full-width-center section-title-gradient-bar")
|
897 |
-
with gr.Column(elem_classes="dashboard-card-content-area"):
|
898 |
-
if example_queries:
|
899 |
-
gr.Examples(
|
900 |
-
examples=example_queries,
|
901 |
-
inputs=[query_input, state_input],
|
902 |
-
examples_per_page=5,
|
903 |
-
label=""
|
904 |
-
)
|
905 |
-
else:
|
906 |
-
gr.Markdown("<div class='placeholder'>Sample questions could not be loaded. Please ensure the vector database is populated.</div>")
|
907 |
-
|
908 |
-
with gr.Group(elem_classes="app-footer-wrapper"):
|
909 |
-
gr.Markdown(
|
910 |
-
f"""
|
911 |
-
<style>
|
912 |
-
.custom-link {{
|
913 |
-
font-weight: bold !important;
|
914 |
-
color: orange !important;
|
915 |
-
text-decoration: underline;
|
916 |
-
}}
|
917 |
-
</style>
|
918 |
-
<p><strong>Disclaimer:</strong> This tool is for informational purposes only and does not constitute legal advice. For specific legal guidance, always consult with a licensed attorney in your jurisdiction.</p>
|
919 |
-
<p>Developed by <strong>Nischal Subedi</strong>. Connect on <a href="https://www.linkedin.com/in/nischal1/" target="_blank" class="custom-link">LinkedIn</a> or explore insights at <a href="https://datascientistinsights.substack.com/" target="_blank" class="custom-link">Substack</a>.</p>
|
920 |
-
"""
|
921 |
-
)
|
922 |
-
|
923 |
-
submit_button.click(
|
924 |
-
fn=query_interface_wrapper,
|
925 |
-
inputs=[api_key_input, query_input, state_input],
|
926 |
-
outputs=output,
|
927 |
-
api_name="submit_query"
|
928 |
-
)
|
929 |
-
|
930 |
-
clear_button.click(
|
931 |
-
fn=lambda: (
|
932 |
-
"", "", initial_value_radio, "<div class='placeholder'>Inputs cleared. Ready for your next question.</div>"
|
933 |
-
),
|
934 |
-
inputs=[],
|
935 |
-
outputs=[api_key_input, query_input, state_input, output]
|
936 |
-
)
|
937 |
-
|
938 |
-
return demo
|
939 |
-
|
940 |
-
# --- Main Execution Block (UNCHANGED from original logic) ---
|
941 |
-
if __name__ == "__main__":
|
942 |
-
logging.info("Starting Landlord-Tenant Rights Bot application...")
|
943 |
-
try:
|
944 |
-
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
945 |
-
DEFAULT_PDF_PATH = os.path.join(SCRIPT_DIR, "tenant-landlord.pdf")
|
946 |
-
DEFAULT_DB_PATH = os.path.join(SCRIPT_DIR, "chroma_db")
|
947 |
-
|
948 |
-
PDF_PATH = os.getenv("PDF_PATH", DEFAULT_PDF_PATH)
|
949 |
-
VECTOR_DB_PATH = os.getenv("VECTOR_DB_PATH", DEFAULT_DB_PATH)
|
950 |
-
|
951 |
-
# Ensure vector DB directory exists before initialization
|
952 |
-
os.makedirs(os.path.dirname(VECTOR_DB_PATH), exist_ok=True)
|
953 |
-
|
954 |
-
logging.info(f"Attempting to load PDF from: {PDF_PATH}")
|
955 |
-
if not os.path.exists(PDF_PATH):
|
956 |
-
logging.error(f"FATAL: PDF file not found at the specified path: {PDF_PATH}")
|
957 |
-
print(f"\n--- CONFIGURATION ERROR ---\nPDF file ('{os.path.basename(PDF_PATH)}') not found at: {PDF_PATH}.\nPlease ensure it exists or set 'PDF_PATH' environment variable.\n---------------------------\n")
|
958 |
-
exit(1) # Correctly exits if PDF is not found
|
959 |
-
|
960 |
-
if not os.access(PDF_PATH, os.R_OK):
|
961 |
-
logging.error(f"FATAL: PDF file at '{PDF_PATH}' exists but is not readable. Check file permissions.")
|
962 |
-
print(f"\n--- PERMISSION ERROR ---\nPDF file ('{os.path.basename(PDF_PATH)}') found but not readable at: {PDF_PATH}\nPlease check file permissions (e.g., using 'chmod +r' in terminal).\n---------------------------\n")
|
963 |
-
exit(1) # Correctly exits if PDF is unreadable
|
964 |
-
|
965 |
-
logging.info(f"PDF file '{os.path.basename(PDF_PATH)}' found and is readable.")
|
966 |
-
|
967 |
-
# Initialize VectorDatabase and RAGSystem
|
968 |
-
vector_db_instance = VectorDatabase(persist_directory=VECTOR_DB_PATH)
|
969 |
-
rag = RAGSystem(vector_db=vector_db_instance)
|
970 |
-
|
971 |
-
# Load PDF data into the vector DB (or verify it's already loaded)
|
972 |
-
rag.load_pdf(PDF_PATH)
|
973 |
-
|
974 |
-
# Get the Gradio interface object
|
975 |
-
app_interface = rag.gradio_interface()
|
976 |
-
SERVER_PORT = int(os.getenv("PORT", 7860)) # Use PORT env var for Hugging Face Spaces
|
977 |
-
|
978 |
-
logging.info(f"Launching Gradio app on http://0.0.0.0:{SERVER_PORT}")
|
979 |
-
print(f"\n--- Gradio App Running ---\nAccess at: http://localhost:{SERVER_PORT} or your public Spaces URL\n--------------------------\n")
|
980 |
-
app_interface.launch(server_name="0.0.0.0", server_port=SERVER_PORT, share=False) # share=False is typical for Spaces
|
981 |
-
|
982 |
-
except ModuleNotFoundError as e:
|
983 |
-
if "vector_db" in str(e):
|
984 |
-
logging.error(f"FATAL: Could not import VectorDatabase. Ensure 'vector_db.py' is in the same directory and 'chromadb', 'langchain', 'pypdf', 'sentence-transformers' are installed.", exc_info=True)
|
985 |
-
print(f"\n--- MISSING DEPENDENCY OR FILE ---\nCould not find/import 'vector_db.py' or one of its dependencies.\nError: {e}\nPlease ensure 'vector_db.py' is present and all required packages (chromadb, langchain, pypdf, sentence-transformers, etc.) are in your requirements.txt and installed.\n---------------------------\n")
|
986 |
-
else:
|
987 |
-
logging.error(f"Application startup failed due to a missing module: {str(e)}", exc_info=True)
|
988 |
-
print(f"\n--- FATAL STARTUP ERROR - MISSING MODULE ---\n{str(e)}\nPlease ensure all dependencies are installed.\nCheck logs for more details.\n---------------------------\n")
|
989 |
-
exit(1)
|
990 |
-
except FileNotFoundError as e:
|
991 |
-
logging.error(f"Application startup failed due to a missing file: {str(e)}", exc_info=True)
|
992 |
-
print(f"\n--- FATAL STARTUP ERROR - FILE NOT FOUND ---\n{str(e)}\nPlease ensure the file exists at the specified path.\nCheck logs for more details.\n---------------------------\n")
|
993 |
-
exit(1)
|
994 |
-
except Exception as e:
|
995 |
-
logging.error(f"Application startup failed: {str(e)}", exc_info=True)
|
996 |
-
print(f"\n--- FATAL STARTUP ERROR ---\n{str(e)}\nCheck logs for more details.\n---------------------------\n")
|
997 |
-
exit(1)
|
|
|
1 |
+
8336e55143b532480e93ba09054e9e93fb2427ed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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