File size: 8,744 Bytes
4273015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64a88cb
7e0e980
4273015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
import gradio as gr
import os
import requests
import openai
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize OpenAI client your openai key
openai.api_key = os.getenv('OPENAI_API_KEY')


def get_current_weather(location, unit='celsius'):
    weather_api_key = userdata.get('WEATHER_API_KEY')
    base_url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={weather_api_key}&units=metric"
    response = requests.get(base_url)
    data = response.json()

    weather_description = data['weather'][0]['description']
    return {
        "location": location,
        "temperature": data['main']['temp'],
        "weather": weather_description
    }

#print(get_current_weather("fremont"))

# format is referred from opeai Function Chat->Tools->Add->Function->get_weather()
functions = [
    {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city, e.g. San Francisco"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location"]
        }
    }
]

functions

#Function Definition and Initial Message Handling
def weather_chat(user_message):
    messages=[]
    messages.append({"role": "user", "content": user_message})
    messages.append({"role": "assistant", "content": "You are a weather bot . Answer only in Celsius and answer only related to weather related questions. If user asks other than weather then politely decline it"})

        # Sending Initial Message to OpenAI
    response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            temperature = 0,
            max_tokens=256,
            top_p=0.2,
            frequency_penalty=0,
            presence_penalty=0,
            messages=messages,
            functions=functions
        )
    #print(f'response1 is : {response}')

    #Handling Function Calls and Fetching Weather Data
    try:
        function_call = response['choices'][0]['message']['function_call']
        #print(f'function_call : {function_call}')
        # Extract function name and arguments
        arguments = eval(function_call['arguments']) # we are passing locatioon in arguments. this line of code is taking the string representation of the arguments returned by the OpenAI API and converting it into a usable Python dictionary, which you then use to call your get_current_weather function.
        #print(f'arguments : {arguments}')
        # Fetch weather data using the extracted arguments
        weather_data = get_current_weather(arguments['location'])

        # Append the function call and weather data to the messages
        messages.append({"role": "assistant", "content": None, "function_call": {"name": "get_current_weather", "arguments": str(arguments)}})
        messages.append({"role": "function", "name": "get_current_weather", "content": str(weather_data)})

        #print(f'message : {messages}')
#magic of llm
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages
        )
        #print(f'response2 : {response}')
        return response['choices'][0]['message']['content']
    except Exception as e:
        return "I'm here to provide weather updates. Please ask me questions related to weather."

#import gradio as gr
# Define Gradio interface
# iface = gr.Interface(
    # fn=weather_chat,
    # inputs=gr.Textbox(label="Weather Queries"),
    # outputs=gr.Textbox(label="Weather Updates", lines=5),
    # title = "Weather Bot",
    # description = "Ask me anything about weather!"
# )

# Launch the Gradio interface
#iface.launch(share="True")

# To create a customized Gradio Interference, following is the prompt.
# import gradio as gr
# # Define Gradio interface
# iface = gr.Interface(
#     fn=weather_chat,
#     inputs=gr.Textbox(label="Weather Queries"),
#     outputs=gr.Textbox(label="Weather Updates", lines=5),
#     title = "Weather Bot",
#     description = "Ask me anything about weather!"
# )

# # Launch the Gradio interface
# iface.launch(share="True")

# make the above gradio app more professional, use blocks and add 2 columns format, give option for famous cities in a drop down or give a option of manually submitting the city, also add the logo
# https://github.com/Decoding-Data-Science/airesidency/blob/main/dds_logo.jpg

# List of famous cities for the dropdown
FAMOUS_CITIES = [
    "New York", "London", "Tokyo", "Paris", "Dubai",
    "Singapore", "Hong Kong", "Sydney", "Mumbai", "Toronto",
    "Los Angeles", "Chicago", "San Francisco", "Berlin", "Madrid",
    "Rome", "Barcelona", "Amsterdam", "Bangkok", "Seoul",
    "Shanghai", "Beijing", "Istanbul", "Moscow", "Mexico City"
]

def process_weather_query(city_dropdown, custom_city, query):
    """
    Process weather query based on city selection and custom input
    """
    # Determine which city to use
    city = custom_city.strip() if custom_city.strip() else city_dropdown

    # Combine city with query if query exists
    if query.strip():
        full_query = f"{query} in {city}"
    else:
        full_query = f"What's the weather in {city}?"

    # Call your weather_chat function
    response = weather_chat(full_query)
    return response

# Create the Gradio Blocks interface
with gr.Blocks(theme=gr.themes.Soft(), title="Weather Bot") as iface:

    # Header with logo
    with gr.Row():
        gr.Image(
            #"https://github.com/Decoding-Data-Science/airesidency/blob/main/dds_logo.jpg?raw=true",
            "weather_bot.jpg",
            label=None,
            show_label=False,
            height=100,
            width=200,
            show_download_button=False,
            container=False
        )

    # Title and description
    gr.Markdown(
        """
        # 🌀️ Weather Bot
        ### Get real-time weather information for any city around the world
        """
    )

    # Main content with two columns
    with gr.Row():
        # Left Column - Input Section
        with gr.Column(scale=1):
            gr.Markdown("### πŸ“ Select or Enter City")

            city_dropdown = gr.Dropdown(
                choices=FAMOUS_CITIES,
                value="New York",
                label="Choose from Popular Cities",
                info="Select a city from the dropdown"
            )

            gr.Markdown("**OR**")

            custom_city = gr.Textbox(
                label="Enter Custom City",
                placeholder="Type any city name...",
                info="Leave empty to use the dropdown selection"
            )

            query_input = gr.Textbox(
                label="Additional Query (Optional)",
                placeholder="e.g., temperature, forecast, humidity...",
                lines=2,
                info="Ask specific weather questions"
            )

            with gr.Row():
                submit_btn = gr.Button("Get Weather 🌍", variant="primary", size="lg")
                clear_btn = gr.Button("Clear πŸ”„", variant="secondary")

        # Right Column - Output Section
        with gr.Column(scale=1):
            gr.Markdown("### 🌑️ Weather Information")

            output = gr.Textbox(
                label="Weather Updates",
                lines=12,
                placeholder="Weather information will appear here...",
                show_copy_button=True
            )

    # Example queries
    gr.Markdown("### πŸ’‘ Example Queries")
    gr.Examples(
        examples=[
            ["London", "", "What's the current temperature?"],
            ["", "Seattle", "Will it rain today?"],
            ["Tokyo", "", "7-day forecast"],
            ["", "Mumbai", "humidity levels"],
            ["Paris", "", ""]
        ],
        inputs=[city_dropdown, custom_city, query_input],
        label="Try these examples"
    )

    # Event handlers
    submit_btn.click(
        fn=process_weather_query,
        inputs=[city_dropdown, custom_city, query_input],
        outputs=output
    )

    clear_btn.click(
        fn=lambda: ("New York", "", "", ""),
        inputs=None,
        outputs=[city_dropdown, custom_city, query_input, output]
    )

    # Footer
    gr.Markdown(
        """
        ---
        <p style='text-align: center; color: #666;'>
        Powered by AI | Built with Gradio
        </p>
        """
    )

# Launch the interface
if __name__ == "__main__":
    iface.launch(share=True)