File size: 36,389 Bytes
983aeb4 ab2f1d4 983aeb4 1b433ca 983aeb4 c739af5 bb0db22 983aeb4 33930c1 983aeb4 9c6a431 2c04b84 33930c1 9c6a431 2c04b84 983aeb4 ab2f1d4 983aeb4 bb0db22 6b395c2 d0f303d c893ceb 983aeb4 bb0db22 d0f303d 983aeb4 bb0db22 d0f303d bb0db22 e939a33 983aeb4 bb0db22 983aeb4 2c04b84 983aeb4 2c04b84 983aeb4 33930c1 f18b1e1 b77e12e f18b1e1 33930c1 983aeb4 33930c1 f18b1e1 33930c1 983aeb4 33930c1 d8b06b3 33930c1 d8b06b3 983aeb4 33930c1 d8b06b3 33930c1 f18b1e1 8ab7769 f18b1e1 d8b06b3 f18b1e1 d8b06b3 33930c1 bbc63a5 bb0db22 db29da7 bb0db22 db29da7 bb0db22 db29da7 bb0db22 db29da7 bb0db22 db29da7 bb0db22 db29da7 bb0db22 db29da7 bb0db22 db29da7 bb0db22 db29da7 bb0db22 983aeb4 bb0db22 983aeb4 bb0db22 983aeb4 1b433ca 983aeb4 80cff10 e1bd504 1b433ca 983aeb4 80cff10 1b433ca 983aeb4 bb0db22 983aeb4 cc052ee 983aeb4 8067596 983aeb4 8067596 983aeb4 bb0db22 983aeb4 bb0db22 983aeb4 bb0db22 983aeb4 80a5c5e bb0db22 80a5c5e 1b433ca 80a5c5e bb0db22 af24b39 7c9af8a 2a57e86 3d1cb03 2a57e86 3d1cb03 37141e9 af24b39 3d1cb03 af24b39 3d1cb03 891c0e6 af24b39 3d1cb03 891c0e6 af24b39 3d1cb03 2a57e86 983aeb4 3645162 983aeb4 3645162 d0f303d 983aeb4 bb0db22 983aeb4 d0f303d 983aeb4 44a8091 bb0db22 3645162 bb0db22 bbc63a5 44a3b70 bbc63a5 44a3b70 bbc63a5 44a3b70 a1a7ed8 bb0db22 7102d87 bb0db22 983aeb4 d0f303d e939a33 8dbe5f9 e939a33 8dbe5f9 e939a33 bbc63a5 d0f303d 983aeb4 bb0db22 983aeb4 95f4c51 bbc63a5 983aeb4 bb0db22 983aeb4 d0f303d 983aeb4 d0f303d bb0db22 983aeb4 73166b8 c372914 ab2f1d4 d0f303d ab2f1d4 73166b8 ab2f1d4 73166b8 bb0db22 73166b8 c372914 ab2f1d4 c372914 ab2f1d4 c372914 bbd6d06 c372914 983aeb4 d0f303d 983aeb4 d0f303d 983aeb4 d0f303d 7b4da8e 983aeb4 d0f303d 7b4da8e d0f303d 983aeb4 57ba99b ace8864 983aeb4 2a57e86 57ba99b 2a57e86 57ba99b 2a57e86 57ba99b 2a57e86 7b4da8e 57ba99b 2a57e86 7b4da8e 2a57e86 57ba99b 2a57e86 7b4da8e 2a57e86 e939a33 2a57e86 983aeb4 bbc63a5 7b4da8e 983aeb4 ab2f1d4 983aeb4 7875cb9 423cc2a 983aeb4 423cc2a 983aeb4 423cc2a 983aeb4 423cc2a ab2f1d4 983aeb4 423cc2a 983aeb4 423cc2a 983aeb4 ace8864 73166b8 983aeb4 bbd6d06 1b433ca |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 |
import streamlit as st
import os
import json
import pandas as pd
import random
from datetime import datetime
from os.path import join
from src import (
preprocess_and_load_df,
get_from_user,
ask_question,
)
from dotenv import load_dotenv
from langchain_groq import ChatGroq
from langchain_google_genai import ChatGoogleGenerativeAI
from streamlit_feedback import streamlit_feedback
from huggingface_hub import HfApi
from datasets import load_dataset, get_dataset_config_info, Dataset
from PIL import Image
import time
import uuid
import asyncio
# Gemini API requires async
try:
asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Page config with beautiful theme
st.set_page_config(
page_title="VayuChat - AI Air Quality Assistant",
page_icon="V",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for beautiful styling
st.markdown("""
<style>
/* Clean app background */
.stApp {
background-color: #ffffff;
color: #212529;
font-family: 'Segoe UI', sans-serif;
}
/* Reduce main container padding */
.main .block-container {
padding-top: 0.5rem;
padding-bottom: 3rem;
max-width: 100%;
}
/* Remove excessive spacing */
.element-container {
margin-bottom: 0.5rem !important;
}
/* Fix sidebar spacing */
[data-testid="stSidebar"] .element-container {
margin-bottom: 0.25rem !important;
}
/* Sidebar */
[data-testid="stSidebar"] {
background-color: #f8f9fa;
border-right: 1px solid #dee2e6;
padding: 1rem;
}
/* Optimize sidebar scrolling */
[data-testid="stSidebar"] > div:first-child {
height: 100vh;
overflow-y: auto;
padding-bottom: 2rem;
}
[data-testid="stSidebar"]::-webkit-scrollbar {
width: 6px;
}
[data-testid="stSidebar"]::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 3px;
}
[data-testid="stSidebar"]::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 3px;
}
[data-testid="stSidebar"]::-webkit-scrollbar-thumb:hover {
background: #a1a1a1;
}
/* Main title */
.main-title {
text-align: center;
color: #343a40;
font-size: 2.5rem;
font-weight: 700;
margin-bottom: 0.5rem;
}
/* Subtitle */
.subtitle {
text-align: center;
color: #6c757d;
font-size: 1.1rem;
margin-bottom: 1.5rem;
}
/* Instructions */
.instructions {
background-color: #f1f3f5;
border-left: 4px solid #0d6efd;
padding: 1rem;
margin-bottom: 1.5rem;
border-radius: 6px;
color: #495057;
text-align: left;
}
/* Quick prompt buttons */
.quick-prompt-container {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 1.5rem;
padding: 1rem;
background-color: #f8f9fa;
border-radius: 10px;
border: 1px solid #dee2e6;
}
.quick-prompt-btn {
background-color: #0d6efd;
color: white;
border: none;
padding: 8px 16px;
border-radius: 20px;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.2s ease;
white-space: nowrap;
}
.quick-prompt-btn:hover {
background-color: #0b5ed7;
transform: translateY(-2px);
}
/* User message styling */
.user-message {
background: #3b82f6;
color: white;
padding: 0.75rem 1rem;
border-radius: 7px;
max-width: 95%;
}
.user-info {
font-size: 0.875rem;
opacity: 0.9;
margin-bottom: 3px;
}
/* Assistant message styling */
.assistant-message {
background: #f1f5f9;
color: #334155;
padding: 0.75rem 1rem;
border-radius: 12px;
max-width: 85%;
}
.assistant-info {
font-size: 0.875rem;
color: #6b7280;
margin-bottom: 5px;
}
/* Processing indicator */
.processing-indicator {
background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
color: #333;
padding: 1rem 1.5rem;
border-radius: 12px;
margin: 1rem 0;
margin-left: 0;
margin-right: auto;
max-width: 70%;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.7; }
100% { opacity: 1; }
}
/* Feedback box */
.feedback-section {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
padding: 1rem;
border-radius: 8px;
margin: 1rem 0;
}
/* Success and error messages */
.success-message {
background-color: #d1e7dd;
color: #0f5132;
padding: 1rem;
border-radius: 6px;
border: 1px solid #badbcc;
}
.error-message {
background-color: #f8d7da;
color: #842029;
padding: 1rem;
border-radius: 6px;
border: 1px solid #f5c2c7;
}
/* Chat input styling - Fixed alignment */
.stChatInput {
border-radius: 12px !important;
border: 5px solid #e5e7eb !important;
background: #ffffff !important;
padding: 0.75rem 1rem !important;
font-size: 1rem !important;
width: 100% !important;
max-width: none !important;
margin: 0 !important;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
transition: all 0.2s ease !important;
}
.stChatInput:focus {
border-color: #3b82f6 !important;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
outline: none !important;
}
/* Chat input container */
.stChatInput > div {
padding: 0 !important;
margin: 0 !important;
}
/* Chat input text area */
.stChatInput textarea {
border: none !important;
background: transparent !important;
padding: 0 !important;
margin: 0 !important;
font-size: 1rem !important;
line-height: 1.5 !important;
resize: none !important;
outline: none !important;
}
/* Chat input placeholder */
.stChatInput textarea::placeholder {
color: #9ca3af !important;
font-style: normal !important;
}
/* Fix the main chat input container alignment */
[data-testid="stChatInput"] {
position: fixed !important;
bottom: 0 !important;
left: 0 !important;
right: 0 !important;
background: #ffffff !important;
border-top: 1px solid #e5e7eb !important;
padding: 1rem !important;
z-index: 1000 !important;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1) !important;
}
/* Adjust main content to account for fixed chat input */
.main .block-container {
padding-bottom: 100px !important;
}
# /* Alternative: If you prefer inline chat input (not fixed) */
# /*
# [data-testid="stChatInput"] {
# background: #f8fafc !important;
# border: 1px solid #e2e8f0 !important;
# border-radius: 12px !important;
# padding: 0.75rem !important;
# margin: 1rem 0 !important;
# box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
# }
# */
/* Chat input button styling */
[data-testid="stChatInput"] button {
background: #3b82f6 !important;
color: white !important;
border: none !important;
border-radius: 12px !important;
padding: 0.5rem 1rem !important;
font-weight: 600 !important;
transition: background-color 0.2s ease !important;
}
[data-testid="stChatInput"] button:hover {
background: #2563eb !important;
}
/* Ensure proper spacing from sidebar */
@media (min-width: 768px) {
[data-testid="stChatInput"] {
margin-left: 21rem !important; /* Account for sidebar width */
}
}
/* Code container styling */
.code-container {
margin: 1rem 0;
border: 1px solid #d1d5db;
border-radius: 12px;
background: white;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.code-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.875rem 1.25rem;
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
border-bottom: 1px solid #e2e8f0;
cursor: pointer;
transition: all 0.2s ease;
border-radius: 12px 12px 0 0;
}
.code-header:hover {
background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
}
.code-title {
font-size: 0.9rem;
font-weight: 600;
color: #1e293b;
display: flex;
align-items: center;
gap: 0.5rem;
}
.code-title:before {
content: "β‘";
font-size: 0.8rem;
}
.toggle-text {
font-size: 0.75rem;
color: #64748b;
font-weight: 500;
}
.code-block {
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
color: #e2e8f0;
padding: 1.5rem;
font-family: 'SF Mono', 'Monaco', 'Menlo', 'Consolas', monospace;
font-size: 0.875rem;
overflow-x: auto;
line-height: 1.6;
border-radius: 0 0 12px 12px;
}
.answer-container {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 1.5rem;
margin: 1rem 0;
}
.answer-text {
font-size: 1.125rem;
color: #1e293b;
line-height: 1.6;
margin-bottom: 1rem;
}
.answer-highlight {
background: #fef3c7;
padding: 0.125rem 0.375rem;
border-radius: 4px;
font-weight: 600;
color: #92400e;
}
.context-info {
background: #f1f5f9;
border-left: 4px solid #3b82f6;
padding: 0.75rem 1rem;
margin: 1rem 0;
font-size: 0.875rem;
color: #475569;
}
/* Hide default menu and footer */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
/* Auto scroll */
.main-container {
height: 70vh;
overflow-y: auto;
}
</style>
""", unsafe_allow_html=True)
# JavaScript for interactions
st.markdown("""
<script>
function scrollToBottom() {
setTimeout(function() {
const mainContainer = document.querySelector('.main-container');
if (mainContainer) {
mainContainer.scrollTop = mainContainer.scrollHeight;
}
window.scrollTo(0, document.body.scrollHeight);
}, 100);
}
function toggleCode(header) {
const codeBlock = header.nextElementSibling;
const toggleText = header.querySelector('.toggle-text');
if (codeBlock.style.display === 'none') {
codeBlock.style.display = 'block';
toggleText.textContent = 'Click to collapse';
} else {
codeBlock.style.display = 'none';
toggleText.textContent = 'Click to expand';
}
}
</script>
""", unsafe_allow_html=True)
# FORCE reload environment variables
load_dotenv(override=True)
# Get API keys
Groq_Token = os.getenv("GROQ_API_KEY")
hf_token = os.getenv("HF_TOKEN")
gemini_token = os.getenv("GEMINI_TOKEN")
# Model order is decided by this
models = {
"gpt-oss-120b": "openai/gpt-oss-120b",
"qwen3-32b": "qwen/qwen3-32b",
"gpt-oss-20b": "openai/gpt-oss-20b",
"llama4 maverik":"meta-llama/llama-4-maverick-17b-128e-instruct",
"llama3.3": "llama-3.3-70b-versatile",
"deepseek-R1": "deepseek-r1-distill-llama-70b",
"gemini-2.5-flash": "gemini-2.5-flash",
"gemini-2.5-pro": "gemini-2.5-pro",
"gemini-2.5-flash-lite": "gemini-2.5-flash-lite",
"gemini-2.0-flash": "gemini-2.0-flash",
"gemini-2.0-flash-lite": "gemini-2.0-flash-lite",
# "llama4 scout":"meta-llama/llama-4-scout-17b-16e-instruct"
# "llama3.1": "llama-3.1-8b-instant"
}
self_path = os.path.dirname(os.path.abspath(__file__))
# Initialize session ID for this session
if "session_id" not in st.session_state:
st.session_state.session_id = str(uuid.uuid4())
def upload_feedback(feedback, error, output, last_prompt, code, status):
"""Enhanced feedback upload function with better logging and error handling"""
try:
if not hf_token or hf_token.strip() == "":
st.warning("Cannot upload feedback - HF_TOKEN not available")
return False
# Create comprehensive feedback data
feedback_data = {
"timestamp": datetime.now().isoformat(),
"session_id": st.session_state.session_id,
"feedback_score": feedback.get("score", ""),
"feedback_comment": feedback.get("text", ""),
"user_prompt": last_prompt,
"ai_output": str(output),
"generated_code": code or "",
"error_message": error or "",
"is_image_output": status.get("is_image", False),
"success": not bool(error)
}
# Create unique folder name with timestamp
timestamp_str = datetime.now().strftime("%Y%m%d_%H%M%S")
random_id = str(uuid.uuid4())[:8]
folder_name = f"feedback_{timestamp_str}_{random_id}"
# Create markdown feedback file
markdown_content = f"""# VayuChat Feedback Report
## Session Information
- **Timestamp**: {feedback_data['timestamp']}
- **Session ID**: {feedback_data['session_id']}
## User Interaction
**Prompt**: {feedback_data['user_prompt']}
## AI Response
**Output**: {feedback_data['ai_output']}
## Generated Code
```python
{feedback_data['generated_code']}
```
## Technical Details
- **Error Message**: {feedback_data['error_message']}
- **Is Image Output**: {feedback_data['is_image_output']}
- **Success**: {feedback_data['success']}
## User Feedback
- **Score**: {feedback_data['feedback_score']}
- **Comments**: {feedback_data['feedback_comment']}
"""
# Save markdown file locally
markdown_filename = f"{folder_name}.md"
markdown_local_path = f"/tmp/{markdown_filename}"
with open(markdown_local_path, "w", encoding="utf-8") as f:
f.write(markdown_content)
# Upload to Hugging Face
api = HfApi(token=hf_token)
# Upload markdown feedback
api.upload_file(
path_or_fileobj=markdown_local_path,
path_in_repo=f"data/{markdown_filename}",
repo_id="SustainabilityLabIITGN/VayuChat_Feedback",
repo_type="dataset",
)
# Upload image if it exists and is an image output
if status.get("is_image", False) and isinstance(output, str) and os.path.exists(output):
try:
image_filename = f"{folder_name}_plot.png"
api.upload_file(
path_or_fileobj=output,
path_in_repo=f"data/{image_filename}",
repo_id="SustainabilityLabIITGN/VayuChat_Feedback",
repo_type="dataset",
)
except Exception as img_error:
print(f"Error uploading image: {img_error}")
# Clean up local files
if os.path.exists(markdown_local_path):
os.remove(markdown_local_path)
st.success("Feedback uploaded successfully!")
return True
except Exception as e:
st.error(f"Error uploading feedback: {e}")
print(f"Feedback upload error: {e}")
return False
# Filter available models
available_models = []
model_names = list(models.keys())
groq_models = []
gemini_models = []
for model_name in model_names:
if "gemini" not in model_name:
groq_models.append(model_name)
else:
gemini_models.append(model_name)
if Groq_Token and Groq_Token.strip():
available_models.extend(groq_models)
if gemini_token and gemini_token.strip():
available_models.extend(gemini_models)
if not available_models:
st.error("No API keys available! Please set up your API keys in the .env file")
st.stop()
# Set GPT-OSS-120B as default if available
default_index = 0
if "gpt-oss-120b" in available_models:
default_index = available_models.index("gpt-oss-120b")
elif "deepseek-R1" in available_models:
default_index = available_models.index("deepseek-R1")
# Compact header - everything perfectly aligned at same height
st.markdown("""
<div style='
display: flex;
align-items: center;
justify-content: center;
padding: 0.5rem 0;
gap: 15px;
border-bottom: 1px solid
#e5e7eb;
margin-bottom: 1rem;
'>
<img src='https://sustainability-lab.github.io/images/logo_light.svg'
style='height: 80px;' />
<h1 style='
margin: 0;
font-size: 1.8rem;
font-weight: 700;
color:
#1f2937;
line-height: 100px;
'>VayuChat</h1>
<span style='
font-size: 0.9rem;
color:
#6b7280;
line-height: 100px;
font-weight: 500;
'>AI Air Quality Analysis β’ Sustainability Lab, IIT Gandhinagar</span>
</div>
""", unsafe_allow_html=True)
# Load data with caching for better performance
@st.cache_data
def load_data():
return preprocess_and_load_df(join(self_path, "Data.csv"))
try:
df = load_data()
# Data loaded silently - no success message needed
except Exception as e:
st.error(f"Error loading data: {e}")
st.stop()
inference_server = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
image_path = "IITGN_Logo.png"
# Clean sidebar
with st.sidebar:
# Model selector at top of sidebar for easy access
model_name = st.selectbox(
"π€ AI Model:",
available_models,
index=default_index,
help="Choose your AI model - easily accessible without scrolling!"
)
st.markdown("---")
# Quick Queries Section
st.markdown("### π Quick Queries")
# Load quick prompts with caching
@st.cache_data
def load_questions():
questions = []
questions_file = join(self_path, "questions.txt")
if os.path.exists(questions_file):
try:
with open(questions_file, 'r', encoding='utf-8') as f:
content = f.read()
questions = [q.strip() for q in content.split("\n") if q.strip()]
except Exception as e:
questions = []
return questions
questions = load_questions()
# Add default prompts if file doesn't exist or is empty
if not questions:
questions = [
"Which month had highest pollution?",
"Which city has worst air quality?",
"Show annual PM2.5 average",
"Plot monthly average PM2.5 for 2023",
"List all cities by pollution level",
"Compare winter vs summer pollution",
"Show seasonal pollution patterns",
"Which areas exceed WHO guidelines?",
"What are peak pollution hours?",
"Show PM10 vs PM2.5 comparison",
"Which station records highest variability in PM2.5?",
"Calculate pollution improvement rate year-over-year by city",
"Identify cities with PM2.5 levels consistently above 50 ΞΌg/mΒ³ for >6 months",
"Find correlation between PM2.5 and PM10 across different seasons and cities",
"Compare weekday vs weekend levels",
"Plot yearly trend analysis",
"Show pollution distribution by city",
"Create correlation plot between pollutants"
]
# Quick query buttons in sidebar
selected_prompt = None
# Show all questions but in a scrollable format
if len(questions) > 0:
st.markdown("**Select a question to analyze:**")
# Getting Started section with simple questions
getting_started_questions = questions[:10] # First 10 simple questions
with st.expander("π Getting Started - Simple Questions", expanded=True):
for i, q in enumerate(getting_started_questions):
if st.button(q, key=f"start_q_{i}", use_container_width=True, help=f"Analyze: {q}"):
selected_prompt = q
st.session_state.last_selected_prompt = q
# Create expandable sections for better organization
with st.expander("π NCAP Funding & Policy Analysis", expanded=False):
for i, q in enumerate([q for q in questions if any(word in q.lower() for word in ['ncap', 'funding', 'investment', 'rupee'])]):
if st.button(q, key=f"ncap_q_{i}", use_container_width=True, help=f"Analyze: {q}"):
selected_prompt = q
st.session_state.last_selected_prompt = q
with st.expander("π¬οΈ Meteorology & Environmental Factors", expanded=False):
for i, q in enumerate([q for q in questions if any(word in q.lower() for word in ['wind', 'temperature', 'humidity', 'rainfall', 'meteorological', 'monsoon', 'barometric'])]):
if st.button(q, key=f"met_q_{i}", use_container_width=True, help=f"Analyze: {q}"):
selected_prompt = q
st.session_state.last_selected_prompt = q
with st.expander("π₯ Population & Demographics", expanded=False):
for i, q in enumerate([q for q in questions if any(word in q.lower() for word in ['population', 'capita', 'density', 'exposure'])]):
if st.button(q, key=f"pop_q_{i}", use_container_width=True, help=f"Analyze: {q}"):
selected_prompt = q
st.session_state.last_selected_prompt = q
with st.expander("π Multi-Pollutant Analysis", expanded=False):
for i, q in enumerate([q for q in questions if any(word in q.lower() for word in ['ozone', 'no2', 'correlation', 'multi-pollutant', 'interaction'])]):
if st.button(q, key=f"multi_q_{i}", use_container_width=True, help=f"Analyze: {q}"):
selected_prompt = q
st.session_state.last_selected_prompt = q
with st.expander("π Other Analysis Questions", expanded=False):
remaining_questions = [q for q in questions if not any(any(word in q.lower() for word in category) for category in [
['ncap', 'funding', 'investment', 'rupee'],
['wind', 'temperature', 'humidity', 'rainfall', 'meteorological', 'monsoon', 'barometric'],
['population', 'capita', 'density', 'exposure'],
['ozone', 'no2', 'correlation', 'multi-pollutant', 'interaction']
])]
for i, q in enumerate(remaining_questions):
if st.button(q, key=f"other_q_{i}", use_container_width=True, help=f"Analyze: {q}"):
selected_prompt = q
st.session_state.last_selected_prompt = q
st.markdown("---")
# Clear Chat Button
if st.button("Clear Chat", use_container_width=True):
st.session_state.responses = []
st.session_state.processing = False
st.session_state.session_id = str(uuid.uuid4())
try:
st.rerun()
except AttributeError:
st.experimental_rerun()
# Initialize session state first
if "responses" not in st.session_state:
st.session_state.responses = []
if "processing" not in st.session_state:
st.session_state.processing = False
if "session_id" not in st.session_state:
st.session_state.session_id = str(uuid.uuid4())
def show_custom_response(response):
"""Custom response display function with improved styling"""
role = response.get("role", "assistant")
content = response.get("content", "")
if role == "user":
# User message with right alignment - reduced margins
st.markdown(f"""
<div style='display: flex; justify-content: flex-end; margin: 1rem 0;'>
<div class='user-message'>
{content}
</div>
</div>
""", unsafe_allow_html=True)
elif role == "assistant":
# Check if content is an image filename - don't display the filename text
is_image_path = isinstance(content, str) and any(ext in content for ext in ['.png', '.jpg', '.jpeg'])
# Check if content is a pandas DataFrame
import pandas as pd
is_dataframe = isinstance(content, pd.DataFrame)
# Check for errors first and display them with special styling
error = response.get("error")
timestamp = response.get("timestamp", "")
timestamp_display = f" β’ {timestamp}" if timestamp else ""
if error:
st.markdown(f"""
<div style='display: flex; justify-content: flex-start; margin: 1rem 0;'>
<div class='assistant-message'>
<div class='assistant-info'>VayuChat{timestamp_display}</div>
<div class='error-message'>
β οΈ <strong>Error:</strong> {error}
<br><br>
<em>π‘ Try rephrasing your question or being more specific about what you'd like to analyze.</em>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# Assistant message with left alignment - reduced margins
elif not is_image_path and not is_dataframe:
st.markdown(f"""
<div style='display: flex; justify-content: flex-start; margin: 1rem 0;'>
<div class='assistant-message'>
<div class='assistant-info'>VayuChat{timestamp_display}</div>
{content if isinstance(content, str) else str(content)}
</div>
</div>
""", unsafe_allow_html=True)
elif is_dataframe:
# Display DataFrame with nice formatting
st.markdown(f"""
<div style='display: flex; justify-content: flex-start; margin: 1rem 0;'>
<div class='assistant-message'>
<div class='assistant-info'>VayuChat{timestamp_display}</div>
Here are the results:
</div>
</div>
""", unsafe_allow_html=True)
# Add context info for dataframes
st.markdown("""
<div class='context-info'>
π‘ This table is interactive - click column headers to sort, or scroll to view all data.
</div>
""", unsafe_allow_html=True)
st.dataframe(content, use_container_width=True)
# Show generated code with Streamlit expander
if response.get("gen_code"):
with st.expander("π View Generated Code", expanded=False):
st.code(response["gen_code"], language="python")
# Try to display image if content is a file path
try:
if isinstance(content, str) and (content.endswith('.png') or content.endswith('.jpg')):
if os.path.exists(content):
# Display image without showing filename
st.image(content, width=800)
return {"is_image": True}
# Also handle case where content shows filename but we want to show image
elif isinstance(content, str) and any(ext in content for ext in ['.png', '.jpg']):
# Extract potential filename from content
import re
filename_match = re.search(r'([^/\\]+\.(?:png|jpg|jpeg))', content)
if filename_match:
filename = filename_match.group(1)
if os.path.exists(filename):
st.image(filename, width=800)
return {"is_image": True}
except:
pass
return {"is_image": False}
# Chat history
# Display chat history
for response_id, response in enumerate(st.session_state.responses):
status = show_custom_response(response)
# Show feedback section for assistant responses
if response["role"] == "assistant":
feedback_key = f"feedback_{int(response_id/2)}"
error = response.get("error", "")
output = response.get("content", "")
last_prompt = response.get("last_prompt", "")
code = response.get("gen_code", "")
# Beautiful action bar with feedback and retry
st.markdown('<div style="margin: 1.5rem 0 0.5rem 0;"></div>', unsafe_allow_html=True) # Spacer
if "feedback" in st.session_state.responses[response_id]:
# Show submitted feedback nicely
feedback_data = st.session_state.responses[response_id]["feedback"]
col1, col2 = st.columns([3, 1])
with col1:
st.markdown(f"""
<div style='
background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
border: 1px solid #a7f3d0;
border-radius: 8px;
padding: 0.75rem 1rem;
display: flex;
align-items: center;
gap: 8px;
'>
<span style='font-size: 1.1rem;'>{feedback_data.get('score', '')}</span>
<span style='color: #059669; font-weight: 500; font-size: 0.9rem;'>
Thanks for your feedback!
</span>
</div>
""", unsafe_allow_html=True)
with col2:
if st.button("π Retry", key=f"retry_{response_id}", use_container_width=True):
user_prompt = ""
if response_id > 0:
user_prompt = st.session_state.responses[response_id-1].get("content", "")
if user_prompt:
if response_id > 0:
retry_prompt = st.session_state.responses[response_id-1].get("content", "")
del st.session_state.responses[response_id]
del st.session_state.responses[response_id-1]
st.session_state.follow_up_prompt = retry_prompt
st.rerun()
else:
# Clean feedback and retry layout
col1, col2, col3, col4 = st.columns([2, 2, 1, 1])
with col1:
if st.button("β¨ Excellent", key=f"{feedback_key}_excellent", use_container_width=True):
feedback = {"score": "β¨ Excellent", "text": ""}
st.session_state.responses[response_id]["feedback"] = feedback
st.rerun()
with col2:
if st.button("π§ Needs work", key=f"{feedback_key}_poor", use_container_width=True):
feedback = {"score": "π§ Needs work", "text": ""}
st.session_state.responses[response_id]["feedback"] = feedback
st.rerun()
with col4:
if st.button("π Retry", key=f"retry_{response_id}", use_container_width=True):
user_prompt = ""
if response_id > 0:
user_prompt = st.session_state.responses[response_id-1].get("content", "")
if user_prompt:
if response_id > 0:
retry_prompt = st.session_state.responses[response_id-1].get("content", "")
del st.session_state.responses[response_id]
del st.session_state.responses[response_id-1]
st.session_state.follow_up_prompt = retry_prompt
st.rerun()
# Chat input with better guidance
prompt = st.chat_input("π¬ Ask about air quality trends, pollution analysis, or city comparisons...", key="main_chat")
# Handle selected prompt from quick prompts
if selected_prompt:
prompt = selected_prompt
# Handle follow-up prompts from quick action buttons
if st.session_state.get("follow_up_prompt") and not st.session_state.get("processing"):
prompt = st.session_state.follow_up_prompt
st.session_state.follow_up_prompt = None # Clear the follow-up prompt
# Handle new queries
if prompt and not st.session_state.get("processing"):
# Prevent duplicate processing
if "last_prompt" in st.session_state:
last_prompt = st.session_state["last_prompt"]
last_model_name = st.session_state.get("last_model_name", "")
if (prompt == last_prompt) and (model_name == last_model_name):
prompt = None
if prompt:
# Add user input to chat history
user_response = get_from_user(prompt)
st.session_state.responses.append(user_response)
# Set processing state
st.session_state.processing = True
st.session_state.current_model = model_name
st.session_state.current_question = prompt
# Rerun to show processing indicator
st.rerun()
# Process the question if we're in processing state
if st.session_state.get("processing"):
# Enhanced processing indicator like Claude Code
st.markdown("""
<div style='padding: 1rem; text-align: center; background: #f8fafc; border-radius: 8px; margin: 1rem 0;'>
<div style='display: flex; align-items: center; justify-content: center; gap: 0.5rem; color: #475569;'>
<div style='font-weight: 500;'>π€ Processing with """ + str(st.session_state.get('current_model', 'Unknown')) + """</div>
<div class='dots' style='display: inline-flex; gap: 2px;'>
<div class='dot' style='width: 4px; height: 4px; background: #3b82f6; border-radius: 50%; animation: bounce 1.4s infinite ease-in-out;'></div>
<div class='dot' style='width: 4px; height: 4px; background: #3b82f6; border-radius: 50%; animation: bounce 1.4s infinite ease-in-out; animation-delay: 0.16s;'></div>
<div class='dot' style='width: 4px; height: 4px; background: #3b82f6; border-radius: 50%; animation: bounce 1.4s infinite ease-in-out; animation-delay: 0.32s;'></div>
</div>
</div>
<div style='font-size: 0.75rem; color: #6b7280; margin-top: 0.25rem;'>Analyzing data and generating response...</div>
</div>
<style>
@keyframes bounce {
0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
40% { transform: scale(1.2); opacity: 1; }
}
</style>
""", unsafe_allow_html=True)
prompt = st.session_state.get("current_question")
model_name = st.session_state.get("current_model")
try:
response = ask_question(model_name=model_name, question=prompt)
if not isinstance(response, dict):
response = {
"role": "assistant",
"content": "Error: Invalid response format",
"gen_code": "",
"ex_code": "",
"last_prompt": prompt,
"error": "Invalid response format",
"timestamp": datetime.now().strftime("%H:%M")
}
response.setdefault("role", "assistant")
response.setdefault("content", "No content generated")
response.setdefault("gen_code", "")
response.setdefault("ex_code", "")
response.setdefault("last_prompt", prompt)
response.setdefault("error", None)
response.setdefault("timestamp", datetime.now().strftime("%H:%M"))
except Exception as e:
response = {
"role": "assistant",
"content": f"Sorry, I encountered an error: {str(e)}",
"gen_code": "",
"ex_code": "",
"last_prompt": prompt,
"error": str(e),
"timestamp": datetime.now().strftime("%H:%M")
}
st.session_state.responses.append(response)
st.session_state["last_prompt"] = prompt
st.session_state["last_model_name"] = model_name
st.session_state.processing = False
# Clear processing state
if "current_model" in st.session_state:
del st.session_state.current_model
if "current_question" in st.session_state:
del st.session_state.current_question
st.rerun()
# Close chat container
st.markdown("</div>", unsafe_allow_html=True)
# Minimal auto-scroll - only scroll when processing
if st.session_state.get("processing"):
st.markdown("<script>scrollToBottom();</script>", unsafe_allow_html=True)
# Dataset Info Section (matching mockup)
st.markdown("### Dataset Info")
st.markdown("""
<div style='background: #f1f5f9; border-radius: 8px; padding: 1rem; margin-bottom: 1rem;'>
<h4 style='margin: 0 0 0.5rem 0; color: #1e293b; font-size: 0.9rem;'>PM2.5 Air Quality Data</h4>
<p style='margin: 0; font-size: 0.75rem; color: #475569;'><strong>Time Range:</strong> 2022 - 2023</p>
<p style='margin: 0; font-size: 0.75rem; color: #475569;'><strong>Locations:</strong> 300+ cities across India</p>
<p style='margin: 0; font-size: 0.75rem; color: #475569;'><strong>Records:</strong> 100,000+ measurements</p>
</div>
""", unsafe_allow_html=True) |