soctopus2327 commited on
Commit
afff569
Β·
verified Β·
1 Parent(s): 89b8d9b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -78
app.py CHANGED
@@ -3,7 +3,6 @@ import requests
3
  import openai
4
  from io import BytesIO
5
  from PIL import Image
6
- import random
7
 
8
  # Set page configuration as the first Streamlit command
9
  st.set_page_config(page_title="Eco-Symphony", page_icon="🌱", layout="centered")
@@ -59,8 +58,12 @@ if "image_bytes" not in st.session_state:
59
  st.session_state.image_bytes = None
60
  if "ngos" not in st.session_state:
61
  st.session_state.ngos = []
 
 
 
 
62
 
63
- # Function to generate daily challenges using GPT
64
  def generate_daily_challenges() -> list:
65
  prompt = "Give me 5 small, easy-to-do eco-friendly daily challenges that can be completed in a day."
66
  response = openai.ChatCompletion.create(
@@ -72,22 +75,6 @@ def generate_daily_challenges() -> list:
72
  challenges = response.choices[0].message['content'].strip().split("\n")
73
  return [challenge.strip() for challenge in challenges if challenge.strip()]
74
 
75
- # Function to fetch endangered species based on user's city
76
- def fetch_endangered_species(city: str) -> dict:
77
- prompt = f"Provide details of an endangered species in {city}, including its name, image description, and current population."
78
- response = openai.ChatCompletion.create(
79
- model="gpt-3.5-turbo",
80
- messages=[{"role": "user", "content": prompt}],
81
- max_tokens=150,
82
- temperature=0.8
83
- )
84
- response_content = response.choices[0].message['content'].strip()
85
- try:
86
- return eval(response_content) # Assuming the response is a JSON-like structure
87
- except Exception as e:
88
- st.error(f"Error parsing endangered species data: {e}")
89
- return {}
90
-
91
  # Function to fetch weather data
92
  def fetch_real_data(city: str) -> dict:
93
  weather_url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_API_KEY}&units=metric'
@@ -153,76 +140,56 @@ def generate_image(description: str) -> bytes:
153
  return None
154
  return response.content
155
 
156
- # Main daily challenges section
157
- def daily_challenges_section(city):
158
- st.subheader("πŸ† Daily Challenges")
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- # Points counter
161
- if 'points' not in st.session_state:
162
- st.session_state['points'] = 0
163
-
164
- st.markdown(f"<h2 style='text-align: center;'>πŸ’° Points: {st.session_state['points']}</h2>", unsafe_allow_html=True)
165
-
166
- # Generate or load daily challenges
167
- if 'daily_challenges' not in st.session_state:
168
- st.session_state['daily_challenges'] = generate_daily_challenges()
169
-
170
- # Create a checkable list for the challenges
171
- completed_challenges = []
172
- for i, challenge in enumerate(st.session_state['daily_challenges']):
173
- if st.checkbox(challenge, key=f"challenge_{i}"):
174
- completed_challenges.append(i)
175
-
176
- # Update points based on completed challenges
177
- st.session_state['points'] = len(completed_challenges) * 10 # Example: 10 points per challenge
178
-
179
- # Check if all challenges are completed
180
- if len(completed_challenges) == len(st.session_state['daily_challenges']):
181
- st.success("All challenges completed! πŸŽ‰ You've unlocked the secret section!")
182
-
183
- # Fetch endangered species data for the user's city
184
- species_data = fetch_endangered_species(city)
185
- if species_data:
186
- st.subheader("πŸ¦‹ Endangered Species Unlocked!")
187
- st.write(f"**Species**: {species_data.get('name', 'Unknown')}")
188
- st.write(f"**Population**: {species_data.get('population', 'Unknown')}")
189
- st.write(f"**Description**: {species_data.get('description', 'No description available')}")
190
-
191
- # Generate an image of the endangered species
192
- image_description = f"Generate an image of the endangered species: {species_data.get('name', 'Unknown')}"
193
- species_image_bytes = generate_image(image_description)
194
- if species_image_bytes:
195
- species_image = Image.open(BytesIO(species_image_bytes))
196
- st.image(species_image, caption=f"Endangered Species: {species_data.get('name', 'Unknown')}", use_column_width=True)
197
-
198
- # Add this to your Streamlit UI where appropriate
199
  st.title("🌿 Eco-Symphony 🎢")
200
  st.write("Enter a city to explore real-time environmental data, complete daily challenges, and unlock hidden content!")
201
 
202
  city = st.text_input("Enter City Name:", placeholder="Type the name of a city...")
203
 
204
- if city:
205
- # Other sections of the app (weather data, music, etc.)
206
  st.session_state.real_data = fetch_real_data(city)
207
  if st.session_state.real_data:
 
208
  narrative = create_narrative(city, st.session_state.real_data)
209
  mood = determine_mood(st.session_state.real_data)
 
 
210
  st.session_state.story = generate_story_with_ai(narrative, mood)
 
 
211
  music_description = f"{mood} mood with {st.session_state.real_data['weather_condition'].lower()} weather"
212
  st.session_state.music_bytes = generate_music(music_description)
213
  st.session_state.image_bytes = generate_image(st.session_state.story)
214
-
215
- # Display generated music and image at the top
216
- if st.session_state.music_bytes:
217
- st.subheader("🎢 Generated Music")
218
- st.audio(BytesIO(st.session_state.music_bytes), format="audio/wav")
219
-
220
- if st.session_state.image_bytes:
221
- st.subheader("πŸ–ΌοΈ Generated Image")
222
- st.image(Image.open(BytesIO(st.session_state.image_bytes)), caption="Generated Image based on Story", use_column_width=True)
223
-
224
- # Display the narrative and data
 
225
  st.subheader("πŸ“œ Environmental Narrative")
 
226
  st.write(narrative)
227
 
228
  st.subheader("πŸ“Š Real Weather Data")
@@ -230,9 +197,63 @@ if city:
230
  st.write("Humidity (%):", st.session_state.real_data.get("humidity", "Data not available"))
231
  st.write("Weather Condition:", st.session_state.real_data.get("weather_condition", "Data not available"))
232
 
233
- if st.session_state.story:
234
- st.subheader("🌈 AI-Generated Story")
235
- st.write(st.session_state.story)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- # Display daily challenges section
238
- daily_challenges_section(city)
 
 
 
 
 
 
 
3
  import openai
4
  from io import BytesIO
5
  from PIL import Image
 
6
 
7
  # Set page configuration as the first Streamlit command
8
  st.set_page_config(page_title="Eco-Symphony", page_icon="🌱", layout="centered")
 
58
  st.session_state.image_bytes = None
59
  if "ngos" not in st.session_state:
60
  st.session_state.ngos = []
61
+ if "points" not in st.session_state:
62
+ st.session_state.points = 0
63
+ if "daily_challenges" not in st.session_state:
64
+ st.session_state.daily_challenges = []
65
 
66
+ # Function to generate daily eco-friendly challenges
67
  def generate_daily_challenges() -> list:
68
  prompt = "Give me 5 small, easy-to-do eco-friendly daily challenges that can be completed in a day."
69
  response = openai.ChatCompletion.create(
 
75
  challenges = response.choices[0].message['content'].strip().split("\n")
76
  return [challenge.strip() for challenge in challenges if challenge.strip()]
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  # Function to fetch weather data
79
  def fetch_real_data(city: str) -> dict:
80
  weather_url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_API_KEY}&units=metric'
 
140
  return None
141
  return response.content
142
 
143
+ # Function to fetch endangered species data
144
+ def fetch_endangered_species(city: str) -> dict:
145
+ prompt = f"Provide details of an endangered species in {city}, including its name, image description, and current population."
146
+ response = openai.ChatCompletion.create(
147
+ model="gpt-3.5-turbo",
148
+ messages=[{"role": "user", "content": prompt}],
149
+ max_tokens=150,
150
+ temperature=0.8
151
+ )
152
+ response_content = response.choices[0].message['content'].strip()
153
+ try:
154
+ return eval(response_content) # Assuming the response is a JSON-like structure
155
+ except Exception as e:
156
+ st.error(f"Error parsing endangered species data: {e}")
157
+ return {}
158
 
159
+ # Streamlit UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  st.title("🌿 Eco-Symphony 🎢")
161
  st.write("Enter a city to explore real-time environmental data, complete daily challenges, and unlock hidden content!")
162
 
163
  city = st.text_input("Enter City Name:", placeholder="Type the name of a city...")
164
 
165
+ if st.button("Generate Environmental Data, Music, and Image"):
 
166
  st.session_state.real_data = fetch_real_data(city)
167
  if st.session_state.real_data:
168
+ # Generate narrative and mood
169
  narrative = create_narrative(city, st.session_state.real_data)
170
  mood = determine_mood(st.session_state.real_data)
171
+
172
+ # Generate AI story
173
  st.session_state.story = generate_story_with_ai(narrative, mood)
174
+
175
+ # Generate Music and Image Based on Story and Mood
176
  music_description = f"{mood} mood with {st.session_state.real_data['weather_condition'].lower()} weather"
177
  st.session_state.music_bytes = generate_music(music_description)
178
  st.session_state.image_bytes = generate_image(st.session_state.story)
179
+
180
+ # Display Music and Image at the Top
181
+ if st.session_state.music_bytes:
182
+ st.subheader("🎢 Generated Music")
183
+ st.audio(BytesIO(st.session_state.music_bytes), format="audio/wav")
184
+
185
+ if st.session_state.image_bytes:
186
+ st.subheader("πŸ–ΌοΈ Generated Image")
187
+ st.image(Image.open(BytesIO(st.session_state.image_bytes)), caption="Generated Image based on Story", use_column_width=True)
188
+
189
+ # Display Environmental Narrative and Data
190
+ if st.session_state.real_data:
191
  st.subheader("πŸ“œ Environmental Narrative")
192
+ narrative = create_narrative(city, st.session_state.real_data)
193
  st.write(narrative)
194
 
195
  st.subheader("πŸ“Š Real Weather Data")
 
197
  st.write("Humidity (%):", st.session_state.real_data.get("humidity", "Data not available"))
198
  st.write("Weather Condition:", st.session_state.real_data.get("weather_condition", "Data not available"))
199
 
200
+ if st.session_state.story:
201
+ st.subheader("🌈 AI-Generated Story")
202
+ st.write(st.session_state.story)
203
+
204
+ # Daily Challenges Section
205
+ st.subheader("πŸ† Daily Challenges")
206
+
207
+ if not st.session_state.daily_challenges:
208
+ st.session_state.daily_challenges = generate_daily_challenges()
209
+
210
+ completed_challenges = []
211
+ for i, challenge in enumerate(st.session_state.daily_challenges):
212
+ if st.checkbox(challenge, key=f"challenge_{i}"):
213
+ completed_challenges.append(i)
214
+
215
+ # Update points based on completed challenges
216
+ st.session_state.points = len(completed_challenges) * 10 # 10 points per challenge
217
+ st.markdown(f"<h2 style='text-align: center;'>πŸ’° Points: {st.session_state.points}</h2>", unsafe_allow_html=True)
218
+
219
+ # Check if all challenges are completed
220
+ if len(completed_challenges) == len(st.session_state.daily_challenges):
221
+ st.success("All challenges completed! πŸŽ‰ You've unlocked the secret section!")
222
+
223
+ # Fetch endangered species data for the user's city
224
+ species_data = fetch_endangered_species(city)
225
+ if species_data:
226
+ st.subheader("πŸ¦‹ Endangered Species Unlocked!")
227
+ st.write(f"**Species**: {species_data.get('name', 'Unknown')}")
228
+ st.write(f"**Population**: {species_data.get('population', 'Unknown')}")
229
+ st.write(f"**Description**: {species_data.get('description', 'No description available')}")
230
+
231
+ # Generate an image of the endangered species
232
+ image_description = f"Generate an image of the endangered species: {species_data.get('name', 'Unknown')}"
233
+ species_image_bytes = generate_image(image_description)
234
+ if species_image_bytes:
235
+ species_image = Image.open(BytesIO(species_image_bytes))
236
+ st.image(species_image, caption=f"Endangered Species: {species_data.get('name', 'Unknown')}", use_column_width=True)
237
+
238
+ # User's Environmental Interests Section
239
+ st.subheader("🌍 Get Involved!")
240
+ st.write("Choose your areas of interest for saving the environment:")
241
+ interests = st.multiselect(
242
+ "Select Areas of Interest:",
243
+ ["Afforestation", "Water Conservation", "Biodiversity Protection", "Recycling", "Climate Change Awareness"]
244
+ )
245
+
246
+ if st.button("Find Nearby NGOs"):
247
+ if interests:
248
+ st.session_state.ngos = fetch_nearby_ngos_with_openai(city, interests)
249
+ else:
250
+ st.warning("Please select at least one area of interest.")
251
 
252
+ # Display NGO information
253
+ if st.session_state.ngos:
254
+ st.subheader("🌟 NGOs Near You")
255
+ for ngo in st.session_state.ngos:
256
+ st.write(f"**{ngo.get('name', 'Unknown NGO')}**")
257
+ st.write(f"πŸ“ Location: {ngo.get('location', 'Unknown Location')}")
258
+ st.write(f"🌱 Focus Area: {ngo.get('focus', 'Unknown Focus Area')}")
259
+ st.write("---")