File size: 13,716 Bytes
c114fc1
 
18bcedb
c114fc1
 
 
18bcedb
7612318
 
 
 
 
 
 
 
 
 
c114fc1
 
339d432
d7dc7e0
18bcedb
7612318
a33d4cf
 
61ffd62
60e8286
738f5e4
18bcedb
c114fc1
18bcedb
8faaeb8
7612318
 
 
 
 
 
 
c114fc1
 
 
3eacb93
c114fc1
 
 
 
 
 
 
 
9b22b06
c114fc1
 
 
 
 
7612318
 
 
 
c114fc1
25414e5
7612318
 
 
 
c114fc1
 
 
 
 
 
 
 
 
 
a642583
151e051
a642583
7612318
 
0689f85
 
151e051
d7dc7e0
7612318
 
 
 
18bcedb
 
d7dc7e0
7612318
 
 
 
 
 
 
 
 
 
c114fc1
18bcedb
c114fc1
18bcedb
 
 
7612318
18bcedb
 
 
 
 
 
 
 
 
 
 
7612318
18bcedb
 
 
 
7612318
 
18bcedb
 
 
 
7612318
 
 
 
 
 
 
 
18bcedb
 
 
 
 
 
 
c114fc1
18bcedb
c114fc1
18bcedb
c114fc1
18bcedb
 
 
d7dc7e0
18bcedb
d7dc7e0
18bcedb
d7dc7e0
18bcedb
 
7612318
18bcedb
7612318
18bcedb
 
7612318
 
18bcedb
 
7612318
 
 
 
 
 
 
18bcedb
7612318
18bcedb
 
7612318
18bcedb
7612318
18bcedb
 
 
 
 
7612318
18bcedb
 
 
 
7612318
18bcedb
 
 
 
 
 
7612318
 
 
18bcedb
 
 
7612318
18bcedb
7612318
18bcedb
 
7612318
 
 
18bcedb
 
 
7612318
18bcedb
 
 
7612318
18bcedb
151e051
 
7612318
 
 
18bcedb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8faaeb8
7612318
 
 
8faaeb8
 
18bcedb
 
 
 
 
 
 
7612318
 
18bcedb
c114fc1
 
 
76dd8fd
07bfeb2
c114fc1
 
 
25414e5
151e051
dafc314
35d6de6
c114fc1
 
 
66b4d7d
c114fc1
c7cd7b8
 
 
ee98be0
 
 
 
c114fc1
ee98be0
7612318
18bcedb
 
 
 
8faaeb8
 
 
 
18bcedb
 
8faaeb8
18bcedb
 
 
 
 
 
 
f9b3adf
7612318
18bcedb
25414e5
7612318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a33d4cf
 
 
 
 
7612318
 
a33d4cf
 
7612318
a33d4cf
 
7612318
42617a2
a33d4cf
25414e5
18bcedb
 
 
 
 
 
7612318
18bcedb
 
 
7612318
 
18bcedb
7612318
 
18bcedb
 
 
846b42b
 
7612318
 
 
 
a33d4cf
 
846b42b
 
18bcedb
846b42b
d7dc7e0
18bcedb
 
dc47a9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7612318
 
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
import streamlit as st
import os
import json
import pandas as pd
import random
from os.path import join
from datetime import datetime
from src import (
    preprocess_and_load_df,
    load_agent,
    ask_agent,
    decorate_with_code,
    show_response,
    get_from_user,
    load_smart_df,
    ask_question,
)
from dotenv import load_dotenv
from langchain_groq.chat_models import ChatGroq
from langchain_google_genai import GoogleGenerativeAI
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

st.set_page_config(layout="wide")

# Load environment variables : Groq and Hugging Face API keys
load_dotenv()
Groq_Token = os.environ["GROQ_API_KEY"]
hf_token = os.environ["HF_TOKEN"]
gemini_token = os.environ["GEMINI_TOKEN"]
models = {
    "llama3": "llama3-70b-8192",
    "mixtral": "mixtral-8x7b-32768",
    "llama2": "llama2-70b-4096",
    "gemma": "gemma-7b-it",
    "gemini-pro": "gemini-pro",
}

self_path = os.path.dirname(os.path.abspath(__file__))


# Using HTML and CSS to center the title
st.write(
    """
    <style>
    .title {
        text-align: center;
        color: #17becf;
    }
    </style>
""",
    unsafe_allow_html=True,
)

# Displaying the centered title
st.markdown(
    "<div style='text-align:center; padding: 20px;'>VayuBuddy makes pollution monitoring easier by bridging the gap between users and datasets.<br>No coding required—just meaningful insights at your fingertips!</div>",
    unsafe_allow_html=True,
)

# Center-aligned instruction text with bold formatting
st.markdown(
    "<div style='text-align:center;'>Choose a query from <b>Select a prompt</b> or type a query in the <b>chat box</b>, select a <b>LLM</b> (Large Language Model), and press enter to generate a response.</div>",
    unsafe_allow_html=True,
)
# os.environ["PANDASAI_API_KEY"] = "$2a$10$gbmqKotzJOnqa7iYOun8eO50TxMD/6Zw1pLI2JEoqncwsNx4XeBS2"

# with open(join(self_path, "context1.txt")) as f:
#     context = f.read().strip()

# agent = load_agent(join(self_path, "app_trial_1.csv"), context)
# df = preprocess_and_load_df(join(self_path, "Data.csv"))
# inference_server = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
# inference_server = "https://api-inference.huggingface.co/models/codellama/CodeLlama-13b-hf"
# inference_server = "https://api-inference.huggingface.co/models/pandasai/bamboo-llm"

image_path = "IITGN_Logo.png"

# Display images and text in three columns with specified ratios
col1, col2, col3 = st.sidebar.columns((1.0, 2, 1.0))
with col2:
    st.image(image_path, use_column_width=True)
    st.markdown("<h1 class='title'>VayuBuddy</h1>", unsafe_allow_html=True)


model_name = st.sidebar.selectbox("Select LLM:", ["llama3", "mixtral", "gemma", "gemini-pro"])

questions = ["Custom Prompt"]
with open(join(self_path, "questions.txt")) as f:
    questions += f.read().split("\n")

waiting_lines = (
    "Thinking...",
    "Just a moment...",
    "Let me think...",
    "Working on it...",
    "Processing...",
    "Hold on...",
    "One moment...",
    "On it...",
)

# agent = load_agent(df, context="", inference_server=inference_server, name=model_name)

# Initialize chat history
if "responses" not in st.session_state:
    st.session_state.responses = []

### Old code for feedback
# def push_to_dataset(feedback, comments,output,code,error):
#     # Load existing dataset or create a new one if it doesn't exist
#     try:
#         ds = load_dataset("YashB1/Feedbacks_eoc", split="evaluation")
#     except FileNotFoundError:
#         # If dataset doesn't exist, create a new one
#         ds = Dataset.from_dict({"feedback": [], "comments": [], "error": [], "output": [], "code": []})

#     # Add new feedback to the dataset
#     new_data = {"feedback": [feedback], "comments": [comments], "error": [error], "output": [output], "code": [code]}  # Convert feedback and comments to lists
#     new_data = Dataset.from_dict(new_data)

#     ds = concatenate_datasets([ds, new_data])

#     # Push the updated dataset to Hugging Face Hub
#     ds.push_to_hub("YashB1/Feedbacks_eoc", split="evaluation")


def upload_feedback():
    print("Uploading feedback")
    data = {
        "feedback": feedback["score"],
        "comment": feedback["text"],
        "error": error,
        "output": output,
        "prompt": last_prompt,
        "code": code,
    }

    # generate a random file name based on current time-stamp: YYYY-MM-DD_HH-MM-SS
    random_folder_name = str(datetime.now()).replace(" ", "_").replace(":", "-").replace(".", "-")
    print("Random folder:", random_folder_name)
    save_path = f"/tmp/vayubuddy_feedback.md"
    path_in_repo = f"data/{random_folder_name}/feedback.md"
    with open(save_path, "w") as f:
        template = f"""Prompt: {last_prompt}

Output: {output}

Code: 

```py
{code}
```

Error: {error}

Feedback: {feedback['score']}

Comments: {feedback['text']}
        """

        print(template, file=f)

    api = HfApi(token=hf_token)
    api.upload_file(
        path_or_fileobj=save_path,
        path_in_repo=path_in_repo,
        repo_id="SustainabilityLabIITGN/VayuBuddy_Feedback",
        repo_type="dataset",
    )
    if status["is_image"]:
        api.upload_file(
            path_or_fileobj=output,
            path_in_repo=f"data/{random_folder_name}/plot.png",
            repo_id="SustainabilityLabIITGN/VayuBuddy_Feedback",
            repo_type="dataset",
        )

    print("Feedback uploaded successfully!")


# Display chat responses from history on app rerun
print("#" * 10)
for response_id, response in enumerate(st.session_state.responses):
    status = show_response(st, response)
    if response["role"] == "assistant":
        feedback_key = f"feedback_{int(response_id/2)}"
        print("response_id", response_id, "feedback_key", feedback_key)

        error = response["error"]
        output = response["content"]
        last_prompt = response["last_prompt"]
        code = response["gen_code"]

        if "feedback" in st.session_state.responses[response_id]:
            st.write("Feedback:", st.session_state.responses[response_id]["feedback"])
        else:
            ## !!! This does on work on Safari !!!
            # feedback = streamlit_feedback(feedback_type="thumbs",
            #     optional_text_label="[Optional] Please provide extra information", on_submit=upload_feedback, key=feedback_key)

            # Display thumbs up/down buttons for feedback
            thumbs = st.radio("We would appreciate your feedback!", ("👍", "👎"), index=None, key=feedback_key)

            if thumbs:
                # Text input for comments
                comments = st.text_area("[Optional] Please provide extra information", key=feedback_key + "_comments")
                feedback = {"score": thumbs, "text": comments}
                if st.button("Submit", on_click=upload_feedback, key=feedback_key + "_submit"):
                    st.session_state.responses[response_id]["feedback"] = feedback
                    st.success("Feedback uploaded successfully!")


print("#" * 10)

show = True
prompt = st.sidebar.selectbox("Select a Prompt:", questions, key="prompt_key")
if prompt == "Custom Prompt":
    show = False
    # React to user input
    prompt = st.chat_input("Ask me anything about air quality!", key=1000)
    if prompt:
        show = True
else:
    # placeholder for chat input
    st.chat_input(
        "Select 'Select a Prompt' -> 'Custom Prompt' in the sidebar to ask your own questions.", key=1000, disabled=True
    )

if "last_prompt" in st.session_state:
    last_prompt = st.session_state["last_prompt"]
    last_model_name = st.session_state["last_model_name"]
    if (prompt == last_prompt) and (model_name == last_model_name):
        show = False

if prompt:
    st.sidebar.info("Select 'Custom Prompt' to ask your own questions.")

    if show:
        # Add user input to chat history
        user_response = get_from_user(prompt)
        st.session_state.responses.append(user_response)

        # select random waiting line
        with st.spinner(random.choice(waiting_lines)):
            ran = False
            for i in range(1):
                print(f"Attempt {i+1}")
                if model_name == "gemini-pro":
                    llm = GoogleGenerativeAI(
                        model=models[model_name], google_api_key=os.getenv("GEMINI_TOKEN"), temperature=0
                    )
                else:
                    llm = ChatGroq(model=models[model_name], api_key=os.getenv("GROQ_API"), temperature=0)

                df_check = pd.read_csv("Data.csv")
                df_check["Timestamp"] = pd.to_datetime(df_check["Timestamp"])
                df_check = df_check.head(5)

                new_line = "\n"

                parameters = {"font.size": 12, "figure.dpi": 600}

                template = f"""```python
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams.update({parameters})

df = pd.read_csv("Data.csv")
df["Timestamp"] = pd.to_datetime(df["Timestamp"])

import geopandas as gpd
india = gpd.read_file("https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson")
india.loc[india['ST_NM'].isin(['Ladakh', 'Jammu & Kashmir']), 'ST_NM'] = 'Jammu and Kashmir'
import uuid
# df.dtypes
{new_line.join(map(lambda x: '# '+x, str(df_check.dtypes).split(new_line)))}

{new_line.join(['# '+line for line in prompt.strip().split(new_line)])}
"""
                with open("system_prompt.txt") as f:
                    system_prompt = f.read().strip()
                query = f"""{system_prompt}
                
                Complete the following code.

                {template}

                """

                answer = None
                code = None
                error = None
                try:
                    if model_name == "gemini-pro":
                        answer = llm.invoke(query)
                    else:
                        answer = llm.invoke(query).content
                    code = f"""
                    {template.split("```python")[1].split("```")[0]}
                    {answer.split("```python")[1].split("```")[0]}
                    """
                    # update variable `answer` when code is executed
                    exec(code)
                    ran = True
                except Exception as e:
                    error = e
                    if code is not None:
                        answer = f"Error executing the code...\n\n{e}"

                if type(answer) != str:
                    answer = f"!!!Faced an error while working on your query. Please try again!!!"

                response = {
                    "role": "assistant",
                    "content": answer,
                    "gen_code": code,
                    "ex_code": code,
                    "last_prompt": prompt,
                    "error": error,
                }

                try:
                    print("Trying to open image", answer)
                    img = Image.open(answer)
                    print("Image opened")
                    image = answer
                    answer = None
                except:
                    image = None

                item = {
                    "prompt": prompt,
                    "code": code,
                    "answer": answer,
                    "error": error,
                    "model": model_name,
                    "image": image,
                }

                # Update to HuggingFace dataset
                dataset_config = get_dataset_config_info("SustainabilityLabIITGN/VayuBuddy_logs", token=hf_token)
                splits = dataset_config.splits
                last_split = list(splits.keys())[-1]
                last_split_size = splits[last_split].num_examples

                ds = load_dataset("SustainabilityLabIITGN/VayuBuddy_logs", token=hf_token, split=last_split)
                if last_split_size >= 100:
                    current_split = str(int(last_split) + 1)
                    ds = Dataset.from_list([item], features=ds.features)
                else:
                    current_split = last_split
                    ds = ds.add_item(item)

                ds.push_to_hub("SustainabilityLabIITGN/VayuBuddy_logs", split=current_split, token=hf_token)

                # Get response from agent
                # response = ask_question(model_name=model_name, question=prompt)
                # response = ask_agent(agent, prompt)

                if ran:
                    break

        # Append agent response to chat history
        st.session_state.responses.append(response)

        st.session_state["last_prompt"] = prompt
        st.session_state["last_model_name"] = model_name
        st.rerun()


# contact details
contact_details = """
**Feel free to reach out to us:**
- [Zeel B Patel](https://patel-zeel.github.io/)
  (PhD Student, IIT Gandhinagar)
- Vinayak Rana
  (Developer, IIT Gandhinagar)
- Nitish Sharma
  (Developer, Independent Contributor)
- Yash J Bachwana
  (Developer, IIT Gandhinagar)
- [Nipun Batra](https://nipunbatra.github.io/)
  (Faculty, IIT Gandhinagar)
"""


# Display contact details with message
st.sidebar.markdown("<hr>", unsafe_allow_html=True)
st.sidebar.markdown(contact_details, unsafe_allow_html=True)


st.markdown(
    """
    <style>
    .sidebar .sidebar-content {
        position: sticky;
        top: 0;
        height: 100vh;
        overflow-y: auto;
        overflow-x: hidden;
    }
    </style>
    """,
    unsafe_allow_html=True,
)