import os
import logging
from typing import Dict, List, Optional
from functools import lru_cache
import re
import gradio as gr
try:
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 ---
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 CONTEXT ---
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": "
Error: Please select a valid state.
", "context_used": "N/A - Invalid Input"}
if not query or not query.strip():
logging.warning("No query provided.")
return {"answer": "Error: Please enter your question.
", "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": "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.
"
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"" in answer:
formatted_response = f"
{answer}"
else:
formatted_response = 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]
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"],
]
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)
example_queries = [ex for ex in example_queries_base if ex[1] in loaded_states_set]
if not example_queries and available_states_list[0] != "Error: States unavailable": # Ensure first state is not error
example_queries.append(["What basic rights do tenants have?", available_states_list[0]])
elif not example_queries : # Fallback if states list is problematic
example_queries.append(["What basic rights do tenants have?", "California"])
# --- FINAL REFINED "Clarity & Counsel" Theme ---
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
:root {
--font-family-main: 'Poppins', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
/* Light Theme */
--app-bg-light: #F9FAFB; --surface-bg-light: #FFFFFF; --text-primary-light: #1A202C;
--text-secondary-light: #718096; --accent-primary-light: #00796B; --accent-primary-hover-light: #00695C;
--interactive-text-light: #00796B; --interactive-text-hover-light: #005F52; --border-light: #E2E8F0;
--button-secondary-bg-light: #F1F5F9; --button-secondary-text-light: #334155; --button-secondary-hover-bg-light: #E2E8F0;
--shadow-light: 0 5px 15px rgba(0,0,0,0.05); --focus-ring-light: rgba(0, 121, 107, 0.25);
--error-bg-light: #FFF1F2; --error-text-light: #C81E1E; --error-border-light: #FFD0D0;
--success-bg-light: #EFFCF6; --success-text-light: #15803D; --success-border-light: #B3EED1;
/* Dark Theme */
--app-bg-dark: #0F172A; --surface-bg-dark: #1E293B; --text-primary-dark: #F1F5F9;
--text-secondary-dark: #94A3B8; --accent-primary-dark: #2DD4BF; --accent-primary-hover-dark: #14B8A6;
--interactive-text-dark: #5EEAD4; --interactive-text-hover-dark: #99F6E4; --border-dark: #334155;
--button-secondary-bg-dark: #334155; --button-secondary-text-dark: #CBD5E1; --button-secondary-hover-bg-dark: #475569;
--shadow-dark: 0 5px 15px rgba(0,0,0,0.2); --focus-ring-dark: rgba(45, 212, 191, 0.3);
--error-bg-dark: #451515; --error-text-dark: #FFD0D0; --error-border-dark: #9E2D2D;
--success-bg-dark: #073D24; --success-text-dark: #B3EED1; --success-border-dark: #16653D;
--radius-md: 8px; --radius-lg: 12px; --transition: 0.2s ease-in-out;
}
body, .gradio-container { font-family: var(--font-family-main) !important; background: var(--app-bg-light) !important; color: var(--text-primary-light) !important; margin: 0; padding: 0; min-height: 100vh; font-size: 16px; line-height: 1.7; }
* { box-sizing: border-box; }
@media (prefers-color-scheme: dark) { body, .gradio-container { background: var(--app-bg-dark) !important; color: var(--text-primary-dark) !important; } }
.gradio-container > .flex.flex-col { max-width: 820px; margin: 0 auto !important; padding: 0 1.5rem 3rem 1.5rem !important; gap: 0 !important; /* Remove gap, manage spacing with element margins */ }
.content-surface { background: var(--surface-bg-light) !important; border-radius: var(--radius-lg) !important; padding: 3rem !important; box-shadow: var(--shadow-light) !important; border: 1px solid var(--border-light) !important; margin-bottom: 3rem; }
.content-surface:last-child { margin-bottom: 0; } /* No bottom margin for the last surface */
@media (prefers-color-scheme: dark) { .content-surface { background: var(--surface-bg-dark) !important; box-shadow: var(--shadow-dark) !important; border: 1px solid var(--border-dark) !important; } }
.app-header-wrapper { background: var(--accent-primary-light) !important; margin-bottom: 3rem; border-bottom-left-radius: var(--radius-lg); border-bottom-right-radius: var(--radius-lg); box-shadow: var(--shadow-light); }
.app-header { color: #FFFFFF !important; padding: 3.5rem 2rem !important; text-align: center !important; display: flex; flex-direction: column; align-items: center; }
.app-header-logo { font-size: 3rem; margin-bottom: 0.75rem; display: block; text-align: center !important; }
.app-header-title { font-size: 2.25rem; font-weight: 600; margin: 0 0 0.5rem 0; text-align: center !important; }
.app-header-tagline { font-size: 1.1rem; font-weight: 300; opacity: 0.95; text-align: center !important; }
@media (prefers-color-scheme: dark) {
.app-header-wrapper { background: var(--accent-primary-dark) !important; box-shadow: var(--shadow-dark); }
.app-header { color: var(--app-bg-dark) !important; }
}
.section-title, .input-form-card h3, .examples-card .gr-examples-header { font-size: 1.5rem !important; font-weight: 600 !important; color: var(--text-primary-light) !important; margin: 0 auto 2rem auto !important; padding-bottom: 1rem !important; border-bottom: 1px solid var(--border-light) !important; text-align: center !important; width: 100%; }
@media (prefers-color-scheme: dark) { .section-title, .input-form-card h3, .examples-card .gr-examples-header { color: var(--text-primary-dark) !important; border-bottom-color: var(--border-dark) !important; } }
.content-surface p { font-size: 1rem; line-height: 1.75; color: var(--text-secondary-light); margin-bottom: 1rem; }
.content-surface a { color: var(--interactive-text-light); text-decoration: none; font-weight: 500; }
.content-surface a:hover { color: var(--interactive-text-hover-light); text-decoration: underline; }
.content-surface strong { font-weight: 600; color: var(--text-primary-light); }
@media (prefers-color-scheme: dark) { .content-surface p { color: var(--text-secondary-dark); } .content-surface a { color: var(--interactive-text-dark); } .content-surface a:hover { color: var(--interactive-text-hover-dark); } .content-surface strong { color: var(--text-primary-dark); } }
.input-field-group { margin-bottom: 2rem; }
.input-row { display: flex; gap: 1.75rem; flex-wrap: wrap; margin-bottom: 2rem; }
.input-field { flex: 1; min-width: 250px; }
.gradio-input-label { font-size: 0.9rem !important; font-weight: 500 !important; color: var(--text-primary-light) !important; margin-bottom: 0.5rem !important; display: block !important; }
.gradio-input-info { font-size: 0.8rem !important; color: var(--text-secondary-light) !important; margin-top: 0.35rem; }
@media (prefers-color-scheme: dark) { .gradio-input-label { color: var(--text-primary-dark) !important; } .gradio-input-info { color: var(--text-secondary-dark) !important; } }
.gradio-textbox textarea, .gradio-dropdown select, .gradio-textbox input[type=password] { border: 1px solid var(--border-light) !important; border-radius: var(--radius-md) !important; padding: 0.9rem 1.05rem !important; font-size: 1rem !important; background: var(--surface-bg-light) !important; color: var(--text-primary-light) !important; width: 100% !important; box-shadow: none !important; transition: border-color var(--transition), box-shadow var(--transition); }
.gradio-textbox textarea { min-height: 120px; }
.gradio-textbox textarea::placeholder, .gradio-textbox input[type=password]::placeholder { color: #A0AEC0 !important; }
.gradio-textbox textarea:focus, .gradio-dropdown select:focus, .gradio-textbox input[type=password]:focus { border-color: var(--accent-primary-light) !important; box-shadow: 0 0 0 3px var(--focus-ring-light) !important; outline: none !important; }
@media (prefers-color-scheme: dark) { .gradio-textbox textarea, .gradio-dropdown select, .gradio-textbox input[type=password] { border: 1px solid var(--border-dark) !important; background: var(--surface-bg-dark) !important; color: var(--text-primary-dark) !important; } .gradio-textbox textarea::placeholder, .gradio-textbox input[type=password]::placeholder { color: #718096 !important; } .gradio-textbox textarea:focus, .gradio-dropdown select:focus, .gradio-textbox input[type=password]:focus { border-color: var(--accent-primary-dark) !important; box-shadow: 0 0 0 3px var(--focus-ring-dark) !important; } }
.gradio-dropdown select { appearance: none; -webkit-appearance: none; -moz-appearance: none; background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22%236B7280%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M5.293%207.293a1%201%200%20011.414%200L10%2010.586l3.293-3.293a1%201%200%20111.414%201.414l-4%204a1%201%200%2001-1.414%200l-4-4a1%201%200%20010-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E'); background-repeat: no-repeat; background-position: right 1rem center; background-size: 1em; padding-right: 3rem !important; }
@media (prefers-color-scheme: dark) { .gradio-dropdown select { background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22%239CA3AF%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M5.293%207.293a1%201%200%20011.414%200L10%2010.586l3.293-3.293a1%201%200%20111.414%201.414l-4%204a1%201%200%2001-1.414%200l-4-4a1%201%200%20010-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E'); } }
.button-row { display: flex; gap: 1.25rem; margin-top: 2.25rem; flex-wrap: wrap; justify-content: flex-end; }
.gradio-button { border-radius: var(--radius-md) !important; padding: 0.8rem 1.85rem !important; font-size: 1rem !important; font-weight: 500 !important; border: 1px solid transparent !important; box-shadow: var(--shadow-light) !important; }
.gradio-button:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 12px rgba(0,0,0,0.07) !important; }
.gradio-button:active:not(:disabled) { transform: translateY(-1px); }
.gradio-button:disabled { background: #E5E7EB !important; color: #9CA3AF !important; box-shadow: none !important; border-color: #D1D5DB !important; }
.gr-button-primary { background: var(--accent-primary-light) !important; color: #FFFFFF !important; border-color: var(--accent-primary-light) !important; }
.gr-button-primary:hover:not(:disabled) { background: var(--accent-primary-hover-light) !important; border-color: var(--accent-primary-hover-light) !important;}
.gr-button-secondary { background: var(--button-secondary-bg-light) !important; color: var(--button-secondary-text-light) !important; border-color: var(--border-light) !important; }
.gr-button-secondary:hover:not(:disabled) { background: var(--button-secondary-hover-bg-light) !important; border-color: #CBD5E0 !important; }
@media (prefers-color-scheme: dark) { .gradio-button { box-shadow: var(--shadow-dark) !important; } .gradio-button:hover:not(:disabled) { box-shadow: 0 6px 12px rgba(0,0,0,0.25) !important; } .gradio-button:disabled { background: #334155 !important; color: #6B7280 !important; border-color: #475569 !important;} .gr-button-primary { background: var(--accent-primary-dark) !important; color: var(--app-bg-dark) !important; border-color: var(--accent-primary-dark) !important; } .gr-button-primary:hover:not(:disabled) { background: var(--accent-primary-hover-dark) !important; border-color: var(--accent-primary-hover-dark) !important; } .gr-button-secondary { background: var(--button-secondary-bg-dark) !important; color: var(--button-secondary-text-dark) !important; border-color: var(--border-dark) !important; } .gr-button-secondary:hover:not(:disabled) { background: var(--button-secondary-hover-bg-dark) !important; border-color: #475569 !important; } }
.output-card .response-header { font-size: 1.3rem; font-weight: 600; color: var(--text-primary-light); margin: 0 0 1rem 0; display: flex; align-items: center; gap: 0.6rem; }
.output-card .response-icon { font-size: 1.4rem; color: var(--text-secondary-light); }
.output-card .divider { border: none; border-top: 1px solid var(--border-light); margin: 1.5rem 0; }
.output-card .output-content-wrapper { font-size: 1rem; line-height: 1.75; color: var(--text-primary-light); }
.output-card .output-content-wrapper p { margin-bottom: 1rem; } .output-card .output-content-wrapper ul, .output-card .output-content-wrapper ol { margin-left: 1.5rem; margin-bottom: 1rem; padding-left: 1rem; } .output-card .output-content-wrapper li { margin-bottom: 0.5rem; }
@media (prefers-color-scheme: dark) { .output-card .response-header { color: var(--text-primary-dark); } .output-card .response-icon { color: var(--text-secondary-dark); } .output-card .divider { border-top: 1px solid var(--border-dark); } .output-card .output-content-wrapper { color: var(--text-primary-dark); } }
.output-card .error-message, .output-card .success-message { padding: 1rem 1.25rem; margin-top: 1.25rem; font-size: 0.95rem; border-radius: var(--radius-md);}
.output-card .error-message .error-icon { font-size: 1.2rem; } .output-card .error-details { font-size: 0.85rem; }
.output-card .placeholder { padding: 3rem 1.5rem; font-size: 1.1rem; border-radius: var(--radius-lg); border: 2px dashed var(--border-light); }
@media (prefers-color-scheme: dark) { .output-card .placeholder { border-color: var(--border-dark); } }
.examples-card .gr-examples-table { border-radius: var(--radius-lg) !important; border: 1px solid var(--border-light) !important; }
.examples-card .gr-examples-table th, .examples-card .gr-examples-table td { padding: 0.9rem 1.1rem !important; font-size: 0.95rem !important; }
.examples-card .gr-examples-table th { background: #F9FAFB !important; }
@media (prefers-color-scheme: dark) { .examples-card .gr-examples-table { border: 1px solid var(--border-dark) !important;} .examples-card .gr-examples-table th { background: #0F172A !important; } }
.app-footer-wrapper { border-top: 1px solid var(--border-light) !important; margin-top: 3rem; }
.app-footer { padding: 3rem 1.5rem !important; text-align: center !important; display: flex; flex-direction: column; align-items: center; }
.app-footer p { font-size: 0.9rem !important; color: var(--text-secondary-light) !important; margin-bottom: 0.75rem; text-align: center !important; max-width: 600px; /* Constrain footer text width */ }
.app-footer a { color: var(--interactive-text-light) !important; font-weight: 500; }
.app-footer a:hover { color: var(--interactive-text-hover-light) !important; text-decoration: underline; }
@media (prefers-color-scheme: dark) { .app-footer-wrapper { border-top-color: var(--border-dark) !important; } .app-footer p { color: var(--text-secondary-dark) !important; } .app-footer a { color: var(--interactive-text-dark) !important; } .app-footer a:hover { color: var(--interactive-text-hover-dark) !important; } }
:focus-visible { outline: 2px solid var(--accent-primary-light) !important; outline-offset: 2px; box-shadow: 0 0 0 3px var(--focus-ring-light) !important; }
@media (prefers-color-scheme: dark) { :focus-visible { outline-color: var(--accent-primary-dark) !important; box-shadow: 0 0 0 3px var(--focus-ring-dark) !important; } }
.gradio-button span:focus { outline: none !important; }
@media (max-width: 768px) { body { font-size: 15px; } .gradio-container > .flex.flex-col { padding: 0 1rem 2.5rem 1rem !important; } .content-surface { padding: 2.25rem !important; margin-bottom: 2.5rem; } .app-header-wrapper { margin-bottom: 2.5rem; } .app-header { padding: 2.75rem 1.25rem !important; } .app-header-logo { font-size: 2.6rem; } .app-header-title { font-size: 2rem; } .app-header-tagline { font-size: 1.05rem; } .input-row { flex-direction: column; gap: 1.5rem; } .input-field { min-width: 100%; } .button-row { justify-content: stretch; } .gradio-button { width: 100%; } .section-title, .input-form-card h3, .examples-card .gr-examples-header { font-size: 1.35rem !important; } .app-footer-wrapper { margin-top: 2.5rem; } .app-footer { padding: 2.5rem 1rem !important; } }
@media (max-width: 480px) { .gradio-container > .flex.flex-col { padding: 0 0.75rem 2rem 0.75rem !important; } .content-surface { padding: 1.75rem !important; margin-bottom: 2rem; border-radius: var(--radius-md) !important; } .app-header-wrapper { margin-bottom: 2rem; border-bottom-left-radius: var(--radius-md); border-bottom-right-radius: var(--radius-md); } .app-header { padding: 2.25rem 1rem !important; } .app-header-logo { font-size: 2.2rem; } .app-header-title { font-size: 1.7rem; } .app-header-tagline { font-size: 0.95rem; } .section-title, .input-form-card h3, .examples-card .gr-examples-header { font-size: 1.25rem !important; margin-bottom: 1.75rem !important; padding-bottom: 0.85rem !important; } .gradio-textbox textarea, .gradio-dropdown select, .gradio-textbox input[type=password] { font-size: 0.95rem !important; padding: 0.85rem 1rem !important; } .gradio-button { padding: 0.85rem 1.5rem !important; font-size: 0.95rem !important; } .examples-card .gr-examples-table th, .examples-card .gr-examples-table td { padding: 0.75rem 0.9rem !important; font-size: 0.9rem !important; } .app-footer-wrapper { margin-top: 2rem; } .app-footer { padding: 2rem 0.75rem !important; } }
.gradio-container > .flex { gap: 0 !important; } /* Main gap removed, managed by surface margins */
.gradio-markdown > *:first-child { margin-top: 0; } .gradio-markdown > *:last-child { margin-bottom: 0; }
.gradio-dropdown, .gradio-textbox { border: none !important; padding: 0 !important; background: transparent !important; }
"""
with gr.Blocks(theme=None, css=custom_css, title="Landlord-Tenant Rights Assistant") as demo:
# --- Header Section ---
# We'll wrap the Markdown in a gr.Group to apply wrapper styles if needed
with gr.Group(elem_classes="app-header-wrapper"):
gr.Markdown(
"""
"""
)
# --- Main Content Sections ---
with gr.Group(elem_classes="content-surface"):
gr.Markdown("
Know Your Rights
")
gr.Markdown(
"""
Navigate landlord-tenant laws with ease. Enter your OpenAI API key, select your state, and ask your question to get detailed, state-specific answers.
Don't have an API key? Get one free from OpenAI.
Disclaimer: This tool provides information only, not legal advice. For legal guidance, consult a licensed attorney.
"""
)
with gr.Group(elem_classes="content-surface input-form-card"):
gr.Markdown("
Ask Your Question
")
with gr.Column(elem_classes="input-field-group"):
api_key_input = gr.Textbox(
label="OpenAI API Key", type="password", placeholder="Enter your API key (e.g., sk-...)",
info="Required to process your query. Securely used per request, not stored.", lines=1
)
with gr.Row(elem_classes="input-row"):
with gr.Column(elem_classes="input-field", min_width="58%"):
query_input = gr.Textbox(
label="Your Question", placeholder="E.g., What are the rules for security deposit returns in my state?",
lines=5, max_lines=10
)
with gr.Column(elem_classes="input-field", min_width="38%"):
state_input = gr.Dropdown(
label="Select State", choices=dropdown_choices, value=initial_value,
allow_custom_value=False
)
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"])
with gr.Group(elem_classes="content-surface output-card"):
output = gr.Markdown(
value="
Your answer will appear here after submitting your query.
",
elem_classes="output-content-wrapper"
)
if example_queries:
with gr.Group(elem_classes="content-surface examples-card"):
gr.Examples(
examples=example_queries, inputs=[query_input, state_input],
label="Explore Sample Questions", examples_per_page=5
)
else:
with gr.Group(elem_classes="content-surface"):
gr.Markdown("
Sample questions could not be loaded.
")
# --- Footer Section ---
with gr.Group(elem_classes="app-footer-wrapper"):
gr.Markdown(
"""
"""
)
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, "
Inputs cleared. Ready for your next question.
"),
inputs=[], outputs=[api_key_input, query_input, state_input, output]
)
logging.info("Final refined Clarity & Counsel theme Gradio interface created.")
return demo
# --- Main Execution Block (remains the same) ---
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)
os.makedirs(os.path.dirname(PDF_PATH), exist_ok=True)
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)
vector_db_instance = VectorDatabase(persist_directory=VECTOR_DB_PATH)
rag = RAGSystem(vector_db=vector_db_instance)
rag.load_pdf(PDF_PATH)
app_interface = rag.gradio_interface()
SERVER_PORT = 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}\n--------------------------\n")
app_interface.launch(server_name="0.0.0.0", server_port=SERVER_PORT, share=True)
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 details.\n---------------------------\n")
exit(1)