abdullahzunorain commited on
Commit
72cc5a6
·
verified ·
1 Parent(s): dd0da2b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -76
app.py CHANGED
@@ -1,102 +1,209 @@
1
-
2
-
3
-
4
-
5
  import requests
6
  import streamlit as st
7
- import groq
8
 
9
  # Access API keys from Streamlit secrets
10
  openweather_api_key = st.secrets["weather_api_key"]
11
  groq_api_key = st.secrets["groq_api_key"]
12
 
 
 
 
 
 
 
 
 
 
 
13
  # Function to get weather data from OpenWeatherMap
14
  def get_weather_data(city):
15
- api_key = openweather_api_key # Use the secret API key
16
- url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
17
- try:
18
- response = requests.get(url)
19
- response.raise_for_status() # Raise an HTTPError if the HTTP request returned an unsuccessful status code
20
  return response.json()
21
- except requests.exceptions.HTTPError as err:
22
- st.error(f"HTTP error occurred: {err}")
23
- except Exception as err:
24
- st.error(f"An error occurred: {err}")
25
- return None
26
-
27
- # Function to parse weather data
28
- def parse_weather_data(weather_data):
29
- temperature = weather_data["main"]["temp"]
30
- weather_description = weather_data["weather"][0]["description"]
31
- return temperature, weather_description
32
-
33
- # Function to get outfit suggestion using Groq's LLaMA model
34
- def get_outfit_suggestion(temperature, description, style, fabric):
35
- # Initialize Groq's API
36
- try:
37
- client = groq.Groq(api_key=groq_api_key) # Use the secret API key
38
-
39
- prompt = f"The current weather is {description} with a temperature of {temperature}°C. Suggest an outfit. The user prefers a {style} style and {fabric} fabric."
40
-
41
- # Use Groq's chat completion to get the text response
42
- response = client.chat.completions.create(
43
- messages=[{"role": "user", "content": prompt}],
44
- model="llama3-8b-8192", # Change to a valid Groq model if necessary
45
- )
46
- return response.choices[0].message.content.strip()
47
- except Exception as e:
48
- st.error(f"Error using Groq API: {e}")
49
  return None
50
 
51
- # Streamlit UI for user input
52
- st.title("Weather-Based Outfit Suggestion App")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- city = st.text_input("Enter your location:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- # Add style and fabric input options
57
- style = st.selectbox("Select your preferred style", ["Casual", "Formal", "Sporty", "Business", "Chic"])
58
- fabric = st.selectbox("Select your preferred fabric", ["Cotton", "Linen", "Wool", "Polyester", "Silk", "Leather"])
 
 
59
 
60
  if city:
61
  weather_data = get_weather_data(city)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if weather_data and weather_data["cod"] == 200:
64
- temperature, description = parse_weather_data(weather_data)
65
 
66
- # Display current weather info
67
- st.write(f"Current temperature in {city}: {temperature}°C")
68
- st.write(f"Weather: {description}")
69
 
70
- # Get outfit suggestion based on user preferences
71
- outfit_suggestion = get_outfit_suggestion(temperature, description, style, fabric)
72
 
73
- if outfit_suggestion:
74
- # Display outfit suggestion
75
- st.write("Outfit Suggestion:")
76
- st.write(outfit_suggestion)
77
 
78
- # Display weather icon
79
- icon_code = weather_data["weather"][0]["icon"]
80
- icon_url = f"http://openweathermap.org/img/wn/{icon_code}.png"
81
- st.image(icon_url)
82
- else:
83
- st.write("Could not retrieve weather data. Please check the location.")
84
 
85
- # Optional: Add CSS for styling
86
- st.markdown(
87
- """
88
- <style>
89
- .reportview-container {
90
- background: #f5f5f5;
91
- }
92
- .stButton>button {
93
- background-color: #ff5733;
94
- color: white;
95
- }
96
- </style>
97
- """,
98
- unsafe_allow_html=True
99
- )
100
 
101
 
102
 
 
 
 
 
 
1
  import requests
2
  import streamlit as st
3
+ import json
4
 
5
  # Access API keys from Streamlit secrets
6
  openweather_api_key = st.secrets["weather_api_key"]
7
  groq_api_key = st.secrets["groq_api_key"]
8
 
9
+ # Function to get user's IP-based location
10
+ def get_location_by_ip():
11
+ try:
12
+ response = requests.get("https://ipinfo.io")
13
+ location_data = response.json()
14
+ return location_data['city']
15
+ except Exception as e:
16
+ st.warning("Could not auto-detect location.")
17
+ return None
18
+
19
  # Function to get weather data from OpenWeatherMap
20
  def get_weather_data(city):
21
+ weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={openweather_api_key}&units=metric"
22
+ response = requests.get(weather_url)
23
+ if response.status_code == 200:
 
 
24
  return response.json()
25
+ else:
26
+ st.error("Could not retrieve weather data. Please check your API key and city name.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  return None
28
 
29
+ # Function to get outfit suggestion from Groq API
30
+ def get_outfit_suggestion(weather_condition):
31
+ url = "https://api.groq.com/v1/suggest-outfit" # Replace with the actual Groq API endpoint
32
+ headers = {
33
+ "Authorization": f"Bearer {groq_api_key}",
34
+ "Content-Type": "application/json"
35
+ }
36
+ payload = {
37
+ "weather_condition": weather_condition
38
+ }
39
+ response = requests.post(url, headers=headers, data=json.dumps(payload))
40
+ if response.status_code == 200:
41
+ return response.json().get("outfit")
42
+ else:
43
+ st.error("Could not retrieve outfit suggestions. Please check your Groq API.")
44
+ return None
45
 
46
+ # Enhanced UI with background color and icons
47
+ st.markdown(
48
+ """
49
+ <style>
50
+ body {
51
+ background-color: #f0f2f6;
52
+ color: #333;
53
+ font-family: Arial, sans-serif;
54
+ }
55
+ .main-header {
56
+ font-size: 2.5em;
57
+ color: #6C63FF;
58
+ text-align: center;
59
+ }
60
+ .weather-box {
61
+ background-color: #ffffff;
62
+ padding: 20px;
63
+ border-radius: 10px;
64
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
65
+ }
66
+ </style>
67
+ """, unsafe_allow_html=True
68
+ )
69
 
70
+ # Main app UI
71
+ st.markdown("<h1 class='main-header'>Weather-Based Outfit Suggestion App</h1>", unsafe_allow_html=True)
72
+
73
+ # Try auto-detecting location if city is empty
74
+ city = st.text_input("Enter your location:", value=get_location_by_ip() or "")
75
 
76
  if city:
77
  weather_data = get_weather_data(city)
78
+ if weather_data:
79
+ # Extract weather information
80
+ weather_condition = weather_data["weather"][0]["main"]
81
+ temperature = weather_data["main"]["temp"]
82
+ feels_like = weather_data["main"]["feels_like"]
83
+ humidity = weather_data["main"]["humidity"]
84
+ wind_speed = weather_data["wind"]["speed"]
85
+
86
+ # Display weather information with icons and enhancements
87
+ st.markdown("<div class='weather-box'>", unsafe_allow_html=True)
88
+ st.subheader(f"🌍 Weather in {city}")
89
+ st.write(f"🌤️ Condition: {weather_condition}")
90
+ st.write(f"🌡️ Temperature: {temperature}°C (Feels like: {feels_like}°C)")
91
+ st.write(f"💧 Humidity: {humidity}%")
92
+ st.write(f"💨 Wind Speed: {wind_speed} m/s")
93
+ st.markdown("</div>", unsafe_allow_html=True)
94
+
95
+ # Get outfit suggestion based on weather
96
+ outfit_suggestion = get_outfit_suggestion(weather_condition)
97
+ if outfit_suggestion:
98
+ st.subheader("👗 Outfit Suggestion")
99
+ st.write(outfit_suggestion)
100
+ # Adding a fun emoji icon based on the weather condition
101
+ outfit_icon = "👚" if "warm" in outfit_suggestion.lower() else "🧥"
102
+ st.markdown(f"{outfit_icon} {outfit_suggestion}")
103
+ else:
104
+ st.warning("No outfit suggestion available for this weather condition.")
105
+ else:
106
+ st.info("Please enter your location to get weather and outfit suggestions.")
107
+
108
+
109
+
110
+
111
+
112
+ # import requests
113
+ # import streamlit as st
114
+ # import groq
115
+
116
+ # # Access API keys from Streamlit secrets
117
+ # openweather_api_key = st.secrets["weather_api_key"]
118
+ # groq_api_key = st.secrets["groq_api_key"]
119
+
120
+ # # Function to get weather data from OpenWeatherMap
121
+ # def get_weather_data(city):
122
+ # api_key = openweather_api_key # Use the secret API key
123
+ # url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
124
+ # try:
125
+ # response = requests.get(url)
126
+ # response.raise_for_status() # Raise an HTTPError if the HTTP request returned an unsuccessful status code
127
+ # return response.json()
128
+ # except requests.exceptions.HTTPError as err:
129
+ # st.error(f"HTTP error occurred: {err}")
130
+ # except Exception as err:
131
+ # st.error(f"An error occurred: {err}")
132
+ # return None
133
+
134
+ # # Function to parse weather data
135
+ # def parse_weather_data(weather_data):
136
+ # temperature = weather_data["main"]["temp"]
137
+ # weather_description = weather_data["weather"][0]["description"]
138
+ # return temperature, weather_description
139
+
140
+ # # Function to get outfit suggestion using Groq's LLaMA model
141
+ # def get_outfit_suggestion(temperature, description, style, fabric):
142
+ # # Initialize Groq's API
143
+ # try:
144
+ # client = groq.Groq(api_key=groq_api_key) # Use the secret API key
145
+
146
+ # prompt = f"The current weather is {description} with a temperature of {temperature}°C. Suggest an outfit. The user prefers a {style} style and {fabric} fabric."
147
+
148
+ # # Use Groq's chat completion to get the text response
149
+ # response = client.chat.completions.create(
150
+ # messages=[{"role": "user", "content": prompt}],
151
+ # model="llama3-8b-8192", # Change to a valid Groq model if necessary
152
+ # )
153
+ # return response.choices[0].message.content.strip()
154
+ # except Exception as e:
155
+ # st.error(f"Error using Groq API: {e}")
156
+ # return None
157
+
158
+ # # Streamlit UI for user input
159
+ # st.title("Weather-Based Outfit Suggestion App")
160
+
161
+ # city = st.text_input("Enter your location:")
162
+
163
+ # # Add style and fabric input options
164
+ # style = st.selectbox("Select your preferred style", ["Casual", "Formal", "Sporty", "Business", "Chic"])
165
+ # fabric = st.selectbox("Select your preferred fabric", ["Cotton", "Linen", "Wool", "Polyester", "Silk", "Leather"])
166
+
167
+ # if city:
168
+ # weather_data = get_weather_data(city)
169
 
170
+ # if weather_data and weather_data["cod"] == 200:
171
+ # temperature, description = parse_weather_data(weather_data)
172
 
173
+ # # Display current weather info
174
+ # st.write(f"Current temperature in {city}: {temperature}°C")
175
+ # st.write(f"Weather: {description}")
176
 
177
+ # # Get outfit suggestion based on user preferences
178
+ # outfit_suggestion = get_outfit_suggestion(temperature, description, style, fabric)
179
 
180
+ # if outfit_suggestion:
181
+ # # Display outfit suggestion
182
+ # st.write("Outfit Suggestion:")
183
+ # st.write(outfit_suggestion)
184
 
185
+ # # Display weather icon
186
+ # icon_code = weather_data["weather"][0]["icon"]
187
+ # icon_url = f"http://openweathermap.org/img/wn/{icon_code}.png"
188
+ # st.image(icon_url)
189
+ # else:
190
+ # st.write("Could not retrieve weather data. Please check the location.")
191
 
192
+ # # Optional: Add CSS for styling
193
+ # st.markdown(
194
+ # """
195
+ # <style>
196
+ # .reportview-container {
197
+ # background: #f5f5f5;
198
+ # }
199
+ # .stButton>button {
200
+ # background-color: #ff5733;
201
+ # color: white;
202
+ # }
203
+ # </style>
204
+ # """,
205
+ # unsafe_allow_html=True
206
+ # )
207
 
208
 
209