VaibT commited on
Commit
0a724f2
Β·
verified Β·
1 Parent(s): 80bb85c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import requests
4
+ import gradio as gr
5
+ from openai import OpenAI
6
+
7
+ # Load API keys from Hugging Face Secrets
8
+ OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
9
+ WEATHER_API_KEY = os.environ["WEATHER_API_KEY"]
10
+
11
+ client = OpenAI(api_key=OPENAI_API_KEY)
12
+
13
+ # Weather Function
14
+ def get_current_weather(location, unit='celsius'):
15
+ url = (
16
+ f"http://api.openweathermap.org/data/2.5/weather"
17
+ f"?q={location}"
18
+ f"&appid={WEATHER_API_KEY}"
19
+ f"&units=metric"
20
+ )
21
+ response = requests.get(url)
22
+ data = response.json()
23
+
24
+ if response.status_code != 200:
25
+ return {"error": data.get("message", "Weather data unavailable")}
26
+
27
+ return {
28
+ "location": location,
29
+ "temperature": data["main"]["temp"],
30
+ "humidity": data["main"]["humidity"],
31
+ "weather": data["weather"][0]["description"]
32
+ }
33
+
34
+ # Chat logic
35
+ def weather_chat(user_message):
36
+ try:
37
+ tools = [
38
+ {
39
+ "type": "function",
40
+ "function": {
41
+ "name": "get_current_weather",
42
+ "description": "Get current weather information for a city",
43
+ "parameters": {
44
+ "type": "object",
45
+ "properties": {
46
+ "location": {"type": "string", "description": "City name"}
47
+ },
48
+ "required": ["location"]
49
+ }
50
+ }
51
+ }
52
+ ]
53
+
54
+ messages = [
55
+ {
56
+ "role": "system",
57
+ "content": """
58
+ You are a professional weather bot/assistant.
59
+ Rules:
60
+ - Answer weather-related questions.
61
+ - Use Celsius and Fahrenheit only.
62
+ - If the question is unrelated to weather, politely decline.
63
+ """
64
+ },
65
+ {"role": "user", "content": user_message}
66
+ ]
67
+
68
+ response = client.chat.completions.create(
69
+ model="gpt-5-nano",
70
+ messages=messages,
71
+ tools=tools
72
+ )
73
+
74
+ assistant_message = response.choices[0].message
75
+
76
+ if assistant_message.tool_calls:
77
+ tool_call = assistant_message.tool_calls[0]
78
+ args = json.loads(tool_call.function.arguments)
79
+ weather_data = get_current_weather(args["location"])
80
+
81
+ messages.append(assistant_message)
82
+ messages.append(
83
+ {
84
+ "role": "tool",
85
+ "tool_call_id": tool_call.id,
86
+ "content": json.dumps(weather_data)
87
+ }
88
+ )
89
+
90
+ final_response = client.chat.completions.create(
91
+ model="gpt-5-nano",
92
+ messages=messages
93
+ )
94
+ return final_response.choices[0].message.content
95
+ else:
96
+ return assistant_message.content
97
+
98
+ except Exception:
99
+ return "Hello! I'm here to provide weather updates only. Please ask me questions related to weather."
100
+
101
+ # -----------------------------
102
+ # Custom Modern Theme + CSS
103
+ # -----------------------------
104
+ custom_css = """YOUR CSS FROM ABOVE (unchanged)"""
105
+
106
+ def respond(message, history):
107
+ if not message:
108
+ return "", history
109
+ response = weather_chat(message)
110
+ history.append({"role": "user", "content": message})
111
+ history.append({"role": "assistant", "content": response})
112
+ return "", history
113
+
114
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
115
+ gr.HTML(
116
+ '''
117
+ <div class="main-title">🌦️ SkyMind WeatherAI 🌀️</div>
118
+ <div class="sub-title">Intelligent Real-time Weather Updates Forecast Assistant 🌍</div>
119
+ '''
120
+ )
121
+
122
+ with gr.Column(elem_classes="weather-card"):
123
+ chatbot = gr.Chatbot(
124
+ type="messages",
125
+ height=500,
126
+ bubble_full_width=False,
127
+ avatar_images=(None, "https://cdn-icons-png.flaticon.com/512/1779/1779940.png"),
128
+ allow_tags=False
129
+ )
130
+
131
+ msg = gr.Textbox(
132
+ placeholder="Ask weather like: Weather in Dubai, Mumbai, Shanghai?...",
133
+ lines=1,
134
+ show_label=False
135
+ )
136
+
137
+ with gr.Row():
138
+ submit_btn = gr.Button("πŸš€ Get Weather", variant="primary")
139
+ copy_btn = gr.Button("πŸ“‹ Copy Answer")
140
+
141
+ copy_js = """
142
+ function copyToClipboard() {
143
+ const messages = document.querySelectorAll('.message.bot');
144
+ if (messages.length > 0) {
145
+ const latestMessage = messages[messages.length - 1].innerText;
146
+ navigator.clipboard.writeText(latestMessage);
147
+ alert("βœ… Weather response copied!");
148
+ }
149
+ }
150
+ """
151
+
152
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
153
+ submit_btn.click(respond, [msg, chatbot], [msg, chatbot])
154
+ copy_btn.click(None, None, None, js=copy_js)
155
+
156
+ demo.launch(server_name="0.0.0.0", server_port=7860)