File size: 5,443 Bytes
5356b03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import openai
import json
import requests
import streamlit as st
#from dotenv import load_dotenv

# Set API keys
openai.api_key = os.environ['OPENAI_API_KEY']
OPENWEATHER_API_KEY = os.environ['OPENWEATHER_API_KEY']

# Function to get the current weather
def get_current_weather(location):
    """Get the current weather in a given location"""
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    complete_url = f"{base_url}appid={OPENWEATHER_API_KEY}&q={location}"

    response = requests.get(complete_url)

    if response.status_code == 200:
        data = response.json()
        weather = data['weather'][0]['main']
        temperature = data['main']['temp'] - 273.15  # Convert Kelvin to Celsius
        return {
            "city": location,
            "weather": weather,
            "temperature": round(temperature, 2)
        }
    else:
        return {"city": location, "weather": "Data Fetch Error", "temperature": "N/A"}

# Streamlit app
st.title("Weather Info Assistant")
#st.write("Get the current weather information for a specific location. Just replace Gurgaon with the location")

user_input = st.text_input("Get the current weather information for a specific location. Just replace Gurgaon with the location", "What is the weather like in Gurgaon?")

if st.button("Get Weather"):
    # Use GPT-3.5-turbo to parse the user query
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {
                "role": "user",
                "content": user_input
            }
        ],
        temperature=0,
        max_tokens=300,
        functions=[
            {
                "name": "get_current_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                    },
                    "required": ["location"],
                },
            }
        ],
        function_call="auto"
    )

    # Extract the location from the response
    try:
        # Extract the function call information
        function_call_info = response.choices[0].message.function_call
        function_name = function_call_info.name  # This should be 'get_current_weather'
        function_arguments = function_call_info.arguments  # This is a JSON string

        # Parse the JSON string to get the arguments dictionary
        args = json.loads(function_arguments)
        location = args['location']

        # Now you can fetch the weather information using the extracted location
        weather_info = get_current_weather(location)

        # Define a dictionary to map weather conditions to emoticons
        weather_icons = {
            "Clear": "☀️",  # Sun icon
            "Clouds": "☁️",  # Cloud icon
            "Rain": "🌧️",  # Rain icon
            "Snow": "❄️",  # Snow icon
            "Thunderstorm": "⛈️",  # Thunderstorm icon
            "Mist": "🌫️",  # Fog icon
            "Smoke": "💨",  # Smoke icon
            "Haze": "🌫️",  # Haze icon
            "Dust": "🌪️",  # Dust icon
            "Fog": "🌫️",  # Fog icon
            "Sand": "🏜️",  # Sand icon
            "Ash": "🌋",  # Volcanic ash icon
            "Squall": "🌬️",  # Wind face icon
            "Tornado": "🌪️"  # Tornado icon
        }

        if weather_info["weather"] != "Data Fetch Error":
            icon = weather_icons.get(weather_info["weather"], "❓")  # Default to question mark if no match
            weather_description = f"The weather in **{weather_info['city']}** is currently `{weather_info['weather']}` with a temperature of `{weather_info['temperature']}°C`."
            chat_response = openai.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {
                        "role": "system",
                        "content": "Generate a conversational response for weather information. Please include the weather and temperature details in the response and provide suggestion on things that can be done best in this weather"
                    },
                    {
                        "role": "user",
                        "content": weather_description
                    }
                ],
                temperature=0.5,
                max_tokens=300
            )
                        
            # Use HTML to style the font size, color, and include the icon in the displayed message
            st.markdown(f"<div style='font-size: 24px; color: blue; font-weight: bold;'> Weather: {weather_info['weather']} {icon} &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Temperature: {weather_info['temperature']}°C</div>", unsafe_allow_html=True)
            st.markdown(f"<div style='font-size: 20px;'> {chat_response.choices[0].message.content}", unsafe_allow_html=True)
        else:
            st.markdown(f"<div style='font-size: 20px;'>**Could not fetch weather data for {weather_info['city']}. Please try again.**</div>", unsafe_allow_html=True)
    except Exception as e:
        print(f"Error processing the response or fetching the weather: {e}")