ombhojane commited on
Commit
5c82b59
·
1 Parent(s): abd9ea0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -0
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import logging
4
+ import emails
5
+ from emails.template import JinjaTemplate as T
6
+ import openai
7
+ import os
8
+ import secrets
9
+
10
+ # Define your OpenWeather API key here
11
+ openweather_api_key = st.secrets["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"]
12
+
13
+ # List of weather conditions and icons
14
+ weather_icons = {
15
+ "Clear": "☀️",
16
+ "Clouds": "☁️",
17
+ "Drizzle": "🌧️",
18
+ "Rain": "🌧️",
19
+ "Thunderstorm": "⛈️",
20
+ "Snow": "❄️",
21
+ "Mist": "🌫️",
22
+ "Smoke": "🌫️",
23
+ "Haze": "🌫️",
24
+ "Dust": "🌫️",
25
+ "Fog": "🌫️",
26
+ "Sand": "🌫️",
27
+ "Ash": "🌫️",
28
+ "Squall": "🌫️",
29
+ "Tornado": "🌪️"
30
+ }
31
+
32
+ def fetch_temperature(location, api_key):
33
+ base_url = "https://api.openweathermap.org/data/2.5/weather"
34
+ params = {
35
+ "q": location,
36
+ "appid": api_key,
37
+ "units": "metric",
38
+ }
39
+
40
+ try:
41
+ response = requests.get(base_url, params=params)
42
+ response.raise_for_status()
43
+
44
+ data = response.json()
45
+
46
+ if "main" in data and "temp" in data["main"]:
47
+ temperature = data["main"]["temp"]
48
+ return temperature
49
+ else:
50
+ return None
51
+ except requests.exceptions.RequestException as e:
52
+ logging.error(f"Error fetching temperature: {str(e)}")
53
+ return None
54
+
55
+ def send_temperature_alert(user_email, location, current_temperature, threshold, alert_type):
56
+ subject = T(f"Temperature {alert_type} Alert")
57
+ html_body = T(f"<p>Temperature in {location} is {alert_type} {threshold}°C.</p>"
58
+ f"<p>Current temperature: {current_temperature}°C</p>")
59
+
60
+ message = emails.html(html=html_body, subject=subject, mail_from=("Temperature Alert", "[email protected]"))
61
+
62
+ try:
63
+ response = message.send(to=(user_email,))
64
+ if response.status_code == 250:
65
+ return True
66
+ except Exception as e:
67
+ logging.error(f"Error sending email: {str(e)}")
68
+
69
+ return False
70
+
71
+ def fetch_weather_condition(location, api_key):
72
+ base_url = "https://api.openweathermap.org/data/2.5/weather"
73
+ params = {
74
+ "q": location,
75
+ "appid": api_key,
76
+ "units": "metric",
77
+ }
78
+
79
+ try:
80
+ response = requests.get(base_url, params=params)
81
+ response.raise_for_status()
82
+
83
+ data = response.json()
84
+
85
+ if "weather" in data and len(data["weather"]) > 0:
86
+ weather_condition = data["weather"][0]["main"]
87
+ return weather_condition
88
+ else:
89
+ return None
90
+ except requests.exceptions.RequestException as e:
91
+ logging.error(f"Error fetching weather condition: {str(e)}")
92
+ return None
93
+
94
+ def generate_suggestions(location, current_temperature, min_temp_threshold, max_temp_threshold, weather_condition):
95
+
96
+ openai.api_key = st.secrets["openai_api_key"]
97
+
98
+ if min_temp_threshold <= current_temperature <= max_temp_threshold:
99
+ prompt = f"Provide suggestions for someone in {location} where it's {current_temperature}°C and {weather_condition}."
100
+ elif current_temperature < min_temp_threshold:
101
+ prompt = f"Provide suggestions for someone in {location} where it's {current_temperature}°C and {weather_condition}. " \
102
+ f"Recommend suitable clothing and precautions for cold weather."
103
+ else:
104
+ prompt = f"Provide suggestions for someone in {location} where it's {current_temperature}°C and {weather_condition}. " \
105
+ f"Recommend suitable clothing and precautions for hot weather."
106
+
107
+ response = openai.Completion.create(
108
+ engine="text-davinci-002",
109
+ prompt=prompt,
110
+ max_tokens=600,
111
+ n=1,
112
+ stop=None,
113
+ temperature=0.7,
114
+ )
115
+
116
+ suggestions = response.choices[0].text
117
+ return suggestions
118
+
119
+
120
+ def main():
121
+ st.title("Fetch Alerts : Personalized Weather Suggestions App")
122
+ user_location = st.text_input("Enter your preferred location (e.g., Paris, France):")
123
+ user_email = st.text_input("Enter your email address:")
124
+ col1, col2 = st.columns(2)
125
+ min_temp_threshold = col1.number_input("Minimum Temp (°C)", value=27)
126
+ max_temp_threshold = col2.number_input("Maximum Temp (°C)", value=30)
127
+ check_button = st.button("Check Temperature and Weather")
128
+
129
+ if check_button:
130
+ weather_condition = fetch_weather_condition(user_location, openweather_api_key)
131
+
132
+ if weather_condition is not None:
133
+ st.header(f"Results of {user_location} {weather_icons[weather_condition]}")
134
+ current_temperature = fetch_temperature(user_location, openweather_api_key)
135
+
136
+ if current_temperature is not None:
137
+ st.write(f"Current temperature: {current_temperature}°C")
138
+
139
+ if current_temperature < min_temp_threshold:
140
+ if user_email:
141
+ if send_temperature_alert(user_email, user_location, current_temperature, min_temp_threshold, "Low"):
142
+ st.success("Low temperature email alert sent successfully!")
143
+ else:
144
+ st.error(f"Failed to send a low temperature alert to {user_email}")
145
+ elif current_temperature > max_temp_threshold:
146
+ if user_email:
147
+ if send_temperature_alert(user_email, user_location, current_temperature, max_temp_threshold, "High"):
148
+ st.success("High temperature email alert sent successfully!")
149
+ else:
150
+ st.error(f"Failed to send a high temperature alert to {user_email}")
151
+
152
+
153
+ suggestions = generate_suggestions(user_location, current_temperature, min_temp_threshold, max_temp_threshold, weather_condition)
154
+ st.subheader("Personalized Suggestions:")
155
+ st.write(suggestions)
156
+
157
+ if __name__ == "__main__":
158
+ main()
159
+