File size: 45,790 Bytes
b9756ef bfee845 b9756ef bfee845 ea0c3e1 04c4d5a 0634f1a 9d5f183 4ebf92d 0634f1a b9756ef ea0c3e1 0634f1a 7c7cb71 ea0c3e1 408ac65 b9756ef bfee845 b9756ef 0634f1a b9756ef 7c7cb71 b9756ef bfee845 b9756ef 2e6a585 b9756ef bfee845 b9756ef bfee845 ea0c3e1 7c7cb71 0634f1a bfee845 7c7cb71 0634f1a ae4713f 0634f1a bfee845 7c7cb71 0634f1a bfee845 0634f1a ea0c3e1 bfee845 0634f1a bfee845 0634f1a b9756ef 0634f1a b9756ef 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a bfee845 b9756ef 0634f1a bfee845 0634f1a ed1ba16 0634f1a bfee845 0634f1a bfee845 b9756ef bfee845 0634f1a bfee845 0634f1a bfee845 0634f1a ae4713f 0634f1a ed1ba16 0634f1a bfee845 0634f1a 7c7cb71 b9756ef bfee845 0634f1a b9756ef 0634f1a ea0c3e1 b9756ef bfee845 0634f1a b9756ef 0634f1a ae4713f 0634f1a bfee845 0634f1a b9756ef bfee845 0634f1a bfee845 04c4d5a 7c7cb71 0634f1a 9d5f183 0634f1a 9d5f183 0634f1a d55a911 0634f1a d55a911 56f099b 408ac65 bfee845 d55a911 408ac65 ae4713f 0634f1a ae4713f bfee845 0634f1a d55a911 56f099b 0634f1a 408ac65 0634f1a 9d5f183 b9756ef 0634f1a 56f099b 0634f1a 2e6a585 0634f1a 408ac65 ae4713f 408ac65 d55a911 0634f1a d55a911 04c4d5a 4c5479b 2e6a585 04c4d5a 408ac65 04c4d5a 408ac65 04c4d5a 408ac65 04c4d5a 408ac65 ae4713f 408ac65 ae4713f 04c4d5a ae4713f 2e6a585 408ac65 04c4d5a ae4713f 2e6a585 408ac65 04c4d5a ae4713f 2e6a585 408ac65 04c4d5a ed1ba16 04c4d5a ae4713f 04c4d5a d55a911 04c4d5a ed1ba16 04c4d5a ae4713f ed1ba16 04c4d5a ed1ba16 04c4d5a 408ac65 04c4d5a 3e20ea0 04c4d5a ae4713f 04c4d5a 408ac65 04c4d5a ed1ba16 04c4d5a 408ac65 ed1ba16 04c4d5a 408ac65 04c4d5a ae4713f 04c4d5a ae4713f 408ac65 04c4d5a 408ac65 ae4713f 2e6a585 408ac65 04c4d5a 408ac65 2e6a585 ae4713f 04c4d5a ae4713f 04c4d5a ae4713f 408ac65 04c4d5a 408ac65 ae4713f 2e6a585 ae4713f 04c4d5a ae4713f 408ac65 ae4713f 04c4d5a ae4713f 408ac65 04c4d5a ae4713f 2e6a585 04c4d5a 2e6a585 b14d947 04c4d5a ae4713f 408ac65 b14d947 04c4d5a 408ac65 04c4d5a b14d947 04c4d5a 408ac65 04c4d5a ae4713f 04c4d5a 4d60153 04c4d5a 2e6a585 4d60153 04c4d5a 408ac65 04c4d5a 408ac65 4d60153 2e6a585 4d60153 04c4d5a 408ac65 04c4d5a 9d5f183 ae4713f 04c4d5a 2e6a585 ae4713f 04c4d5a ae4713f ed1ba16 b14d947 04c4d5a ae4713f 408ac65 2e6a585 04c4d5a ae4713f 2e6a585 04c4d5a ae4713f 2e6a585 ae4713f ed1ba16 b62d4ec b14d947 04c4d5a ae4713f 408ac65 2e6a585 04c4d5a ae4713f 2e6a585 04c4d5a 2e6a585 ae4713f ed1ba16 9ed8c63 b14d947 04c4d5a ae4713f 408ac65 4c5479b 04c4d5a ed1ba16 56f099b 7c7cb71 04c4d5a ed1ba16 04c4d5a ed1ba16 ea4e4a0 ed1ba16 2e6a585 ed1ba16 04c4d5a d55a911 04c4d5a b62d4ec 9d5f183 d55a911 ae4713f ed1ba16 04c4d5a 4ebf92d ae4713f ed1ba16 9ed8c63 9d5f183 ed1ba16 4ebf92d ed1ba16 9d5f183 ed1ba16 04c4d5a ed1ba16 4ebf92d ed1ba16 ae4713f 04c4d5a ae4713f 04c4d5a 2e6a585 04c4d5a 2e6a585 d55a911 ed1ba16 56f099b 4d60153 56f099b 229d1b2 2e6a585 7c7cb71 d55a911 7c7cb71 408ac65 4ebf92d ae4713f 408ac65 d55a911 7c7cb71 04c4d5a ae4713f 408ac65 ea0c3e1 0634f1a b9756ef 0634f1a fb10b7c bfee845 0634f1a bfee845 0634f1a 408ac65 2e6a585 0634f1a 2e6a585 0634f1a 4ebf92d 2e6a585 0634f1a bfee845 4ebf92d ae4713f 4ebf92d bfee845 ae4713f 4ebf92d 0634f1a ae4713f 04c4d5a ae4713f b9756ef d55a911 408ac65 0634f1a |
1 2 3 4 5 6 7 8 9 10 11 12 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 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 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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 |
import os
import logging
from typing import Dict, List, Optional
from functools import lru_cache
import re
import gradio as gr
import gradio.themes as themes # Import gradio.themes
try:
# Assuming vector_db.py exists in the same directory or is installed
from vector_db import VectorDatabase
except ImportError:
print("Error: Could not import VectorDatabase from vector_db.py.")
print("Please ensure vector_db.py exists in the same directory and is correctly defined.")
exit(1)
try:
from langchain_openai import ChatOpenAI
except ImportError:
print("Error: langchain-openai not found. Please install it: pip install langchain-openai")
exit(1)
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# Suppress warnings
import warnings
warnings.filterwarnings("ignore", category=SyntaxWarning)
warnings.filterwarnings("ignore", category=UserWarning, message=".*You are using gradio version.*")
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Enhanced logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
)
# --- RAGSystem Class (Processing Logic - kept intact as requested) ---
class RAGSystem:
def __init__(self, vector_db: Optional[VectorDatabase] = None):
logging.info("Initializing RAGSystem")
self.vector_db = vector_db if vector_db else VectorDatabase()
self.llm = None
self.chain = None
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.
Instructions:
* Use the context and statutes as the primary basis for your answer when available.
* For state-specific queries, prioritize statutes or legal principles from the specified state over federal laws.
* Cite relevant statutes (e.g., (AS § 34.03.220(a)(2))) explicitly in your answer when applicable.
* If multiple statutes apply, list all relevant ones.
* 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.
* Include practical examples or scenarios to enhance clarity and usefulness.
* Use bullet points or numbered lists for readability when appropriate.
* Maintain a professional and neutral tone.
Question: {query}
State: {state}
Statutes from context:
{statutes}
Context information:
--- START CONTEXT ---
{context}
--- END CONCONTEXT ---
Answer:"""
self.prompt_template = PromptTemplate(
input_variables=["query", "context", "state", "statutes"],
template=self.prompt_template_str
)
logging.info("RAGSystem initialized.")
def extract_statutes(self, text: str) -> str:
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'
statutes = re.findall(statute_pattern, text, re.IGNORECASE)
valid_statutes = []
for statute in statutes:
statute = statute.strip()
if '§' in statute and any(char.isdigit() for char in statute):
if not re.match(r'^\([\w\.]+\)$', statute) and 'http' not in statute:
if len(statute) > 5:
valid_statutes.append(statute)
if valid_statutes:
seen = set()
unique_statutes = [s for s in valid_statutes if not (s.rstrip('.,;') in seen or seen.add(s.rstrip('.,;')))]
logging.info(f"Extracted {len(unique_statutes)} unique statutes.")
return "\n".join(f"- {s}" for s in unique_statutes)
logging.info("No statutes found matching the pattern in the context.")
return "No specific statutes found in the provided context."
@lru_cache(maxsize=50)
def process_query_cached(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
logging.info(f"Processing query (cache key: '{query}'|'{state}'|key_hidden) with n_results={n_results}")
if not state or state == "Select a state..." or "Error" in state:
logging.warning("No valid state provided for query.")
return {"answer": "<div class='error-message'>Error: Please select a valid state.</div>", "context_used": "N/A - Invalid Input"}
if not query or not query.strip():
logging.warning("No query provided.")
return {"answer": "<div class='error-message'>Error: Please enter your question.</div>", "context_used": "N/A - Invalid Input"}
if not openai_api_key or not openai_api_key.strip() or not openai_api_key.startswith("sk-"):
logging.warning("No valid OpenAI API key provided.")
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"}
try:
logging.info("Initializing temporary LLM and Chain for this query...")
temp_llm = ChatOpenAI(
temperature=0.2, openai_api_key=openai_api_key, model_name="gpt-3.5-turbo",
max_tokens=1500, request_timeout=45
)
temp_chain = LLMChain(llm=temp_llm, prompt=self.prompt_template)
logging.info("Temporary LLM and Chain initialized successfully.")
except Exception as e:
logging.error(f"LLM Initialization failed: {str(e)}", exc_info=True)
error_msg = "Error: Failed to initialize AI model. Please check your network connection and API key validity."
if "authentication" in str(e).lower():
error_msg = "Error: OpenAI API Key is invalid or expired. Please check your key."
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"}
context = "No relevant context found."
statutes_from_context = "Statute retrieval skipped due to context issues."
try:
logging.info(f"Querying Vector DB for query: '{query[:50]}...' in state '{state}'...")
results = self.vector_db.query(query, state=state, n_results=n_results)
logging.info(f"Vector DB query successful for state '{state}'. Processing results...")
context_parts = []
doc_results = results.get("document_results", {})
docs = doc_results.get("documents", [[]])[0]
metadatas = doc_results.get("metadatas", [[]])[0]
if docs and metadatas and len(docs) == len(metadatas):
logging.info(f"Found {len(docs)} document chunks.")
for i, doc_content in enumerate(docs):
metadata = metadatas[i]
state_label = metadata.get('state', 'Unknown State')
chunk_id = metadata.get('chunk_id', 'N/A')
context_parts.append(f"**Source: Document Chunk {chunk_id} (State: {state_label})**\n{doc_content}")
state_results_data = results.get("state_results", {})
state_docs = state_results_data.get("documents", [[]])[0]
state_metadatas = state_results_data.get("metadatas", [[]])[0]
if state_docs and state_metadatas and len(state_docs) == len(state_metadatas):
logging.info(f"Found {len(state_docs)} state summary documents.")
for i, state_doc_content in enumerate(state_docs):
metadata = state_metadatas[i]
state_label = metadata.get('state', state)
context_parts.append(f"**Source: State Summary (State: {state_label})**\n{state_doc_content}")
if context_parts:
context = "\n\n---\n\n".join(context_parts)
logging.info(f"Constructed context with {len(context_parts)} parts. Length: {len(context)} chars.")
try:
statutes_from_context = self.extract_statutes(context)
except Exception as e:
logging.error(f"Error extracting statutes: {e}", exc_info=True)
statutes_from_context = "Error extracting statutes from context."
else:
logging.warning("No relevant context parts found from vector DB query.")
context = "No relevant context could be retrieved from the knowledge base for this query and state. The AI will answer from its general knowledge."
statutes_from_context = "No specific statutes found as no context was retrieved."
except Exception as e:
logging.error(f"Vector DB query/context processing failed: {str(e)}", exc_info=True)
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."
statutes_from_context = "Statute retrieval skipped due to error retrieving context."
try:
logging.info("Invoking LLMChain with constructed input...")
llm_input = {"query": query, "context": context, "state": state, "statutes": statutes_from_context}
answer_dict = temp_chain.invoke(llm_input)
answer_text = answer_dict.get('text', '').strip()
if not answer_text:
logging.warning("LLM returned an empty answer.")
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>"
else:
logging.info("LLM generated answer successfully.")
return {"answer": answer_text, "context_used": context}
except Exception as e:
logging.error(f"LLM processing failed: {str(e)}", exc_info=True)
error_message = "Error: AI answer generation failed."
details = f"Details: {str(e)}"
if "authentication" in str(e).lower():
error_message = "Error: Authentication failed. Please double-check your OpenAI API key."
details = ""
elif "rate limit" in str(e).lower():
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."
details = ""
elif "context length" in str(e).lower():
error_message = "Error: The request was too long for the AI model. This can happen with very complex questions or extensive retrieved context."
details = "Try simplifying your question or asking about a more specific aspect."
elif "timeout" in str(e).lower():
error_message = "Error: The request to the AI model timed out. The service might be busy."
details = "Please try again in a few moments."
formatted_error = f"<div class='error-message'><span class='error-icon'>❌</span>{error_message}</div>"
if details:
formatted_error += f"<div class='error-details'>{details}</div>"
return {"answer": formatted_error, "context_used": context}
def process_query(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
return self.process_query_cached(query.strip(), state, openai_api_key.strip(), n_results)
def get_states(self) -> List[str]:
try:
states = self.vector_db.get_states()
if not states:
logging.warning("No states retrieved from vector_db. Returning empty list.")
return []
valid_states = sorted(list(set(s for s in states if s and isinstance(s, str) and s != "Select a state...")))
logging.info(f"Retrieved {len(valid_states)} unique, valid states from VectorDatabase.")
return valid_states
except Exception as e:
logging.error(f"Failed to get states from VectorDatabase: {str(e)}", exc_info=True)
return ["Error: Could not load states"]
def load_pdf(self, pdf_path: str) -> int:
if not os.path.exists(pdf_path):
logging.error(f"PDF file not found at path: {pdf_path}")
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
try:
logging.info(f"Attempting to load/verify data from PDF: {pdf_path}")
# Assuming process_and_load_pdf is part of VectorDatabase and correctly implemented
num_states_processed = self.vector_db.process_and_load_pdf(pdf_path)
doc_count = self.vector_db.document_collection.count()
state_count = self.vector_db.state_collection.count()
total_items = doc_count + state_count
if total_items > 0:
logging.info(f"Vector DB contains {total_items} items ({doc_count} docs, {state_count} states). PDF processed or data already existed.")
current_states = self.get_states()
return len(current_states) if current_states and "Error" not in current_states[0] else 0
else:
logging.warning(f"PDF processing completed, but the vector database appears empty. Check PDF content and processing logs.")
return 0
except Exception as e:
logging.error(f"Failed to load or process PDF '{pdf_path}': {str(e)}", exc_info=True)
raise RuntimeError(f"Failed to process PDF '{pdf_path}': {e}") from e
# --- GRADIO INTERFACE (Refactored to use earneleh/paris theme) ---
def gradio_interface(self):
def query_interface_wrapper(api_key: str, query: str, state: str) -> str:
# Basic client-side validation for immediate feedback (redundant but good UX)
if not api_key or not api_key.strip() or not api_key.startswith("sk-"):
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'>Get one free from OpenAI</a>.</div>"
if not state or state == "Select a state..." or "Error" in state:
return "<div class='error-message'><span class='error-icon'>⚠️</span>Please select a valid state from the dropdown.</div>"
if not query or not query.strip():
return "<div class='error-message'><span class='error-icon'>⚠️</span>Please enter your question in the text box.</div>"
# Call the core processing logic
result = self.process_query(query=query, state=state, openai_api_key=api_key)
answer = result.get("answer", "<div class='error-message'><span class='error-icon'>⚠️</span>An unexpected error occurred.</div>")
# Check if the answer already contains an error message (from deeper within process_query)
if "<div class='error-message'>" in answer:
return answer # Return the pre-formatted error message directly
else:
# Format the successful response with the new UI structure
formatted_response = f"<div class='response-header'><span class='response-icon'>📜</span>Response for {state}</div><hr class='divider'>{answer}"
return formatted_response
try:
available_states_list = self.get_states()
dropdown_choices = ["Select a state..."] + (available_states_list if available_states_list and "Error" not in available_states_list[0] else ["Error: States unavailable"])
initial_value = dropdown_choices[0]
except Exception: # Catch-all for safety
dropdown_choices = ["Error: Critical failure loading states"]
initial_value = dropdown_choices[0]
# Define example queries, filtering based on available states
example_queries_base = [
["What are the rules for security deposit returns?", "California"],
["Can a landlord enter my apartment without notice?", "New York"],
["My landlord hasn't made necessary repairs. What can I do?", "Texas"],
["How much notice must a landlord give to raise rent?", "Florida"],
["What is an implied warranty of habitability?", "Illinois"]
]
example_queries = []
if available_states_list and "Error" not in available_states_list[0] and len(available_states_list) > 0:
loaded_states_set = set(available_states_list)
# Filter for examples whose state is in the loaded states
example_queries = [ex for ex in example_queries_base if ex[1] in loaded_states_set]
# Add a generic example if no specific state examples match or if list is empty
if not example_queries:
example_queries.append(["What basic rights do tenants have?", available_states_list[0] if available_states_list else "California"])
else: # Fallback if states list is problematic
example_queries.append(["What basic rights do tenants have?", "California"])
# --- Minimal Custom CSS for structural/behavioral overrides not covered by the theme ---
# This CSS focuses on animations, specific layout tweaks, and hiding unwanted Gradio default elements.
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@700;800;900&display=swap');
/* Animation for header */
@keyframes fadeInSlideDown { from { opacity: 0; transform: translateY(-40px); } to { opacity: 1; transform: translateY(0); } }
/* General layout adjustments to Gradio's base container */
.gradio-container > .flex.flex-col {
max-width: 1120px;
margin: 0 auto !important;
padding: 0 !important; /* Remove default Gradio padding */
gap: 0 !important; /* Remove default Gradio gap */
}
/* Header specific styling */
.app-header-wrapper {
padding: 4.5rem 3.5rem !important; /* Use hardcoded padding to override theme potentially */
text-align: center !important;
border-bottom-left-radius: 24px; /* Use hardcoded radius */
border-bottom-right-radius: 24px;
position: relative;
overflow: hidden;
z-index: 10;
margin-bottom: 2.5rem; /* Use hardcoded margin */
border: 1px solid var(--border-color-primary) !important;
border-top: none;
max-width: 1120px;
margin-left: auto;
margin-right: auto;
width: 100%;
}
.app-header { display: flex; flex-direction: column; align-items: center; position: relative; z-index: 1; }
.app-header-logo {
font-size: 5.5rem; margin-bottom: 0.8rem; line-height: 1;
filter: drop-shadow(0 0 15px var(--primary-500)); /* Using primary color from theme */
transform: translateY(-40px); opacity: 0;
animation: fadeInSlideDown 1.5s ease-out forwards; animation-delay: 0.3s;
}
.app-header-title {
font-family: 'Playfair Display', serif !important; /* Explicit font family */
font-size: 4.2rem; font-weight: 900;
margin: 0 0 0.8rem 0; letter-spacing: -0.07em;
text-shadow: 0 8px 16px rgba(0,0,0,0.5);
transform: translateY(-40px); opacity: 0;
animation: fadeInSlideDown 1.5s ease-out forwards; animation-delay: 0.6s;
}
.app-header-tagline {
font-family: 'Inter', sans-serif !important; /* Explicit font family */
font-size: 1.6rem; font-weight: 300;
opacity: 0.9; max-width: 900px;
transform: translateY(-40px); opacity: 0;
animation: fadeInSlideDown 1.5s ease-out forwards; animation-delay: 0.9s;
}
/* Main dashboard container */
.main-dashboard-container {
border-radius: 24px; /* Use hardcoded radius */
border: 1px solid var(--border-color-primary) !important;
padding: 3.5rem !important; /* Use hardcoded padding */
margin: 0 auto 0.8rem auto;
z-index: 1; position: relative;
display: flex; flex-direction: column; gap: 2.5rem; /* Use hardcoded gap */
max-width: 1120px;
}
/* Card sections within the dashboard */
.dashboard-card-section {
border-radius: 12px; /* Use hardcoded radius */
border: 1px solid var(--border-color-primary);
padding: 2.5rem; /* Use hardcoded padding */
box-shadow: inset 0 0 10px rgba(0,0,0,0.2);
display: flex; flex-direction: column; gap: 1.5rem;
}
/* Light mode specific inner shadow for card sections */
@media (prefers-color-scheme: light) {
.dashboard-card-section { box-shadow: inset 0 0 8px rgba(0,0,0,0.05); }
}
/* Section titles */
.sub-section-title {
font-family: 'Playfair Display', serif !important;
font-size: 2.7rem !important;
font-weight: 800 !important;
text-align: center !important;
margin-top: 1.5rem !important;
margin-bottom: 0.8rem !important;
display: block !important;
width: 100% !important;
}
/* Text styling for custom markdown within cards */
.dashboard-card-section p, .output-content-wrapper p {
font-size: 1.15rem; line-height: 1.8;
margin-bottom: 1.2rem;
}
.dashboard-card-section a, .output-content-wrapper a {
text-decoration: none; font-weight: 500;
}
.dashboard-card-section a:hover, .output-content-wrapper a:hover { text-decoration: underline; }
.dashboard-card-section strong, .output-content-wrapper strong { font-weight: 700; }
/* Input layout */
.input-field-group { margin-bottom: 1rem; }
.input-row { display: flex; gap: 1.8rem; flex-wrap: wrap; margin-bottom: 1rem; }
.input-field { flex: 1; }
/* Button layout */
.button-row { display: flex; gap: 2rem; margin-top: 2rem; flex-wrap: wrap; justify-content: flex-end; }
.gradio-button {
border-radius: 12px !important; /* Hardcode radius */
padding: 1.2rem 2.8rem !important; /* Hardcode padding */
font-size: 1.15rem !important; /* Hardcode font size */
font-weight: 600 !important; /* Hardcode font weight */
border: 1px solid transparent !important;
box-shadow: 0 6px 20px rgba(0,0,0,0.35); /* Custom shadow */
transition: all 0.4s cubic-bezier(0.0, 0.0, 0.2, 1);
}
.gradio-button:hover:not(:disabled) { transform: translateY(-6px); box-shadow: 0 12px 28px rgba(0,0,0,0.45) !important; }
.gradio-button:active:not(:disabled) { transform: translateY(-3px); }
.gradio-button:disabled {
box-shadow: none !important;
cursor: not-allowed;
}
.gr-button-secondary { /* Override for secondary button specific look */
background: transparent !important;
border: 2px solid var(--border-color-primary) !important;
box-shadow: none !important;
}
.gr-button-secondary:hover:not(:disabled) {
background: var(--button-secondary-background-hover) !important; /* Use theme variable */
border-color: var(--primary-500) !important; /* Use theme primary color */
}
@media (prefers-color-scheme: light) {
.gradio-button { box-shadow: 0 6px 20px rgba(0,0,0,0.1); }
.gradio-button:hover:not(:disabled) { box-shadow: 0 12px 28px rgba(0,0,0,0.2) !important; }
}
/* Output card and placeholders */
.output-card { padding: 0 !important; margin-top: 0 !important; margin-bottom: 0 !important; }
.output-card .response-header {
font-size: 1.8rem; font-weight: 700;
margin: 0 0 1rem 0; display: flex; align-items: center; gap: 1.2rem;
}
.output-card .response-icon { font-size: 2rem; color: var(--primary-500); } /* Use theme primary color */
.output-card .divider { border: none; border-top: 1px solid var(--border-color-primary); margin: 1.5rem 0 1.8rem 0; }
.output-card .output-content-wrapper { font-size: 1.15rem; line-height: 1.8; }
.output-card .output-content-wrapper p { margin-bottom: 1rem; }
.output-card .output-content-wrapper ul, .output-card .output-content-wrapper ol { margin-left: 2.2rem; margin-bottom: 1.2rem; padding-left: 0; list-style-type: disc; }
.output-card .output-content-wrapper ol { list-style-type: decimal; }
.output-card .output-content-wrapper li { margin-bottom: 0.8rem; }
.output-card .error-message {
padding: 1.5rem 2rem; margin-top: 1.5rem; font-size: 1.1rem;
border-radius: 12px; /* Hardcoded radius */
background: var(--error-background-fill) !important; /* Use theme error background */
color: var(--error-text-color) !important; /* Use theme error text */
border: 2px solid var(--error-border-color) !important; /* Use theme error border */
display: flex; align-items: flex-start; gap: 1.5em;
}
.output-card .error-message .error-icon { font-size: 1.8rem; line-height: 1; padding-top: 0.1em; }
.output-card .error-details { font-size: 0.95rem; margin-top: 0.8rem; opacity: 0.9; word-break: break-word; }
.output-card .placeholder {
padding: 2.5rem 2rem; font-size: 1.2rem; border-radius: 12px; /* Hardcoded radius */
border: 3px dashed var(--border-color-primary);
text-align: center; opacity: 0.8;
}
/* Examples table styling */
.examples-section table.gr-samples-table {
border-radius: 12px !important; /* Hardcoded radius */
border: 1px solid var(--border-color-primary) !important;
overflow: hidden;
box-shadow: inset 0 0 10px rgba(0,0,0,0.2);
}
@media (prefers-color-scheme: light) {
.examples-section table.gr-samples-table { box-shadow: inset 0 0 8px rgba(0,0,0,0.05); }
}
.examples-section table.gr-samples-table th, .examples-section table.gr-samples-table td { padding: 1rem 1.2rem !important; font-size: 1.05rem !important; border: none !important; }
.examples-section table.gr-samples-table th {
background: var(--block-background-fill) !important; /* Using theme background fill for table headers */
font-weight: 600 !important; text-align: left;
}
.examples-section table.gr-samples-table td {
border-top: 1px solid var(--border-color-primary) !important;
cursor: pointer;
}
.examples-section table.gr-samples-table tr:hover td { background: var(--hover-color) !important; } /* Use theme hover color */
.examples-section table.gr-samples-table tr:first-child td { border-top: none !important; }
/* Footer styling */
.app-footer-wrapper {
border-top: 1px solid var(--border-color-primary) !important;
margin-top: 0.5rem; /* Hardcoded margin */
padding-top: 2.5rem; /* Hardcoded padding */
padding-bottom: 2.5rem; /* Hardcoded padding */
border-top-left-radius: 24px; /* Hardcoded radius */
border-top-right-radius: 24px;
box-shadow: inset 0 8px 15px rgba(0,0,0,0.2);
max-width: 1120px;
margin-left: auto;
margin-right: auto;
width: 100%;
display: flex !important;
flex-direction: column !important;
align-items: flex-start !important; /* Left aligns the content */
}
.app-footer {
padding: 0 3.5rem !important; /* Hardcoded padding */
display: flex;
flex-direction: column;
align-items: stretch;
width: 100%;
}
.app-footer p {
font-size: 1.05rem !important;
text-align: left !important;
margin-bottom: 1rem;
}
.app-footer a { font-weight: 500; }
/* Hide default Gradio example labels and related elements for cleaner presentation */
.gr-examples .gr-label, .gr-examples button.gr-button-filter, .gr-examples .label-wrap,
.gr-examples div[data-testid*="label-text"], .gr-examples span[data-testid*="label-text"],
.gr-examples div[class*="label"], .gr-examples .gr-example-label,
.gr-examples .gr-box.gr-component.gradio-example > div:first-child:has(> span[data-testid]),
.gr-examples .gr-box.gr-component.gradio-example > div:first-child > span,
.gr-examples .gr-accordion-header, .gr-examples .gr-accordion-title, .gr-examples .gr-accordion-toggle-icon,
.gr-examples .gr-accordion-header button, .gr-examples .gr-button.gr-button-filter,
.gr-examples .gr-button.gr-button-primary.gr-button-filter,
.gr-examples .gr-examples-header, .gr-examples .gr-examples-header > * {
display: none !important; visibility: hidden !important; width: 0 !important; height: 0 !important;
overflow: hidden !important; margin: 0 !important; padding: 0 !important; border: 0 !important;
font-size: 0 !important; line-height: 0 !important; position: absolute !important;
pointer-events: none !important;
}
/* Responsive Adjustments (remaining hardcoded overrides) */
@media (max-width: 1024px) {
.gradio-container > .flex.flex-col { max-width: 960px; padding: 0 1.5rem !important; }
.app-header-title { font-size: 3.8rem; } .app-header-tagline { font-size: 1.5rem; }
.app-header-wrapper { padding: 2.5rem 3.5rem !important; margin-bottom: 2rem; border-bottom-left-radius: 12px; border-bottom-right-radius: 12px; }
.main-dashboard-container { padding: 2.5rem !important; margin-bottom: 0.6rem; border-radius: 12px; gap: 2rem; }
.dashboard-card-section { padding: 1.8rem; border-radius: 8px; }
.sub-section-title { font-size: 2.0rem !important; margin-bottom: 0.7rem !important; }
.input-row { gap: 1.5rem; } .input-field { min-width: 280px; }
.gradio-textbox textarea { min-height: 160px; } .output-card .response-header { font-size: 1.7rem; }
.examples-section { padding-top: 1.2rem; }
.examples-section table.gr-samples-table th, .examples-section table.gr-samples-table td { padding: 0.9rem 1.1rem !important; }
.app-footer-wrapper { margin-top: 0.6rem; border-top-left-radius: 12px; border-top-right-radius: 12px; }
.app-footer { padding: 0 1.5rem !important; }
}
@media (max-width: 768px) {
.gradio-container > .flex.flex-col { padding: 0 1rem !important; }
.app-header-wrapper { padding: 1.8rem 2.5rem !important; margin-bottom: 1.8rem; border-bottom-left-radius: 12px; border-bottom-right-radius: 12px; }
.app-header-logo { font-size: 4.5rem; margin-bottom: 0.6rem; } .app-header-title { font-size: 3.2rem; letter-spacing: -0.06em; }
.app-header-tagline { font-size: 1.3rem; }
.main-dashboard-container { padding: 1.8rem !important; margin-bottom: 0.5rem; border-radius: 12px; gap: 1.8rem; }
.dashboard-card-section { padding: 1.5rem; border-radius: 8px; }
.sub-section-title { font-size: 1.8rem !important; margin-top: 1rem !important; margin-bottom: 0.6rem !important; }
.input-row { flex-direction: column; gap: 1rem; } .input-field { min-width: 100%; }
.gradio-textbox textarea { min-height: 140px; } .button-row { justify-content: stretch; gap: 1rem; }
.gradio-button { width: 100%; padding: 1.1rem 2rem !important; font-size: 1.1rem !important; }
.output-card .response-header { font-size: 1.5rem; } .output-card .response-icon { font-size: 1.7rem; }
.output-card .placeholder { padding: 2.5rem 1.5rem; font-size: 1.1rem; }
.examples-section { padding-top: 1.2rem; }
.examples-section table.gr-samples-table th, .examples-section table.gr-samples-table td { padding: 0.9rem 1.1rem !important; font-size: 1.0rem !important; }
.app-footer-wrapper { margin-top: 0.6rem; border-top-left-radius: 12px; border-top-right-radius: 12px; padding-top: 2rem; padding-bottom: 2rem; }
.app-footer { padding: 0 1rem !important; }
}
@media (max-width: 480px) {
.gradio-container > .flex.flex-col { padding: 0 0.8rem !important; }
.app-header-wrapper { padding: 1.2rem 1rem !important; margin-bottom: 1.5rem; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; }
.app-header-logo { font-size: 3.8rem; margin-bottom: 0.5rem; } .app-header-title { font-size: 2.8rem; }
.app-header-tagline { font-size: 1.1rem; }
.main-dashboard-container { padding: 1.2rem !important; margin-bottom: 0.4rem; border-radius: 8px; gap: 1.5rem; }
.dashboard-card-section { padding: 1rem; border-radius: 4px; }
.sub-section-title { font-size: 1.5rem !important; margin-top: 0.8rem !important; margin-bottom: 0.5rem !important; }
.gradio-textbox textarea, .gradio-dropdown select, .gradio-textbox input[type=password] { font-size: 1.05rem !important; padding: 1rem 1.2rem !important; }
.gradio-textbox textarea { min-height: 120px; }
.gradio-button { padding: 1rem 1.5rem !important; font-size: 1rem !important; }
.output-card .response-header { font-size: 1.4rem; } .output-card .response-icon { font-size: 1.5rem; }
.output-card .placeholder { padding: 2rem 1rem; font-size: 1.05rem; }
.examples-section { padding-top: 0.8rem; }
.examples-section table.gr-samples-table th, .examples-section table.gr-samples-table td { padding: 0.6rem 0.8rem !important; font-size: 0.95rem !important; }
.app-footer-wrapper { margin-top: 0.4rem; border-top-left-radius: 8px; border-top-right-radius: 8px; padding-top: 1.5rem; padding-bottom: 1.5rem; }
.app-footer { padding: 0 0.8rem !important; }
}
"""
with gr.Blocks(theme="earneleh/paris", css=custom_css, title="Landlord-Tenant Rights Assistant") as demo:
# --- Header Section ---
with gr.Group(elem_classes="app-header-wrapper"):
gr.Markdown(
"""
<div class="app-header">
<span class="app-header-logo">⚖️</span>
<h1 class="app-header-title">Landlord-Tenant Rights Assistant</h1>
<p class="app-header-tagline">Empowering You with State-Specific Legal Insights</p>
</div>
"""
)
# --- Main Dashboard Console Container ---
with gr.Column(elem_classes="main-dashboard-container"):
# --- Section 1: Introduction and Disclaimer Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='sub-section-title'>Welcome & Disclaimer</h3>")
gr.Markdown(
"""
<p>Navigate landlord-tenant laws with ease. This assistant provides detailed, state-specific answers grounded in legal authority.</p>
<p><strong>Disclaimer:</strong> This tool is for informational purposes only and does not constitute legal advice. For specific legal guidance, always consult a licensed attorney in your jurisdiction.</p>
"""
)
# --- Section 2: OpenAI API Key Input Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='sub-section-title'>OpenAI API Key</h3>")
api_key_input = gr.Textbox(
label="OpenAI API Key", # Keep label for theme compatibility
type="password", placeholder="Enter your API key (e.g., sk-...)",
info="Required to process your query. Securely used per request, not stored. <a href='https://platform.openai.com/api-keys' target='_blank'>Get one free from OpenAI</a>.", lines=1,
elem_classes=["input-field-group"]
)
# --- Section 3: Query Input and State Selection Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='sub-section-title'>Ask Your Question</h3>")
with gr.Row(elem_classes="input-row"):
with gr.Column(elem_classes="input-field", scale=3):
query_input = gr.Textbox(
label="Question", placeholder="E.g., What are the rules for security deposit returns in my state?",
lines=5, max_lines=10,
elem_classes=["input-field-group"]
)
with gr.Column(elem_classes="input-field", scale=1):
state_input = gr.Dropdown(
label="Select State", choices=dropdown_choices, value=initial_value,
allow_custom_value=False,
elem_classes=["input-field-group"]
)
with gr.Row(elem_classes="button-row"):
clear_button = gr.Button("Clear", variant="secondary", elem_classes=["gr-button-secondary"])
submit_button = gr.Button("Submit Query", variant="primary", elem_classes=["gr-button-primary"])
# --- Section 4: Output Display Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='sub-section-title'>Legal Assistant's Response</h3>")
output = gr.Markdown(
value="<div class='placeholder output-card'>The answer will appear here after submitting your query.</div>",
elem_classes="output-content-wrapper output-card"
)
# --- Section 5: Example Questions Section ---
with gr.Group(elem_classes="dashboard-card-section examples-section"):
gr.Markdown("<h3 class='sub-section-title'>Example Questions to Ask</h3>")
if example_queries:
gr.Examples(
examples=example_queries, inputs=[query_input, state_input],
examples_per_page=5,
label="" # Hide default Examples label
)
else:
gr.Markdown("<div class='placeholder'>Sample questions could not be loaded.</div>")
# --- Footer Section ---
with gr.Group(elem_classes="app-footer-wrapper"):
gr.Markdown(
"""
<div class="app-footer">
<p>This tool is for informational purposes only and does not constitute legal advice. For legal guidance, always consult with a licensed attorney in your jurisdiction.</p>
<p>Developed by <strong>Nischal Subedi</strong>.
Connect on <a href="https://www.linkedin.com/in/nischal1/" target='_blank'>LinkedIn</a>
or explore insights at <a href="https://datascientistinsights.substack.com/" target='_blank'>Substack</a>.</p>
</div>
"""
)
# --- Event Listeners (Logic remains identical) ---
submit_button.click(
fn=query_interface_wrapper, inputs=[api_key_input, query_input, state_input], outputs=output, api_name="submit_query"
)
clear_button.click(
fn=lambda: (
"",
"",
initial_value,
"<div class='placeholder output-card'>Inputs cleared. Ready for your next question.</div>"
),
inputs=[], outputs=[api_key_input, query_input, state_input, output]
)
logging.info("Gradio interface created with earneleh/paris theme and refined custom CSS.")
return demo
# --- Main Execution Block (remains untouched from original logic) ---
if __name__ == "__main__":
logging.info("Starting Landlord-Tenant Rights Bot application...")
try:
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_PDF_PATH = os.path.join(SCRIPT_DIR, "tenant-landlord.pdf")
DEFAULT_DB_PATH = os.path.join(SCRIPT_DIR, "chroma_db")
PDF_PATH = os.getenv("PDF_PATH", DEFAULT_PDF_PATH)
VECTOR_DB_PATH = os.getenv("VECTOR_DB_PATH", DEFAULT_DB_PATH)
os.makedirs(os.path.dirname(VECTOR_DB_PATH), exist_ok=True)
logging.info(f"Attempting to load PDF from: {PDF_PATH}")
if not os.path.exists(PDF_PATH):
logging.error(f"FATAL: PDF file not found at the specified path: {PDF_PATH}")
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")
exit(1)
if not os.access(PDF_PATH, os.R_OK):
logging.error(f"FATAL: PDF file at '{PDF_PATH}' exists but is not readable. Check file permissions.")
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")
exit(1)
logging.info(f"PDF file '{os.path.basename(PDF_PATH)}' found and is readable.")
vector_db_instance = VectorDatabase(persist_directory=VECTOR_DB_PATH)
rag = RAGSystem(vector_db=vector_db_instance)
# Ensure vector_db.py has process_and_load_pdf and it's called appropriately
# Example: if rag.load_pdf handles it internally based on db content.
# If not, you might need to call vector_db_instance.process_and_load_pdf(PDF_PATH) here
# For now, assuming rag.load_pdf is sufficient as per original structure.
rag.load_pdf(PDF_PATH)
app_interface = rag.gradio_interface()
SERVER_PORT = int(os.getenv("PORT", 7860)) # Use PORT env var if on Spaces/Cloud, else 7860
logging.info(f"Launching Gradio app on http://0.0.0.0:{SERVER_PORT}")
print(f"\n--- Gradio App Running ---\nAccess at: http://localhost:{SERVER_PORT} or your public Spaces URL\n--------------------------\n")
app_interface.launch(server_name="0.0.0.0", server_port=SERVER_PORT, share=False) # share=False is typical for Spaces
except ModuleNotFoundError as e:
if "vector_db" in str(e):
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)
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")
else:
logging.error(f"Application startup failed due to a missing module: {str(e)}", exc_info=True)
print(f"\n--- FATAL STARTUP ERROR - MISSING MODULE ---\n{str(e)}\nPlease ensure all dependencies are installed.\nCheck logs for more details.\n---------------------------\n")
exit(1)
except FileNotFoundError as e:
logging.error(f"Application startup failed due to a missing file: {str(e)}", exc_info=True)
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")
exit(1)
except Exception as e:
logging.error(f"Application startup failed: {str(e)}", exc_info=True)
print(f"\n--- FATAL STARTUP ERROR ---\n{str(e)}\nCheck logs for more details.\n---------------------------\n")
exit(1) |