File size: 41,191 Bytes
b9756ef
 
bfee845
b9756ef
bfee845
 
ea0c3e1
0634f1a
 
 
 
 
 
 
 
 
 
 
 
 
b9756ef
 
ea0c3e1
0634f1a
 
 
 
 
 
 
7c7cb71
 
 
 
ea0c3e1
0634f1a
b9756ef
 
 
 
 
 
bfee845
b9756ef
0634f1a
 
 
 
 
 
 
 
b9756ef
 
7c7cb71
b9756ef
 
bfee845
b9756ef
bfee845
b9756ef
bfee845
 
 
b9756ef
bfee845
ea0c3e1
7c7cb71
0634f1a
bfee845
7c7cb71
 
0634f1a
 
bfee845
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
 
 
 
bfee845
0634f1a
bfee845
b9756ef
bfee845
0634f1a
 
bfee845
0634f1a
 
bfee845
0634f1a
 
 
 
 
 
 
 
 
 
 
 
 
 
bfee845
0634f1a
 
7c7cb71
b9756ef
 
 
bfee845
0634f1a
 
 
 
 
b9756ef
0634f1a
 
ea0c3e1
b9756ef
bfee845
0634f1a
 
b9756ef
0634f1a
 
 
 
 
 
 
 
 
 
bfee845
0634f1a
 
 
b9756ef
bfee845
0634f1a
bfee845
0634f1a
7c7cb71
0634f1a
56f099b
0634f1a
d55a911
0634f1a
d55a911
0634f1a
d55a911
56f099b
bfee845
d55a911
0634f1a
d55a911
0634f1a
d55a911
bfee845
 
0634f1a
 
d55a911
 
56f099b
0634f1a
 
 
 
 
 
 
b9756ef
0634f1a
56f099b
0634f1a
 
56f099b
d55a911
56f099b
d55a911
0634f1a
d55a911
56f099b
4c5479b
d55a911
 
 
 
56f099b
 
 
 
 
 
d55a911
 
56f099b
 
 
 
 
 
d55a911
 
 
56f099b
d55a911
0634f1a
56f099b
d55a911
56f099b
d55a911
56f099b
d55a911
56f099b
 
 
d55a911
56f099b
 
 
 
 
d55a911
56f099b
 
d55a911
 
56f099b
 
d55a911
56f099b
d55a911
 
 
56f099b
d55a911
 
56f099b
 
d55a911
56f099b
 
 
d55a911
56f099b
 
 
 
 
 
 
d55a911
 
56f099b
 
d55a911
56f099b
 
d55a911
56f099b
d55a911
56f099b
d55a911
56f099b
 
d55a911
56f099b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d55a911
 
56f099b
0634f1a
 
56f099b
 
d55a911
56f099b
d55a911
 
4c5479b
 
d55a911
56f099b
 
 
 
 
 
 
 
 
 
 
 
7c7cb71
56f099b
d55a911
 
0634f1a
 
d55a911
 
 
0634f1a
7c7cb71
 
d55a911
 
0634f1a
d55a911
 
 
 
0634f1a
56f099b
d55a911
 
56f099b
d55a911
56f099b
0634f1a
 
d55a911
 
0634f1a
d55a911
 
0634f1a
56f099b
d55a911
 
 
 
0634f1a
 
d55a911
 
 
 
0634f1a
d55a911
 
 
 
56f099b
 
 
 
 
 
 
 
 
 
 
 
229d1b2
7c7cb71
d55a911
7c7cb71
 
d55a911
 
7c7cb71
56f099b
0634f1a
bfee845
d55a911
ea0c3e1
0634f1a
b9756ef
0634f1a
90b9e68
 
bfee845
0634f1a
 
bfee845
0634f1a
 
bfee845
0634f1a
 
d55a911
0634f1a
 
 
bfee845
d55a911
bfee845
 
cac7e1a
0634f1a
d55a911
 
bfee845
b9756ef
d55a911
 
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
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": "<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'>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'>{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}")
            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 ---
    def gradio_interface(self):
        def query_interface_wrapper(api_key: str, query: str, state: str) -> str:
            # ... (validation logic remains the same)
            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 here</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>"

            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>")
            if not "<div class='error-message'>" in answer:
                 formatted_response = f"<div class='response-header'><span class='response-icon'>📜</span>Response for {state}</div><hr class='divider'>{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(
                    """
                    <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 Content Sections ---
            with gr.Group(elem_classes="content-surface"):
                gr.Markdown("<h3 class='section-title'>Know Your Rights</h3>")
                gr.Markdown(
                    """
                    <p>Navigate landlord-tenant laws with ease. Enter your <strong>OpenAI API key</strong>, select your state, and ask your question to get detailed, state-specific answers.</p>
                    <p>Don't have an API key? <a href='https://platform.openai.com/api-keys' target='_blank'>Get one free from OpenAI</a>.</p>
                    <p><strong>Disclaimer:</strong> This tool provides information only, not legal advice. For legal guidance, consult a licensed attorney.</p>
                    """
                )

            with gr.Group(elem_classes="content-surface input-form-card"):
                gr.Markdown("<h3>Ask Your Question</h3>")
                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="<div class='placeholder'>Your answer will appear here after submitting your query.</div>",
                    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("<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>
                    """
                )

            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'>Inputs cleared. Ready for your next question.</div>"),
                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)