Nischal Subedi
updated UI v5
ff69f36
raw
history blame
54.9 kB
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
# --- NEW: Custom Gradio Theme Definition (Legal Aesthetic) ---
class LegalAestheticTheme(themes.Base):
def __init__(
self,
**kwargs,
):
# Pass all accepted kwargs to the base class
super().__init__(
# Fonts are accepted directly by themes.Base
font=[themes.GoogleFont("Inter"), "sans-serif"],
font_mono=themes.GoogleFont("JetBrains Mono"),
# --- Dark Mode Colors (Legal Noir) ---
# Primary/Accent Colors (Goldenrod/Amber scale)
primary_50_dark="#FFFDE7",
primary_100_dark="#FFF9C4",
primary_200_dark="#FFF59D",
primary_300_dark="#FFF176",
primary_400_dark="#FFEE58",
primary_500_dark="#FFC107", # Main accent color
primary_600_dark="#E0A800", # Hover accent color
primary_700_dark="#B88A00",
primary_800_dark="#8D6C00",
primary_900_dark="#614B00",
primary_950_dark="#403200",
# Backgrounds
background_page_dark="#0F0F1A",
block_background_fill_dark="#1A1A2B",
background_fill_primary_dark="#1E1E30",
background_fill_secondary_dark="#2A2A40",
background_fill_tertiary_dark="#3F3F5A",
# Text Colors
text_color_body_dark="#EAEAF0",
text_color_subdued_dark="#A0A0B0",
text_color_header_dark="#EAEAF0",
# Borders
border_color_primary_dark="#3F3F5A",
border_color_secondary_dark="#505060",
# Shadows (as hex colors for theme consistency, will be applied as rgba in CSS)
# These are colors, not directly applied as 'shadow-lg' etc. by theme.Base
# They will be used via CSS variables
shadow_lg_dark="0F0F1A", # Represents darkest shadow color for rgba(..., 0.6)
shadow_md_dark="1A1A2B", # Represents medium shadow color for rgba(..., 0.4)
shadow_sm_dark="1E1E30", # Represents light shadow color for rgba(..., 0.35)
# Links
link_text_color_dark="#FFC107",
link_text_color_hover_dark="#E0A800",
# Buttons (theme handles primary colors, custom CSS for secondary)
button_primary_background_dark="#FFC107",
button_primary_background_hover_dark="#E0A800",
button_primary_text_color_dark="#1A1A2B",
# Error Colors
color_error_50_dark="#4D001A",
color_error_200_dark="#990026",
color_error_500_dark="#CC0033",
color_error_600_dark="#FFB3C2",
# --- Light Mode Colors (Legal Lumen) ---
primary_50_light="#E3F2FD",
primary_100_light="#BBDEFB",
primary_200_light="#90CAF9",
primary_300_light="#64B5F6",
primary_400_light="#42A5F5",
primary_500_light="#2196F3",
primary_600_light="#1E88E5",
primary_700_light="#1976D2",
primary_800_light="#1565C0",
primary_900_light="#0D47A1",
primary_950_light="#082F6A",
background_page_light="#F0F2F5",
block_background_fill_light="#E0E4EB",
background_fill_primary_light="#FFFFFF",
background_fill_secondary_light="#F8F9FA",
background_fill_tertiary_light="#DDE2E8",
text_color_body_light="#212529",
text_color_subdued_light="#6C757D",
text_color_header_light="#212529",
border_color_primary_light="#DDE2E8",
border_color_secondary_light="#CCD1D7",
shadow_lg_light="F0F2F5",
shadow_md_light="E0E4EB",
shadow_sm_light="FFFFFF",
link_text_color_light="#007bff",
link_text_color_hover_light="#0056b3",
button_primary_background_light="#007bff",
button_primary_background_hover_light="#0056b3",
button_primary_text_color_light="#FFFFFF",
color_error_50_light="#F8D7DA",
color_error_200_light="#F5C6CB",
color_error_500_light="#DC3545",
color_error_600_light="#721C24",
# Radii and Spacing (matching custom CSS, and setting theme defaults)
radius_xs="4px",
radius_sm="8px",
radius_md="12px",
radius_lg="24px",
spacing_md="2.5rem",
spacing_lg="3.5rem",
spacing_xl="4.5rem",
**kwargs,
)
# Assign heading_font directly to self after super().__init__ as it's not a direct base constructor argument
self.heading_font = [themes.GoogleFont("Playfair Display"), "serif"]
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'>Error: Please select a valid state.</div>" # Simplified message
if not query or not query.strip():
return "<div class='error-message'>Error: Please enter your question.</div>" # Simplified message
# 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
# Use a div for the icon and header text for better control over alignment and spacing
formatted_response = f"<div class='response-header-container'><span class='response-icon'>📜</span><h4 class='response-title'>Response for {state}</h4></div><hr class='response-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 and specific aesthetics ---
# This CSS is designed to complement our custom LegalAestheticTheme.
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');
/* Keyframe animation for initial header load */
@keyframes fadeInSlideDown { from { opacity: 0; transform: translateY(-40px); } to { opacity: 1; transform: translateY(0); } }
/* General Gradio container layout and centering */
body { margin: 0; padding: 0; } /* Reset default body margin */
.gradio-container {
font-family: var(--font-text) !important; /* Use theme's text font variable */
min-height: 100vh;
display: flex;
justify-content: center; /* Center content horizontally */
align-items: flex-start; /* Align content to top vertically */
padding: var(--spacing-lg) 1rem; /* Overall padding top/bottom, fixed horizontal for small screens */
background-color: var(--background-page); /* Use theme's page background */
transition: background-color 0.4s ease-in-out, color 0.4s ease-in-out; /* Smooth theme transition */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.gradio-container > .flex.flex-col {
max-width: 1120px; /* Constrain max width for desktop */
width: 100%;
margin: 0 auto; /* Center the main content column */
gap: var(--spacing-md) !important; /* Consistent spacing between main sections */
padding: 0 !important; /* Remove default Gradio column padding */
}
/* Header specific styling (outside main dashboard for distinct look) */
.app-header-wrapper {
background-color: var(--block-background-fill); /* Use theme's block background */
padding: var(--spacing-xl) var(--spacing-lg); /* Spacious padding */
text-align: center;
border-radius: var(--radius-lg); /* Use theme radius */
box-shadow: 0 1.2rem 3.5rem rgba(var(--shadow-lg),0.6); /* Use theme shadow color with rgba */
position: relative;
overflow: hidden;
z-index: 10;
border: 1px solid var(--border-color-primary); /* Use theme border */
}
.app-header { display: flex; flex-direction: column; align-items: center; }
.app-header-logo {
font-size: 5.5rem; margin-bottom: 0.8rem; line-height: 1;
color: var(--primary-500); /* Use theme primary color */
filter: drop-shadow(0 0 15px var(--primary-500));
transform: translateY(-40px); opacity: 0;
animation: fadeInSlideDown 1.5s ease-out forwards; animation-delay: 0.3s;
}
.app-header-title {
font-family: var(--font-heading) !important; /* Use theme's heading font variable */
font-size: 4.2rem; font-weight: 900;
margin: 0 0 0.8rem 0; letter-spacing: -0.07em;
color: var(--text-color-header); /* Use theme text color for headings */
text-shadow: 0 8px 16px rgba(0,0,0,0.5); /* Custom shadow for effect */
transform: translateY(-40px); opacity: 0;
animation: fadeInSlideDown 1.5s ease-out forwards; animation-delay: 0.6s;
}
.app-header-tagline {
font-family: var(--font-text) !important;
font-size: 1.6rem; font-weight: 300;
color: var(--text-color-subdued); /* Use theme subdued text color */
opacity: 0.9; max-width: 900px;
transform: translateY(-40px); opacity: 0;
animation: fadeInSlideDown 1.5s ease-out forwards; animation-delay: 0.9s;
}
/* Main dashboard console container */
.main-dashboard-container {
display: flex;
flex-direction: column;
gap: 2rem; /* Spacing between cards */
background-color: var(--background-fill-primary); /* Use theme's main background */
border-radius: var(--radius-lg);
box-shadow: 0 0.8rem 2.5rem rgba(var(--shadow-lg),0.4); /* Use theme shadow color with rgba */
padding: var(--spacing-md); /* Inner padding for the whole dashboard content */
border: 1px solid var(--border-color-primary);
}
/* Individual Card Sections */
.dashboard-card-section {
background-color: var(--background-fill-secondary); /* A slightly darker/lighter background for cards */
border-radius: var(--radius-md);
padding: 2rem; /* Padding inside each card */
box-shadow: 0 0.6rem 2rem rgba(var(--shadow-md),0.2); /* Subtle shadow for cards */
border: 1px solid var(--border-color-primary);
}
/* Section titles within cards */
.card-section-title {
font-family: var(--font-heading) !important; /* Use theme's heading font variable */
font-size: 2.2rem !important;
font-weight: 800 !important;
color: var(--text-color-body) !important; /* Use theme body text color */
text-align: center !important; /* Centered as requested */
margin-bottom: 1.5rem !important;
padding-bottom: 0.8rem !important;
border-bottom: 1px solid var(--border-color-primary) !important;
}
/* General text styling within cards */
.dashboard-card-section p {
font-family: var(--font-text) !important;
font-size: 1.1rem;
line-height: 1.6;
color: var(--text-color-body);
margin-bottom: 1rem;
}
.dashboard-card-section strong {
color: var(--text-color-body); /* Ensure strong text is legible */
font-weight: 600;
}
.dashboard-card-section a {
color: var(--link-text-color); /* Use theme link color */
text-decoration: underline;
}
.dashboard-card-section a:hover {
color: var(--link-text-color-hover); /* Use theme link hover color */
text-decoration: none;
}
/* Input field styling (mostly handled by theme, but override specific padding/radius) */
.gradio-textbox textarea, .gradio-dropdown select, .gradio-textbox input[type=password] {
padding: 1.2rem 1.4rem !important; /* Adjust padding for consistency */
border-radius: var(--radius-sm) !important; /* Use theme radius */
font-size: 1.05rem !important;
}
.gradio-textbox textarea { min-height: 160px; }
.gradio-input-info a {
color: var(--link-text-color); /* Ensure info links are themed */
text-decoration: underline;
}
.gradio-input-info a:hover {
color: var(--link-text-color-hover);
}
/* Style for the dropdown arrow, ensuring it's visible in both themes */
.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%22currentColor%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') !important;
background-repeat: no-repeat;
background-position: right 1rem center !important;
background-size: 1.2em !important;
padding-right: 3rem !important;
color: var(--text-color-body) !important; /* Ensure dropdown text is legible */
}
/* Current color for SVG icon will adapt with text_color_body, but explicitly set if needed */
/* For light mode, the fill for SVG should be a darker color */
@media (prefers-color-scheme: light) {
.gradio-dropdown select {
color: var(--text-color-body) !important; /* Ensure dropdown text is dark */
}
}
/* Button styling overrides to match original design intent with theme */
.gradio-button {
border-radius: var(--radius-sm) !important;
font-weight: 600 !important;
padding: 0.8rem 2rem !important; /* Make buttons slightly less tall */
min-height: 48px; /* Ensure minimum height */
box-shadow: 0 6px 20px rgba(var(--shadow-sm),0.35); /* Use theme shadow color with rgba */
transition: all 0.2s ease-in-out;
transform: translateY(0);
}
.gradio-button:hover:not(:disabled) {
transform: translateY(-3px); /* Subtle lift on hover */
box-shadow: 0 0.8rem 2.5rem rgba(var(--shadow-md),0.4);
}
.gradio-button:active:not(:disabled) {
transform: translateY(0);
}
/* Primary button uses theme primary colors automatically */
.gr-button-secondary {
background-color: transparent !important;
border: 1px solid var(--border-color-primary) !important;
color: var(--text-color-body) !important; /* Use theme body text for secondary button */
box-shadow: none !important;
}
.gr-button-secondary:hover:not(:disabled) {
background-color: var(--primary-50) !important; /* Light tint of primary on hover */
color: var(--primary-500) !important; /* Primary color for text on hover */
border-color: var(--primary-500) !important; /* Primary color for border on hover */
}
/* Output Response Section */
.response-header-container {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1rem;
}
.response-icon {
font-size: 2.2rem;
color: var(--primary-500); /* Use theme primary color */
}
.response-title {
font-family: var(--font-heading) !important;
font-size: 1.8rem !important;
font-weight: 700 !important;
color: var(--text-color-body) !important; /* Ensure heading is legible */
margin: 0;
padding: 0;
}
.output-content-wrapper .response-divider { /* Specific class for this divider */
border: none;
border-top: 1px solid var(--border-color-secondary); /* A lighter border for divider */
margin: 1rem 0 1.5rem 0;
}
.output-content-wrapper {
font-family: var(--font-text) !important;
line-height: 1.7;
font-size: 1.05rem;
color: var(--text-color-body);
}
.output-content-wrapper ul, .output-content-wrapper ol {
margin-left: 2rem;
margin-bottom: 1rem;
padding-left: 0;
}
.output-content-wrapper li {
margin-bottom: 0.5rem;
}
.output-card .placeholder {
padding: 2rem;
font-size: 1.1rem;
border-radius: var(--radius-md);
border: 2px dashed var(--border-color-secondary);
color: var(--text-color-subdued);
text-align: center;
opacity: 0.7;
min-height: 150px; /* Ensure some height for placeholder */
display: flex;
align-items: center;
justify-content: center;
}
.output-card .error-message {
padding: 1.5rem;
font-size: 1.05rem;
border-radius: var(--radius-sm);
background-color: var(--color-error-50); /* Use theme error color with low opacity */
color: var(--color-error-600); /* Strong error text color */
border: 1px solid var(--color-error-200); /* Theme error border */
display: flex;
align-items: flex-start;
gap: 1rem;
}
.output-card .error-message .error-icon {
font-size: 1.8rem;
line-height: 1;
color: var(--color-error-500); /* Use theme error color */
}
.output-card .error-details {
font-size: 0.9rem;
margin-top: 0.5rem;
opacity: 0.8;
word-break: break-word;
}
/* Examples Table (from gr.Examples) */
.examples-section table.gr-samples-table {
border-radius: var(--radius-sm) !important;
border: 1px solid var(--border-color-primary) !important;
overflow: hidden;
background-color: var(--background-fill-secondary); /* Match card background */
}
.examples-section table.gr-samples-table th, .examples-section table.gr-samples-table td {
padding: 0.8rem 1rem !important;
font-size: 0.95rem !important;
border: none !important;
color: var(--text-color-body) !important;
}
.examples-section table.gr-samples-table th {
background-color: var(--background-fill-tertiary) !important; /* Slightly different background for header */
font-weight: 600 !important;
text-align: left;
color: var(--text-color-header) !important;
}
.examples-section table.gr-samples-table td {
border-top: 1px solid var(--border-color-secondary) !important; /* Lighter border for rows */
cursor: pointer;
}
.examples-section table.gr-samples-table tr:hover td {
background-color: var(--primary-50) !important; /* Light tint on hover */
}
.examples-section table.gr-samples-table tr:first-child td { border-top: none !important; }
/* Footer styling (at the very bottom of the page) */
.app-footer-wrapper {
background-color: var(--block-background-fill); /* Use theme's block background */
border-top: 1px solid var(--border-color-primary) !important;
padding: 1.5rem 2.5rem; /* Consistent padding */
border-radius: var(--radius-lg);
box-shadow: 0 1.2rem 3.5rem rgba(var(--shadow-lg),0.6); /* Use theme shadow color with rgba */
width: 100%;
max-width: 1120px;
margin: var(--spacing-md) auto 0 auto; /* Spacing from main dashboard */
display: flex;
flex-direction: column;
align-items: flex-start; /* Left aligns the content */
}
.app-footer {
width: 100%; /* Ensure content takes full width */
}
.app-footer p {
font-family: var(--font-text) !important;
font-size: 0.95rem !important;
color: var(--text-color-subdued) !important;
margin-bottom: 0.5rem;
text-align: left !important;
}
.app-footer a {
color: var(--link-text-color) !important;
font-weight: 500;
text-decoration: underline;
}
.app-footer a:hover {
color: var(--link-text-color-hover) !important;
text-decoration: none;
}
/* Hide unwanted Gradio default elements for a clean look */
.gr-messages-row, .gr-share-btn, .gr-api-btn, .gr-view-api, /* Common boilerplate elements */
.gradio-container > footer, /* Default Gradio footer text that appears below blocks */
.gradio-app .version-info, /* Gradio version info */
.gradio-app .dark\:text-gray-400, /* Target other default footer text classes */
.gradio-app .absolute.bottom-0.right-0.px-2.py-1.text-gray-400.text-xs /* another common footer class */ {
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;
}
/* More specific example label/button hiding */
.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;
}
/* Further clean up any potential residual margin/padding Gradio adds to its components */
.gradio-container .gr-box { margin: 0 !important; padding: 0 !important; }
.gradio-container .gr-form { gap: 0 !important; } /* Remove gaps in forms where not desired */
/* Responsive Adjustments (using hardcoded values for precision, but mapping to theme variables where applicable for color/font) */
@media (max-width: 1024px) {
.gradio-container { padding: 2rem 0.8rem; }
.gradio-container > .flex.flex-col { gap: 2rem !important; }
.app-header-wrapper { padding: 2.5rem 1.8rem; margin-bottom: 2rem; border-radius: 12px; }
.app-header-title { font-size: 3.5rem; } .app-header-tagline { font-size: 1.4rem; }
.main-dashboard-container { padding: 2rem; gap: 1.8rem; border-radius: 12px; }
.dashboard-card-section { padding: 1.5rem; border-radius: 8px; }
.card-section-title { font-size: 1.8rem !important; margin-bottom: 1.2rem !important; }
.input-row { flex-direction: column; gap: 1rem; }
.gradio-textbox textarea { min-height: 140px; }
.button-row { justify-content: center; gap: 1rem; flex-direction: column; }
.gradio-button { width: 100%; max-width: 300px; margin: 0 auto; } /* Center buttons on smaller screens */
.response-header-container { gap: 0.8rem; } .response-icon { font-size: 2rem; } .response-title { font-size: 1.6rem !important; }
.output-card .placeholder { padding: 1.5rem; font-size: 1rem; min-height: 120px;}
.examples-section table.gr-samples-table th, .examples-section table.gr-samples-table td { padding: 0.7rem 0.9rem !important; font-size: 0.9rem !important; }
.app-footer-wrapper { padding: 1.2rem 1.8rem; margin-top: 1.5rem; border-radius: 12px; }
.app-footer p { font-size: 0.85rem !important; }
}
@media (max-width: 768px) {
.gradio-container { padding: 1.5rem 0.5rem; }
.gradio-container > .flex.flex-col { gap: 1.8rem !important; }
.app-header-wrapper { padding: 2rem 1rem; margin-bottom: 1.5rem; border-radius: 12px; }
.app-header-logo { font-size: 4.5rem; } .app-header-title { font-size: 2.8rem; } .app-header-tagline { font-size: 1.2rem; }
.main-dashboard-container { padding: 1.5rem; gap: 1.5rem; border-radius: 12px; }
.dashboard-card-section { padding: 1.2rem; border-radius: 8px; }
.card-section-title { font-size: 1.6rem !important; margin-bottom: 1rem !important; }
.gradio-textbox textarea { min-height: 120px; }
.output-content-wrapper { font-size: 1rem; }
.output-card .error-message { padding: 1rem; }
.app-footer-wrapper { padding: 1rem 1rem; margin-top: 1rem; border-radius: 12px; }
}
@media (max-width: 480px) {
.app-header-logo { font-size: 3.5rem; } .app-header-title { font-size: 2.2rem; } .app-header-tagline { font-size: 1rem; }
.gradio-textbox textarea { min-height: 100px; }
.gradio-button { padding: 0.6rem 1.5rem !important; min-height: 40px; font-size: 0.95rem !important; }
.response-icon { font-size: 1.8rem; } .response-title { font-size: 1.4rem !important; }
.examples-section table.gr-samples-table th, .examples-section table.gr-samples-table td { padding: 0.5rem 0.7rem !important; font-size: 0.85rem !important; }
}
"""
with gr.Blocks(theme=self.LegalAestheticTheme(), css=custom_css, title="Landlord-Tenant Rights Assistant") as demo:
# --- Header Section (distinct, top-level block) ---
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 (centralized, card-based) ---
with gr.Column(elem_classes="main-dashboard-container"):
# --- Section 1: Welcome & Disclaimer Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='card-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>
""",
elem_classes="dashboard-card-content" # Apply general text styling
)
# --- Section 2: OpenAI API Key Input Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='card-section-title'>OpenAI API Key</h3>") # Centered by CSS
api_key_input = gr.Textbox(
label="OpenAI API Key", # Keep label for theme compatibility and accessibility
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: Ask Your Question Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='card-section-title'>Ask Your Question</h3>") # Centered by CSS
with gr.Row():
with gr.Column(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
)
with gr.Column(scale=1, min_width=200):
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"])
# --- Section 4: Legal Assistant's Response Card ---
with gr.Group(elem_classes="dashboard-card-section"):
gr.Markdown("<h3 class='card-section-title'>Legal Assistant's Response</h3>") # Centered by CSS
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 Card ---
with gr.Group(elem_classes="dashboard-card-section examples-section"):
gr.Markdown("<h3 class='card-section-title'>Example Questions to Ask</h3>") # Centered by CSS
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 (distinct, bottom-level block) ---
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>
""",
elem_classes="footer-content" # Apply general text styling to footer markdown
)
# --- 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 custom LegalAestheticTheme and refined CSS for optimal layout, legibility, and Hugging Face compatibility.")
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)