Nischal Subedi commited on
Commit
a07f515
·
1 Parent(s): 7e15221
Files changed (1) hide show
  1. app.py +242 -170
app.py CHANGED
@@ -5,7 +5,7 @@ from functools import lru_cache
5
  import re
6
 
7
  import gradio as gr
8
- import gradio.themes as themes # Import gradio.themes
9
 
10
  try:
11
  # Assuming vector_db.py exists in the same directory or is installed
@@ -13,30 +13,32 @@ try:
13
  except ImportError:
14
  print("Error: Could not import VectorDatabase from vector_db.py.")
15
  print("Please ensure vector_db.py exists in the same directory and is correctly defined.")
 
16
  exit(1)
17
 
18
  try:
19
  from langchain_openai import ChatOpenAI
20
  except ImportError:
21
  print("Error: langchain-openai not found. Please install it: pip install langchain-openai")
 
22
  exit(1)
23
 
24
  from langchain.prompts import PromptTemplate
25
  from langchain.chains import LLMChain
26
 
27
- # Suppress warnings
28
  import warnings
29
  warnings.filterwarnings("ignore", category=SyntaxWarning)
30
  warnings.filterwarnings("ignore", category=UserWarning, message=".*You are using gradio version.*")
31
  warnings.filterwarnings("ignore", category=DeprecationWarning)
32
 
33
- # Enhanced logging
34
  logging.basicConfig(
35
  level=logging.INFO,
36
  format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
37
  )
38
 
39
- # --- RAGSystem Class (Processing Logic - kept intact as requested) ---
40
  class RAGSystem:
41
  def __init__(self, vector_db: Optional[VectorDatabase] = None):
42
  logging.info("Initializing RAGSystem")
@@ -241,7 +243,7 @@ Answer:"""
241
  logging.error(f"Failed to load or process PDF '{pdf_path}': {str(e)}", exc_info=True)
242
  raise RuntimeError(f"Failed to process PDF '{pdf_path}': {e}") from e
243
 
244
- # --- GRADIO INTERFACE (Refactored to use earneleh/paris theme) ---
245
  def gradio_interface(self):
246
  def query_interface_wrapper(api_key: str, query: str, state: str) -> str:
247
  # Basic client-side validation for immediate feedback (redundant but good UX)
@@ -266,8 +268,9 @@ Answer:"""
266
 
267
  try:
268
  available_states_list = self.get_states()
 
269
  dropdown_choices = ["Select a state..."] + (available_states_list if available_states_list and "Error" not in available_states_list[0] else ["Error: States unavailable"])
270
- initial_value = dropdown_choices[0]
271
  except Exception: # Catch-all for safety
272
  dropdown_choices = ["Error: Critical failure loading states"]
273
  initial_value = dropdown_choices[0]
@@ -287,124 +290,158 @@ Answer:"""
287
  example_queries = [ex for ex in example_queries_base if ex[1] in loaded_states_set]
288
  # Add a generic example if no specific state examples match or if list is empty
289
  if not example_queries:
 
290
  example_queries.append(["What basic rights do tenants have?", available_states_list[0] if available_states_list else "California"])
291
- else: # Fallback if states list is problematic
292
  example_queries.append(["What basic rights do tenants have?", "California"])
293
 
294
- # Improved Custom CSS for better UI design and HuggingFace compatibility
 
 
295
  custom_css = """
296
- /* Import legible fonts */
297
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Poppins:wght@600;700;800&display=swap');
298
 
299
- /* Root variables for consistent theming */
300
  :root {
301
- --primary-color: #2563eb;
302
- --primary-hover: #1d4ed8;
303
- --background-primary: #ffffff;
304
- --background-secondary: #f8fafc;
305
- --text-primary: #1e293b;
306
- --text-secondary: #64748b;
307
- --border-color: #e2e8f0;
308
- --border-focus: #2563eb;
309
- --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
310
- --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
311
- --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
312
- --error-bg: #fef2f2;
313
- --error-border: #fecaca;
314
- --error-text: #dc2626;
315
  }
316
 
317
- /* Dark mode variables */
318
- @media (prefers-color-scheme: dark) {
319
- :root {
320
- --background-primary: #0f172a;
321
- --background-secondary: #1e293b;
322
- --text-primary: #f1f5f9;
323
- --text-secondary: #94a3b8;
324
- --border-color: #334155;
325
- --error-bg: #1e1b1b;
326
- --error-border: #451a1a;
327
- --error-text: #f87171;
328
- }
 
329
  }
 
330
  /* Base container improvements */
331
  .gradio-container {
332
- max-width: 1000px !important;
333
- margin: 0 auto !important;
334
- padding: 1rem !important;
335
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
 
 
 
 
 
 
336
  }
337
- /* Header styling */
 
338
  .app-header-wrapper {
339
  background: linear-gradient(135deg, var(--background-primary) 0%, var(--background-secondary) 100%) !important;
340
  border: 2px solid var(--border-color) !important;
341
  border-radius: 16px !important;
342
- padding: 2rem !important;
343
  margin-bottom: 1.5rem !important;
344
- text-align: center !important;
345
  box-shadow: var(--shadow-md) !important;
346
  }
347
  .app-header-logo {
348
- font-size: 3rem !important;
349
- margin-bottom: 0.5rem !important;
350
  display: block !important;
 
351
  }
352
  .app-header-title {
353
  font-family: 'Poppins', sans-serif !important;
354
- font-size: 2.5rem !important;
355
- font-weight: 700 !important;
356
  color: var(--text-primary) !important;
357
- margin: 0 0 0.5rem 0 !important;
358
- line-height: 1.2 !important;
 
359
  }
360
  .app-header-tagline {
361
- font-size: 1.1rem !important;
362
  color: var(--text-secondary) !important;
363
  font-weight: 400 !important;
364
  margin: 0 !important;
 
 
 
365
  }
366
- /* Main container with compact spacing */
 
367
  .main-dashboard-container {
368
  display: flex !important;
369
  flex-direction: column !important;
370
- gap: 1rem !important; /* Reduced gap for more compact look */
371
  }
372
- /* Card sections with better boundaries */
373
  .dashboard-card-section {
374
  background: var(--background-primary) !important;
375
- border: 2px solid var(--border-color) !important;
376
  border-radius: 12px !important;
377
- padding: 1.5rem !important; /* Reduced padding for compactness */
378
- box-shadow: var(--shadow-sm) !important;
379
  transition: all 0.2s ease !important;
380
  }
381
  .dashboard-card-section:hover {
382
- box-shadow: var(--shadow-md) !important;
383
  }
384
- /* Centered section titles with better typography */
 
385
  .sub-section-title {
386
  font-family: 'Poppins', sans-serif !important;
387
- font-size: 1.5rem !important;
388
- font-weight: 600 !important;
389
  color: var(--text-primary) !important;
390
- text-align: center !important;
391
- margin: 0 0 1rem 0 !important;
392
- padding-bottom: 0.5rem !important;
393
- border-bottom: 2px solid var(--border-color) !important;
394
  display: block !important;
 
 
 
 
 
 
 
 
 
 
 
395
  }
396
- /* Improved input styling with clear boundaries */
 
397
  .gradio-textbox, .gradio-dropdown {
398
- margin-bottom: 0.75rem !important; /* Reduced margin for compactness */
399
  }
400
  .gradio-textbox textarea,
401
  .gradio-textbox input,
402
- .gradio-dropdown select {
 
 
 
403
  background: var(--background-primary) !important;
404
- border: 2px solid var(--border-color) !important;
405
  border-radius: 8px !important;
406
- padding: 0.75rem !important;
407
- font-size: 0.95rem !important;
408
  font-family: 'Inter', sans-serif !important;
409
  color: var(--text-primary) !important;
410
  transition: all 0.2s ease !important;
@@ -412,57 +449,55 @@ Answer:"""
412
  }
413
  .gradio-textbox textarea:focus,
414
  .gradio-textbox input:focus,
415
- .gradio-dropdown select:focus {
 
416
  outline: none !important;
417
- border-color: var(--border-focus) !important;
418
- box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1) !important;
419
- }
420
- /* Placeholder text styling */
421
- .gradio-textbox textarea::placeholder,
422
- .gradio-textbox input::placeholder {
423
- color: var(--text-secondary) !important;
424
- opacity: 0.7 !important;
425
  }
 
426
  /* Label styling for better readability */
427
  .gradio-textbox label,
428
  .gradio-dropdown label {
429
- font-weight: 500 !important;
430
  color: var(--text-primary) !important;
431
- font-size: 0.9rem !important;
432
- margin-bottom: 0.5rem !important;
433
  display: block !important;
434
  }
435
- /* Info text styling */
436
  .gradio-textbox .gr-form,
437
  .gradio-dropdown .gr-form {
438
- font-size: 0.85rem !important;
439
  color: var(--text-secondary) !important;
440
- margin-top: 0.25rem !important;
441
  }
442
  /* Input row layout improvements */
443
  .input-row {
444
  display: flex !important;
445
- gap: 1rem !important;
446
- margin-bottom: 0.5rem !important; /* Reduced margin */
447
  }
448
  .input-field {
449
  flex: 1 !important;
450
  }
 
451
  /* Button styling improvements */
452
  .button-row {
453
  display: flex !important;
454
  gap: 1rem !important;
455
- justify-content: flex-end !important;
456
- margin-top: 1rem !important;
457
  }
458
  .gradio-button {
459
- padding: 0.75rem 1.5rem !important;
460
- border-radius: 8px !important;
461
- font-weight: 500 !important;
462
- font-size: 0.9rem !important;
463
- transition: all 0.2s ease !important;
464
  cursor: pointer !important;
465
  border: 2px solid transparent !important;
 
466
  }
467
  .gr-button-primary {
468
  background: var(--primary-color) !important;
@@ -472,7 +507,7 @@ Answer:"""
472
  .gr-button-primary:hover {
473
  background: var(--primary-hover) !important;
474
  box-shadow: var(--shadow-md) !important;
475
- transform: translateY(-1px) !important;
476
  }
477
  .gr-button-secondary {
478
  background: transparent !important;
@@ -482,63 +517,83 @@ Answer:"""
482
  .gr-button-secondary:hover {
483
  background: var(--background-secondary) !important;
484
  border-color: var(--primary-color) !important;
 
485
  }
486
- /* Output styling with clear boundaries */
 
487
  .output-content-wrapper {
488
  background: var(--background-primary) !important;
489
- border: 2px solid var(--border-color) !important;
490
  border-radius: 8px !important;
491
- padding: 1rem !important;
492
- min-height: 100px !important;
493
- font-size: 0.95rem !important;
494
- line-height: 1.6 !important;
495
  color: var(--text-primary) !important;
 
 
 
496
  }
497
  .response-header {
498
- font-size: 1.2rem !important;
499
- font-weight: 600 !important;
500
- color: var(--text-primary) !important;
501
  margin-bottom: 0.75rem !important;
502
  display: flex !important;
503
  align-items: center !important;
504
- gap: 0.5rem !important;
505
  }
506
  .response-icon {
507
- font-size: 1.3rem !important;
508
  color: var(--primary-color) !important;
509
  }
510
  .divider {
511
  border: none !important;
512
- border-top: 1px solid var(--border-color) !important;
513
- margin: 0.75rem 0 !important;
514
  }
 
515
  /* Error message styling */
516
  .error-message {
517
  background: var(--error-bg) !important;
518
  border: 2px solid var(--error-border) !important;
519
  color: var(--error-text) !important;
520
- padding: 1rem !important;
521
  border-radius: 8px !important;
522
  display: flex !important;
523
  align-items: flex-start !important;
524
- gap: 0.75rem !important;
525
- font-size: 0.9rem !important;
 
 
 
 
 
 
526
  }
527
  .error-icon {
528
- font-size: 1.2rem !important;
529
  line-height: 1 !important;
530
  margin-top: 0.1rem !important;
531
  }
532
- /* Placeholder styling */
 
 
 
 
 
 
533
  .placeholder {
534
  background: var(--background-secondary) !important;
535
  border: 2px dashed var(--border-color) !important;
536
  border-radius: 8px !important;
537
- padding: 2rem 1rem !important;
538
  text-align: center !important;
539
  color: var(--text-secondary) !important;
540
  font-style: italic !important;
 
541
  }
 
542
  /* Examples table styling */
543
  .examples-section .gr-samples-table {
544
  border: 2px solid var(--border-color) !important;
@@ -548,13 +603,14 @@ Answer:"""
548
  }
549
  .examples-section .gr-samples-table th,
550
  .examples-section .gr-samples-table td {
551
- padding: 0.75rem !important;
552
  border: none !important;
553
- font-size: 0.9rem !important;
 
554
  }
555
  .examples-section .gr-samples-table th {
556
  background: var(--background-secondary) !important;
557
- font-weight: 600 !important;
558
  color: var(--text-primary) !important;
559
  }
560
  .examples-section .gr-samples-table td {
@@ -566,66 +622,78 @@ Answer:"""
566
  .examples-section .gr-samples-table tr:hover td {
567
  background: var(--background-secondary) !important;
568
  }
569
- /* Footer styling */
 
 
 
 
 
 
 
570
  .app-footer-wrapper {
571
  background: var(--background-secondary) !important;
572
  border: 2px solid var(--border-color) !important;
573
  border-radius: 12px !important;
574
- padding: 1.5rem !important;
575
  margin-top: 1.5rem !important;
576
- text-align: center !important;
577
  }
578
  .app-footer p {
579
- margin: 0.5rem 0 !important;
580
- font-size: 0.9rem !important;
581
  color: var(--text-secondary) !important;
582
- line-height: 1.5 !important;
583
  }
584
  .app-footer a {
585
  color: var(--primary-color) !important;
586
  text-decoration: none !important;
587
- font-weight: 500 !important;
588
  }
589
  .app-footer a:hover {
590
  text-decoration: underline !important;
591
  }
592
- /* Hide Gradio default elements */
593
- .gr-examples .gr-label,
594
- .gr-examples .label-wrap,
595
- .gr-examples .gr-accordion-header {
596
- display: none !important;
597
- }
598
- /* Responsive design */
599
  @media (max-width: 768px) {
600
  .gradio-container {
601
- padding: 0.5rem !important;
602
  }
603
-
604
  .app-header-title {
605
- font-size: 2rem !important;
606
  }
607
-
608
  .app-header-tagline {
609
  font-size: 1rem !important;
610
  }
611
-
 
 
612
  .input-row {
613
- flex-direction: column !important;
614
  }
615
-
616
  .button-row {
617
- flex-direction: column !important;
618
  }
619
-
620
  .gradio-button {
621
- width: 100% !important;
 
 
 
 
 
 
 
 
 
 
622
  }
623
  }
624
  """
625
 
626
- with gr.Blocks(theme="soft", css=custom_css, title="Landlord-Tenant Rights Assistant") as demo:
627
- # Header Section
 
628
  with gr.Group(elem_classes="app-header-wrapper"):
 
629
  gr.Markdown(
630
  """
631
  <div class="app-header">
@@ -636,12 +704,12 @@ Answer:"""
636
  """
637
  )
638
 
639
- # Main Dashboard Container
640
  with gr.Column(elem_classes="main-dashboard-container"):
641
 
642
  # Introduction and Disclaimer Card
643
  with gr.Group(elem_classes="dashboard-card-section"):
644
- gr.Markdown("<h3 class='sub-section-title'>Welcome & Disclaimer</h3>")
645
  gr.Markdown(
646
  """
647
  Navigate landlord-tenant laws with ease. This assistant provides detailed, state-specific answers grounded in legal authority.
@@ -652,21 +720,21 @@ Answer:"""
652
 
653
  # OpenAI API Key Input Card
654
  with gr.Group(elem_classes="dashboard-card-section"):
655
- gr.Markdown("<h3 class='sub-section-title'>OpenAI API Key</h3>")
656
  api_key_input = gr.Textbox(
657
  label="API Key",
658
- type="password",
659
- placeholder="Enter your API key (e.g., sk-...)",
660
- info="Required to process your query. Get one free from OpenAI.",
661
  lines=1,
662
- elem_classes=["input-field-group"]
663
  )
664
 
665
  # Query Input and State Selection Card
666
  with gr.Group(elem_classes="dashboard-card-section"):
667
- gr.Markdown("<h3 class='sub-section-title'>Ask Your Question</h3>")
668
- with gr.Row(elem_classes="input-row"):
669
- with gr.Column(elem_classes="input-field", scale=3):
670
  query_input = gr.Textbox(
671
  label="Your Question",
672
  placeholder="E.g., What are the rules for security deposit returns in my state?",
@@ -674,7 +742,7 @@ Answer:"""
674
  max_lines=8,
675
  elem_classes=["input-field-group"]
676
  )
677
- with gr.Column(elem_classes="input-field", scale=1):
678
  state_input = gr.Dropdown(
679
  label="Select State",
680
  choices=dropdown_choices,
@@ -682,32 +750,32 @@ Answer:"""
682
  allow_custom_value=False,
683
  elem_classes=["input-field-group"]
684
  )
685
- with gr.Row(elem_classes="button-row"):
686
  clear_button = gr.Button("Clear", variant="secondary", elem_classes=["gr-button-secondary"])
687
  submit_button = gr.Button("Submit Query", variant="primary", elem_classes=["gr-button-primary"])
688
 
689
  # Output Display Card
690
  with gr.Group(elem_classes="dashboard-card-section"):
691
- gr.Markdown("<h3 class='sub-section-title'>Legal Assistant's Response</h3>")
692
  output = gr.Markdown(
693
  value="<div class='placeholder'>The answer will appear here after submitting your query.</div>",
694
- elem_classes="output-content-wrapper"
695
  )
696
 
697
  # Example Questions Section
698
  with gr.Group(elem_classes="dashboard-card-section examples-section"):
699
- gr.Markdown("<h3 class='sub-section-title'>Example Questions</h3>")
700
  if example_queries:
701
  gr.Examples(
702
  examples=example_queries,
703
  inputs=[query_input, state_input],
704
  examples_per_page=5,
705
- label=""
706
  )
707
  else:
708
- gr.Markdown("<div class='placeholder'>Sample questions could not be loaded.</div>")
709
 
710
- # Footer Section
711
  with gr.Group(elem_classes="app-footer-wrapper"):
712
  gr.Markdown(
713
  """
@@ -716,20 +784,20 @@ Answer:"""
716
  """
717
  )
718
 
719
- # Event Listeners
720
  submit_button.click(
721
  fn=query_interface_wrapper,
722
  inputs=[api_key_input, query_input, state_input],
723
  outputs=output,
724
- api_name="submit_query"
725
  )
726
 
727
  clear_button.click(
728
  fn=lambda: (
729
- "",
730
- "",
731
- initial_value,
732
- "<div class='placeholder'>Inputs cleared. Ready for your next question.</div>"
733
  ),
734
  inputs=[],
735
  outputs=[api_key_input, query_input, state_input, output]
@@ -737,7 +805,7 @@ Answer:"""
737
 
738
  return demo
739
 
740
- # --- Main Execution Block (remains untouched from original logic, just fixed the exit) ---
741
  if __name__ == "__main__":
742
  logging.info("Starting Landlord-Tenant Rights Bot application...")
743
  try:
@@ -748,28 +816,32 @@ if __name__ == "__main__":
748
  PDF_PATH = os.getenv("PDF_PATH", DEFAULT_PDF_PATH)
749
  VECTOR_DB_PATH = os.getenv("VECTOR_DB_PATH", DEFAULT_DB_PATH)
750
 
 
751
  os.makedirs(os.path.dirname(VECTOR_DB_PATH), exist_ok=True)
752
 
753
  logging.info(f"Attempting to load PDF from: {PDF_PATH}")
754
  if not os.path.exists(PDF_PATH):
755
  logging.error(f"FATAL: PDF file not found at the specified path: {PDF_PATH}")
756
  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")
757
- exit(1) # This exit is correct: if file not found
758
 
759
  if not os.access(PDF_PATH, os.R_OK):
760
  logging.error(f"FATAL: PDF file at '{PDF_PATH}' exists but is not readable. Check file permissions.")
761
  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")
762
- exit(1) # This exit is correct: if file exists but is not readable
763
 
764
  logging.info(f"PDF file '{os.path.basename(PDF_PATH)}' found and is readable.")
765
 
 
766
  vector_db_instance = VectorDatabase(persist_directory=VECTOR_DB_PATH)
767
  rag = RAGSystem(vector_db=vector_db_instance)
768
 
 
769
  rag.load_pdf(PDF_PATH)
770
 
 
771
  app_interface = rag.gradio_interface()
772
- SERVER_PORT = int(os.getenv("PORT", 7860)) # Use PORT env var if on Spaces/Cloud, else 7860
773
 
774
  logging.info(f"Launching Gradio app on http://0.0.0.0:{SERVER_PORT}")
775
  print(f"\n--- Gradio App Running ---\nAccess at: http://localhost:{SERVER_PORT} or your public Spaces URL\n--------------------------\n")
 
5
  import re
6
 
7
  import gradio as gr
8
+ # import gradio.themes as themes # Not directly used for theme dropdown, but kept if you had other theme-related utilities.
9
 
10
  try:
11
  # Assuming vector_db.py exists in the same directory or is installed
 
13
  except ImportError:
14
  print("Error: Could not import VectorDatabase from vector_db.py.")
15
  print("Please ensure vector_db.py exists in the same directory and is correctly defined.")
16
+ # Exit if critical dependency is missing at import time
17
  exit(1)
18
 
19
  try:
20
  from langchain_openai import ChatOpenAI
21
  except ImportError:
22
  print("Error: langchain-openai not found. Please install it: pip install langchain-openai")
23
+ # Exit if critical dependency is missing at import time
24
  exit(1)
25
 
26
  from langchain.prompts import PromptTemplate
27
  from langchain.chains import LLMChain
28
 
29
+ # Suppress warnings for cleaner console output
30
  import warnings
31
  warnings.filterwarnings("ignore", category=SyntaxWarning)
32
  warnings.filterwarnings("ignore", category=UserWarning, message=".*You are using gradio version.*")
33
  warnings.filterwarnings("ignore", category=DeprecationWarning)
34
 
35
+ # Enhanced logging configuration
36
  logging.basicConfig(
37
  level=logging.INFO,
38
  format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
39
  )
40
 
41
+ # --- RAGSystem Class (Processing Logic - KEPT INTACT AS REQUESTED) ---
42
  class RAGSystem:
43
  def __init__(self, vector_db: Optional[VectorDatabase] = None):
44
  logging.info("Initializing RAGSystem")
 
243
  logging.error(f"Failed to load or process PDF '{pdf_path}': {str(e)}", exc_info=True)
244
  raise RuntimeError(f"Failed to process PDF '{pdf_path}': {e}") from e
245
 
246
+ # --- GRADIO INTERFACE (NEW UI DESIGN) ---
247
  def gradio_interface(self):
248
  def query_interface_wrapper(api_key: str, query: str, state: str) -> str:
249
  # Basic client-side validation for immediate feedback (redundant but good UX)
 
268
 
269
  try:
270
  available_states_list = self.get_states()
271
+ # Ensure "Select a state..." is always the first option
272
  dropdown_choices = ["Select a state..."] + (available_states_list if available_states_list and "Error" not in available_states_list[0] else ["Error: States unavailable"])
273
+ initial_value = dropdown_choices[0] # Set initial value to the prompt
274
  except Exception: # Catch-all for safety
275
  dropdown_choices = ["Error: Critical failure loading states"]
276
  initial_value = dropdown_choices[0]
 
290
  example_queries = [ex for ex in example_queries_base if ex[1] in loaded_states_set]
291
  # Add a generic example if no specific state examples match or if list is empty
292
  if not example_queries:
293
+ # Add one example using the first available state, or a common one if no states
294
  example_queries.append(["What basic rights do tenants have?", available_states_list[0] if available_states_list else "California"])
295
+ else: # Fallback if states list is problematic (e.g., empty or error)
296
  example_queries.append(["What basic rights do tenants have?", "California"])
297
 
298
+
299
+ # Custom CSS for better UI design, clear boundaries, and text alignment for HuggingFace
300
+ # This CSS overrides Gradio defaults to create the desired look and feel.
301
  custom_css = """
302
+ /* Import legible fonts from Google Fonts */
303
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Poppins:wght@600;700;800&display=swap');
304
 
305
+ /* Root variables for consistent theming - adjusted for calm_seafoam feel */
306
  :root {
307
+ --primary-color: #4CAF50; /* A pleasant green */
308
+ --primary-hover: #45a049;
309
+ --background-primary: #F0F8F8; /* Light seafoam background */
310
+ --background-secondary: #E8F0F0; /* Slightly darker for contrast */
311
+ --text-primary: #2C3E50; /* Darker text for readability */
312
+ --text-secondary: #5F7C8A; /* Muted text */
313
+ --border-color: #B2D8D8; /* Seafoam border */
314
+ --border-focus: #4CAF50; /* Focus color matches primary */
315
+ --shadow-sm: 0 1px 3px rgba(0,0,0,0.08);
316
+ --shadow-md: 0 4px 10px rgba(0,0,0,0.1);
317
+ --shadow-lg: 0 10px 20px rgba(0,0,0,0.15);
318
+ --error-bg: #FFEBEB;
319
+ --error-border: #FFCACA;
320
+ --error-text: #D32F2F;
321
  }
322
 
323
+ /* Dark mode variables - for consistency if a dark mode toggle were present */
324
+ /* calm_seafoam theme itself is light, but if a `dark` class is applied to body: */
325
+ body.dark {
326
+ --background-primary: #1F303A; /* Dark blue-green */
327
+ --background-secondary: #2C404B;
328
+ --text-primary: #E0F2F1;
329
+ --text-secondary: #A7C5C8;
330
+ --border-color: #5F7C8A;
331
+ --primary-color: #66BB6A; /* Brighter green for dark mode */
332
+ --primary-hover: #5cb85f;
333
+ --error-bg: #3F1D1D;
334
+ --error-border: #5A1A1A;
335
+ --error-text: #FF7070;
336
  }
337
+
338
  /* Base container improvements */
339
  .gradio-container {
340
+ max-width: 900px !important; /* Slightly smaller for focused content */
341
+ margin: 0 auto !important; /* Center the whole app */
342
+ padding: 1.5rem !important;
343
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
344
+ background-color: var(--background-secondary) !important; /* Overall background */
345
+ box-shadow: none !important; /* Remove default gradio container shadow */
346
+ }
347
+ /* Ensure all main content sections have primary background */
348
+ .main-dashboard-container > * {
349
+ background-color: var(--background-primary) !important;
350
  }
351
+
352
+ /* Header styling - centered and prominent */
353
  .app-header-wrapper {
354
  background: linear-gradient(135deg, var(--background-primary) 0%, var(--background-secondary) 100%) !important;
355
  border: 2px solid var(--border-color) !important;
356
  border-radius: 16px !important;
357
+ padding: 2.5rem 1.5rem !important; /* More vertical padding */
358
  margin-bottom: 1.5rem !important;
359
+ text-align: center !important; /* Center text within header */
360
  box-shadow: var(--shadow-md) !important;
361
  }
362
  .app-header-logo {
363
+ font-size: 3.5rem !important; /* Larger icon */
364
+ margin-bottom: 0.75rem !important;
365
  display: block !important;
366
+ color: var(--primary-color) !important; /* Theme color */
367
  }
368
  .app-header-title {
369
  font-family: 'Poppins', sans-serif !important;
370
+ font-size: 2.8rem !important; /* Larger title */
371
+ font-weight: 800 !important; /* Bolder */
372
  color: var(--text-primary) !important;
373
+ margin: 0 0 0.75rem 0 !important;
374
+ line-height: 1.1 !important;
375
+ letter-spacing: -0.02em !important; /* Slightly tighter spacing */
376
  }
377
  .app-header-tagline {
378
+ font-size: 1.2rem !important;
379
  color: var(--text-secondary) !important;
380
  font-weight: 400 !important;
381
  margin: 0 !important;
382
+ max-width: 700px; /* Constrain tagline width */
383
+ margin-left: auto;
384
+ margin-right: auto;
385
  }
386
+
387
+ /* Main container with consistent spacing */
388
  .main-dashboard-container {
389
  display: flex !important;
390
  flex-direction: column !important;
391
+ gap: 1.25rem !important; /* Consistent spacing between cards */
392
  }
393
+ /* Card sections with clear boundaries (boundeyes) */
394
  .dashboard-card-section {
395
  background: var(--background-primary) !important;
396
+ border: 2px solid var(--border-color) !important; /* Distinct border */
397
  border-radius: 12px !important;
398
+ padding: 1.75rem !important; /* Consistent padding */
399
+ box-shadow: var(--shadow-sm) !important; /* Subtle shadow */
400
  transition: all 0.2s ease !important;
401
  }
402
  .dashboard-card-section:hover {
403
+ box-shadow: var(--shadow-md) !important; /* Enhanced shadow on hover */
404
  }
405
+
406
+ /* Centered section titles with improved typography */
407
  .sub-section-title {
408
  font-family: 'Poppins', sans-serif !important;
409
+ font-size: 1.6rem !important;
410
+ font-weight: 700 !important;
411
  color: var(--text-primary) !important;
412
+ text-align: center !important; /* Centered text */
413
+ margin: 0 0 1.25rem 0 !important; /* More space below title */
414
+ padding-bottom: 0.75rem !important;
415
+ border-bottom: 2px solid var(--border-color) !important; /* Underline effect */
416
  display: block !important;
417
+ letter-spacing: -0.01em !important;
418
+ }
419
+
420
+ /* Specific styling for the welcome/disclaimer markdown content */
421
+ .dashboard-card-section p {
422
+ line-height: 1.7 !important;
423
+ color: var(--text-primary) !important;
424
+ font-size: 1rem !important;
425
+ }
426
+ .dashboard-card-section strong {
427
+ color: var(--primary-color) !important; /* Highlight strong text with primary color */
428
  }
429
+
430
+ /* Improved input styling with clear boundaries and focus */
431
  .gradio-textbox, .gradio-dropdown {
432
+ margin-bottom: 0.75rem !important;
433
  }
434
  .gradio-textbox textarea,
435
  .gradio-textbox input,
436
+ .gradio-dropdown > div > input[type="text"], /* Target dropdown input for custom values */
437
+ .gradio-dropdown .primary-wrap, /* Target dropdown wrapper */
438
+ .gradio-dropdown .scroll-hide /* Target dropdown list container for consistency */
439
+ {
440
  background: var(--background-primary) !important;
441
+ border: 2px solid var(--border-color) !important; /* Clear border */
442
  border-radius: 8px !important;
443
+ padding: 0.85rem 1rem !important; /* Slightly more padding */
444
+ font-size: 0.98rem !important;
445
  font-family: 'Inter', sans-serif !important;
446
  color: var(--text-primary) !important;
447
  transition: all 0.2s ease !important;
 
449
  }
450
  .gradio-textbox textarea:focus,
451
  .gradio-textbox input:focus,
452
+ .gradio-dropdown > div > input[type="text"]:focus,
453
+ .gradio-dropdown .primary-wrap.focused { /* Apply focus style to dropdown wrap */
454
  outline: none !important;
455
+ border-color: var(--border-focus) !important; /* Distinct border on focus */
456
+ box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.15) !important; /* Soft glow on focus */
 
 
 
 
 
 
457
  }
458
+
459
  /* Label styling for better readability */
460
  .gradio-textbox label,
461
  .gradio-dropdown label {
462
+ font-weight: 600 !important; /* Bolder labels */
463
  color: var(--text-primary) !important;
464
+ font-size: 1rem !important;
465
+ margin-bottom: 0.6rem !important;
466
  display: block !important;
467
  }
468
+ /* Info text styling below inputs */
469
  .gradio-textbox .gr-form,
470
  .gradio-dropdown .gr-form {
471
+ font-size: 0.9rem !important;
472
  color: var(--text-secondary) !important;
473
+ margin-top: 0.4rem !important; /* More space for info text */
474
  }
475
  /* Input row layout improvements */
476
  .input-row {
477
  display: flex !important;
478
+ gap: 1.25rem !important; /* Consistent gap between query and state */
479
+ margin-bottom: 0.5rem !important;
480
  }
481
  .input-field {
482
  flex: 1 !important;
483
  }
484
+
485
  /* Button styling improvements */
486
  .button-row {
487
  display: flex !important;
488
  gap: 1rem !important;
489
+ justify-content: flex-end !important; /* Align buttons to the right */
490
+ margin-top: 1.5rem !important; /* More space above buttons */
491
  }
492
  .gradio-button {
493
+ padding: 0.85rem 1.8rem !important; /* More padding for bigger buttons */
494
+ border-radius: 9px !important; /* Slightly more rounded */
495
+ font-weight: 600 !important; /* Bolder text */
496
+ font-size: 1rem !important;
497
+ transition: all 0.25s ease !important;
498
  cursor: pointer !important;
499
  border: 2px solid transparent !important;
500
+ text-align: center !important; /* Ensure button text is centered */
501
  }
502
  .gr-button-primary {
503
  background: var(--primary-color) !important;
 
507
  .gr-button-primary:hover {
508
  background: var(--primary-hover) !important;
509
  box-shadow: var(--shadow-md) !important;
510
+ transform: translateY(-2px) !important; /* Subtle lift effect on hover */
511
  }
512
  .gr-button-secondary {
513
  background: transparent !important;
 
517
  .gr-button-secondary:hover {
518
  background: var(--background-secondary) !important;
519
  border-color: var(--primary-color) !important;
520
+ transform: translateY(-2px) !important;
521
  }
522
+
523
+ /* Output styling with clear boundaries (boundeyes are clear) */
524
  .output-content-wrapper {
525
  background: var(--background-primary) !important;
526
+ border: 2px solid var(--border-color) !important; /* Clear border */
527
  border-radius: 8px !important;
528
+ padding: 1.5rem !important;
529
+ min-height: 150px !important; /* More space for output */
530
+ font-size: 1rem !important;
531
+ line-height: 1.7 !important;
532
  color: var(--text-primary) !important;
533
+ overflow-wrap: break-word; /* Ensure long words wrap */
534
+ word-break: break-word; /* Ensure long words wrap */
535
+ white-space: pre-wrap; /* Preserve formatting for newlines in markdown */
536
  }
537
  .response-header {
538
+ font-size: 1.3rem !important;
539
+ font-weight: 700 !important;
540
+ color: var(--primary-color) !important; /* Matches primary color */
541
  margin-bottom: 0.75rem !important;
542
  display: flex !important;
543
  align-items: center !important;
544
+ gap: 0.6rem !important;
545
  }
546
  .response-icon {
547
+ font-size: 1.5rem !important;
548
  color: var(--primary-color) !important;
549
  }
550
  .divider {
551
  border: none !important;
552
+ border-top: 1px dashed var(--border-color) !important; /* Dashed divider for visual separation */
553
+ margin: 1rem 0 !important;
554
  }
555
+
556
  /* Error message styling */
557
  .error-message {
558
  background: var(--error-bg) !important;
559
  border: 2px solid var(--error-border) !important;
560
  color: var(--error-text) !important;
561
+ padding: 1.25rem !important;
562
  border-radius: 8px !important;
563
  display: flex !important;
564
  align-items: flex-start !important;
565
+ gap: 0.8rem !important;
566
+ font-size: 0.95rem !important;
567
+ font-weight: 500 !important;
568
+ line-height: 1.6 !important;
569
+ }
570
+ .error-message a {
571
+ color: var(--error-text) !important;
572
+ text-decoration: underline !important;
573
  }
574
  .error-icon {
575
+ font-size: 1.4rem !important;
576
  line-height: 1 !important;
577
  margin-top: 0.1rem !important;
578
  }
579
+ .error-details {
580
+ font-size: 0.85rem !important;
581
+ color: var(--error-text) !important;
582
+ margin-top: 0.5rem !important;
583
+ opacity: 0.8;
584
+ }
585
+ /* Placeholder styling for empty output */
586
  .placeholder {
587
  background: var(--background-secondary) !important;
588
  border: 2px dashed var(--border-color) !important;
589
  border-radius: 8px !important;
590
+ padding: 2.5rem 1.5rem !important;
591
  text-align: center !important;
592
  color: var(--text-secondary) !important;
593
  font-style: italic !important;
594
+ font-size: 1.1rem !important;
595
  }
596
+
597
  /* Examples table styling */
598
  .examples-section .gr-samples-table {
599
  border: 2px solid var(--border-color) !important;
 
603
  }
604
  .examples-section .gr-samples-table th,
605
  .examples-section .gr-samples-table td {
606
+ padding: 0.9rem !important;
607
  border: none !important;
608
+ font-size: 0.95rem !important;
609
+ text-align: left !important; /* Ensure example text is left-aligned */
610
  }
611
  .examples-section .gr-samples-table th {
612
  background: var(--background-secondary) !important;
613
+ font-weight: 700 !important;
614
  color: var(--text-primary) !important;
615
  }
616
  .examples-section .gr-samples-table td {
 
622
  .examples-section .gr-samples-table tr:hover td {
623
  background: var(--background-secondary) !important;
624
  }
625
+ /* Hide Gradio default elements for examples for cleaner look */
626
+ .gr-examples .gr-label,
627
+ .gr-examples .label-wrap,
628
+ .gr-examples .gr-accordion-header {
629
+ display: none !important;
630
+ }
631
+
632
+ /* Footer styling - centered text */
633
  .app-footer-wrapper {
634
  background: var(--background-secondary) !important;
635
  border: 2px solid var(--border-color) !important;
636
  border-radius: 12px !important;
637
+ padding: 1.75rem !important;
638
  margin-top: 1.5rem !important;
639
+ text-align: center !important; /* Centered footer text */
640
  }
641
  .app-footer p {
642
+ margin: 0.6rem 0 !important;
643
+ font-size: 0.95rem !important;
644
  color: var(--text-secondary) !important;
645
+ line-height: 1.6 !important;
646
  }
647
  .app-footer a {
648
  color: var(--primary-color) !important;
649
  text-decoration: none !important;
650
+ font-weight: 600 !important;
651
  }
652
  .app-footer a:hover {
653
  text-decoration: underline !important;
654
  }
655
+
656
+ /* Responsive design for smaller screens */
 
 
 
 
 
657
  @media (max-width: 768px) {
658
  .gradio-container {
659
+ padding: 1rem !important;
660
  }
 
661
  .app-header-title {
662
+ font-size: 2.2rem !important;
663
  }
 
664
  .app-header-tagline {
665
  font-size: 1rem !important;
666
  }
667
+ .sub-section-title {
668
+ font-size: 1.4rem !important;
669
+ }
670
  .input-row {
671
+ flex-direction: column !important; /* Stack inputs vertically */
672
  }
 
673
  .button-row {
674
+ flex-direction: column !important; /* Stack buttons vertically */
675
  }
 
676
  .gradio-button {
677
+ width: 100% !important; /* Full width buttons */
678
+ }
679
+ .dashboard-card-section {
680
+ padding: 1.25rem !important;
681
+ }
682
+ .output-content-wrapper {
683
+ min-height: 120px !important;
684
+ }
685
+ .placeholder {
686
+ padding: 1.5rem 1rem !important;
687
+ font-size: 1rem !important;
688
  }
689
  }
690
  """
691
 
692
+ # Using gr.Blocks with the specified theme and custom CSS
693
+ with gr.Blocks(theme="shivi/calm_seafoam", css=custom_css, title="Landlord-Tenant Rights Assistant") as demo:
694
+ # Header Section - uses gr.Group for distinct card-like styling
695
  with gr.Group(elem_classes="app-header-wrapper"):
696
+ # Markdown used for flexible styling and auto-centering via CSS
697
  gr.Markdown(
698
  """
699
  <div class="app-header">
 
704
  """
705
  )
706
 
707
+ # Main Dashboard Container - acts as a column to stack various sections
708
  with gr.Column(elem_classes="main-dashboard-container"):
709
 
710
  # Introduction and Disclaimer Card
711
  with gr.Group(elem_classes="dashboard-card-section"):
712
+ gr.Markdown("<h3 class='sub-section-title'>Welcome & Disclaimer</h3>") # Centered by CSS
713
  gr.Markdown(
714
  """
715
  Navigate landlord-tenant laws with ease. This assistant provides detailed, state-specific answers grounded in legal authority.
 
720
 
721
  # OpenAI API Key Input Card
722
  with gr.Group(elem_classes="dashboard-card-section"):
723
+ gr.Markdown("<h3 class='sub-section-title'>OpenAI API Key</h3>") # Centered by CSS
724
  api_key_input = gr.Textbox(
725
  label="API Key",
726
+ type="password", # Hides the input for security
727
+ placeholder="Enter your OpenAI API key (e.g., sk-...)",
728
+ info="Required to process your query. Get one from OpenAI: platform.openai.com/api-keys",
729
  lines=1,
730
+ elem_classes=["input-field-group"] # Custom class for input styling
731
  )
732
 
733
  # Query Input and State Selection Card
734
  with gr.Group(elem_classes="dashboard-card-section"):
735
+ gr.Markdown("<h3 class='sub-section-title'>Ask Your Question</h3>") # Centered by CSS
736
+ with gr.Row(elem_classes="input-row"): # Row for side-by-side query and state
737
+ with gr.Column(elem_classes="input-field", scale=3): # Query text area takes more space
738
  query_input = gr.Textbox(
739
  label="Your Question",
740
  placeholder="E.g., What are the rules for security deposit returns in my state?",
 
742
  max_lines=8,
743
  elem_classes=["input-field-group"]
744
  )
745
+ with gr.Column(elem_classes="input-field", scale=1): # State dropdown takes less space
746
  state_input = gr.Dropdown(
747
  label="Select State",
748
  choices=dropdown_choices,
 
750
  allow_custom_value=False,
751
  elem_classes=["input-field-group"]
752
  )
753
+ with gr.Row(elem_classes="button-row"): # Row for action buttons
754
  clear_button = gr.Button("Clear", variant="secondary", elem_classes=["gr-button-secondary"])
755
  submit_button = gr.Button("Submit Query", variant="primary", elem_classes=["gr-button-primary"])
756
 
757
  # Output Display Card
758
  with gr.Group(elem_classes="dashboard-card-section"):
759
+ gr.Markdown("<h3 class='sub-section-title'>Legal Assistant's Response</h3>") # Centered by CSS
760
  output = gr.Markdown(
761
  value="<div class='placeholder'>The answer will appear here after submitting your query.</div>",
762
+ elem_classes="output-content-wrapper" # Custom class for output styling
763
  )
764
 
765
  # Example Questions Section
766
  with gr.Group(elem_classes="dashboard-card-section examples-section"):
767
+ gr.Markdown("<h3 class='sub-section-title'>Example Questions</h3>") # Centered by CSS
768
  if example_queries:
769
  gr.Examples(
770
  examples=example_queries,
771
  inputs=[query_input, state_input],
772
  examples_per_page=5,
773
+ label="" # Hide default Gradio label for examples to use our custom title
774
  )
775
  else:
776
+ gr.Markdown("<div class='placeholder'>Sample questions could not be loaded. Please ensure the vector database is populated.</div>")
777
 
778
+ # Footer Section - contains disclaimer and developer info
779
  with gr.Group(elem_classes="app-footer-wrapper"):
780
  gr.Markdown(
781
  """
 
784
  """
785
  )
786
 
787
+ # Event Listeners for buttons
788
  submit_button.click(
789
  fn=query_interface_wrapper,
790
  inputs=[api_key_input, query_input, state_input],
791
  outputs=output,
792
+ api_name="submit_query" # Useful for debugging / external calls
793
  )
794
 
795
  clear_button.click(
796
  fn=lambda: (
797
+ "", # Clear API key input
798
+ "", # Clear query input
799
+ initial_value, # Reset state dropdown to default prompt
800
+ "<div class='placeholder'>Inputs cleared. Ready for your next question.</div>" # Reset output message
801
  ),
802
  inputs=[],
803
  outputs=[api_key_input, query_input, state_input, output]
 
805
 
806
  return demo
807
 
808
+ # --- Main Execution Block (UNCHANGED from original logic) ---
809
  if __name__ == "__main__":
810
  logging.info("Starting Landlord-Tenant Rights Bot application...")
811
  try:
 
816
  PDF_PATH = os.getenv("PDF_PATH", DEFAULT_PDF_PATH)
817
  VECTOR_DB_PATH = os.getenv("VECTOR_DB_PATH", DEFAULT_DB_PATH)
818
 
819
+ # Ensure vector DB directory exists before initialization
820
  os.makedirs(os.path.dirname(VECTOR_DB_PATH), exist_ok=True)
821
 
822
  logging.info(f"Attempting to load PDF from: {PDF_PATH}")
823
  if not os.path.exists(PDF_PATH):
824
  logging.error(f"FATAL: PDF file not found at the specified path: {PDF_PATH}")
825
  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")
826
+ exit(1) # Correctly exits if PDF is not found
827
 
828
  if not os.access(PDF_PATH, os.R_OK):
829
  logging.error(f"FATAL: PDF file at '{PDF_PATH}' exists but is not readable. Check file permissions.")
830
  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")
831
+ exit(1) # Correctly exits if PDF is unreadable
832
 
833
  logging.info(f"PDF file '{os.path.basename(PDF_PATH)}' found and is readable.")
834
 
835
+ # Initialize VectorDatabase and RAGSystem
836
  vector_db_instance = VectorDatabase(persist_directory=VECTOR_DB_PATH)
837
  rag = RAGSystem(vector_db=vector_db_instance)
838
 
839
+ # Load PDF data into the vector DB (or verify it's already loaded)
840
  rag.load_pdf(PDF_PATH)
841
 
842
+ # Get the Gradio interface object
843
  app_interface = rag.gradio_interface()
844
+ SERVER_PORT = int(os.getenv("PORT", 7860)) # Use PORT env var for Hugging Face Spaces
845
 
846
  logging.info(f"Launching Gradio app on http://0.0.0.0:{SERVER_PORT}")
847
  print(f"\n--- Gradio App Running ---\nAccess at: http://localhost:{SERVER_PORT} or your public Spaces URL\n--------------------------\n")