abdullahzunorain commited on
Commit
1aa3c59
·
verified ·
1 Parent(s): 0216bb8

Update app.py

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