Building Weather Data Navigator with Lyzr’s DataAnalyzr Agent
Tags: lyzr, genai, insight, data
Published: 2024-04-02 18:51:22

In today’s data-driven world, extracting insights from **complex datasets** is essential for informed decision-making. Weather data, in particular, holds immense potential for various industries, from agriculture to energy management. However, analyzing **weather data** can be daunting, requiring specialized tools and expertise.

To address this challenge, we’ve developed a Streamlit app powered by **Lyzr’s DataAnalyzr agent**. This innovative tool streamlines the process of uploading, analyzing, and uncovering insights from weather data, making data analytics accessible to everyone, regardless of their technical background.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4k0j264ei5qhaaj227x.png)
In this blog post, we’ll take you on a journey through the **Weather Data Navigator app**, highlighting its intuitive interface, robust analytical capabilities, and transformative impact across diverse sectors.

**Why use Lyzr SDK’s?**

With Lyzr SDKs, crafting your own **GenAI** application is a breeze, requiring only a few lines of code to get up and running swiftly.

[Checkout the Lyzr SDK’s](https://docs.lyzr.ai/homepage)

**Lets get Started!**
Create a new file **app.py** and use that

```
import os
import streamlit as st
from utils import utils
from lyzr import DataConnector, DataAnalyzr
```
Next Set Up **OpenAI API Key** and using Streamlit’s secrets management, set up the OpenAI API key within your Streamlit application. Replace "OPENAI_API_KEY" with the actual key name defined in your Streamlit secrets where your OpenAI API key is stored.

```
openai.api_key = st.secrets["OPENAI_API_KEY"]
```

```
def data_uploader():
    st.subheader("Upload Weather Data file")
    # Upload csv file
    uploaded_file = st.file_uploader("Choose csv file", type=["csv"])
    if uploaded_file is not None:
        utils.save_uploaded_file(uploaded_file)
    else:
        utils.remove_existing_files(data)
        utils.remove_existing_files(plot)
```
The **data_uploader()** function within the Python script facilitates the seamless uploading of weather data files in **CSV format** within a **Streamlit** application. Beginning with a descriptive subheader titled "Upload Weather Data file," the function guides users through the process.

Leveraging Streamlit's **file_uploader** widget, users are prompted to select a CSV file containing weather data, ensuring compatibility for subsequent analysis. Upon successful file upload, the function saves the uploaded **CSV file** using a utility function.

```
def analyzr():
    path = utils.get_files_in_directory(data)
    path = path[0]

    dataframe = DataConnector().fetch_dataframe_from_csv(file_path=Path(path))
    analyzr_instance = DataAnalyzr(df=dataframe, api_key=st.secrets["apikey"])

    return analyzr_instance
```
The **analyzr()** function in the Python script plays a pivotal role in conducting data analysis within the Streamlit application. It begins by retrieving the file path of the uploaded weather data file and then proceeds to load this data into a structured DataFrame using a custom utility function.

Once initialized, the function returns the **analyzr_instance**, which encapsulates the necessary data and methods for conducting further analysis on the weather data, enabling users to derive valuable insights and make informed decisions.

```
def file_checker():
    file = []
    for filename in os.listdir(data):
        file_path = os.path.join(data, filename)
        file.append(file_path)

    return file
```
The **file_checker()** function systematically examines the designated directory where **weather data files** are expected to reside. By iterating through each file within this directory, it constructs the complete file path for each entry, ensuring comprehensive coverage.

Once all file paths are collected and appended to a list, the function returns this list, providing a comprehensive catalog of available weather data files for further processing within the application.

```
# Function to display the dataset description
def display_description(analyzr):
    description = analyzr.dataset_description()
    if description is not None:
        st.subheader("Dataset Description:")
        st.write(description)
```
The **display_description()** function is designed to present the description of the dataset, leveraging the capabilities of the analyzr object. It first retrieves the dataset description using the **dataset_description()** method from the analyzr object. If a description is available (not None), it proceeds to display it within the Streamlit app interface, under the subheader "Dataset Description."

This function provides users with essential information about the dataset, aiding in their understanding and interpretation of the data being analyzed.

```
# Function to display queries
def display_queries(analyzr):
    queries = analyzr.ai_queries_df()
    if queries is not None:
        st.subheader("These Queries you can run on the data:")
        st.write(queries)
```
The **display_queries()** function serves to showcase the queries that users can execute on the dataset, utilizing functionalities offered by the analyzr object. It begins by retrieving the queries using the **ai_queries_df()** method from the analyzr object.

If queries are available (not None), it proceeds to display them within the Streamlit app interface, presented under the subheader "These Queries you can run on the data." This function empowers users with a selection of pre-defined queries, facilitating their exploration and analysis of the dataset with ease.

```
if __name__ == "__main__":
    style_app()
    st.sidebar.title("Weather Data Navigator")
    selection = st.sidebar.radio("Go to", ["Data", "Analysis"])

    if selection == "Data":
        data_uploader()
    elif selection == "Analysis":
        file = file_checker()
        if len(file) > 0:
            analyzr = analyzr()

            # Create buttons for the options
            if st.button("Data Description"):
                display_description(analyzr)
            if st.button("Generate Queries"):
                display_queries(analyzr)
        
        else:
            st.error("Please upload a CSV file")
```
The conditional block starting with if __name__ == "__main__": serves as the entry point for executing the **main** functionality of the script.

It begins by applying custom styling to the Streamlit app interface using the **style_app()** function. Then, it constructs a sidebar titled "Weather Data Navigator" and provides users with options to navigate between "Data" and "Analysis" sections.

If the user selects “Data,” the script invokes the **data_uploader()** function to facilitate uploading of weather data files. On the other hand, if "Analysis" is chosen, the script checks for the presence of uploaded files using the **file_checker()** function. If files are found, it proceeds to initialize the analyzr object and offers options to display dataset descriptions and generate queries using the **display_description()** and **display_queries()** functions, respectively.

In case no files are uploaded, it displays an error message prompting the user to upload a **CSV file**.This conditional block orchestrates the flow of the Streamlit application, ensuring a seamless user experience and enabling efficient interaction with **weather data** for both data upload and analysis.

With the **Weather Data Navigator app**, we aim to democratize data analytics and empower users to unlock the full potential of weather data. Whether you’re a seasoned data scientist or a novice user, our app provides the tools and insights you need to make informed decisions in a rapidly changing world.

Experience the power of data analytics with **Lyzr’s DataAnalyzr agent** and take your weather data analysis to new heights.

Try our **Weather Data Navigator app** today and embark on a journey of discovery and innovation.

Youtube Link: https://www.youtube.com/watch?v=J_Pzmo2WN4I

App link:https://weather-data-navigator-lyzr.streamlit.app/

Source Code:https://github.com/isakshay007/Weather-Data-Navigator

**Connect with Lyzr**
To learn more about Lyzr and its SDK’s, visit our website or get in touch with our team:

**Website**: [Lyzr.ai](https://www.lyzr.ai/)
**Book a Demo**: [Book a Demo](https://www.lyzr.ai/book-demo/)
**Discord**: [Join our Discord community](https://discord.com/invite/nm7zSyEFA2)
**Slack**: [Join our Slack channel](https://anybodycanai.slack.com/join/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw#/shared-invite/email)