soctopus2327 commited on
Commit
9d0ea95
Β·
verified Β·
1 Parent(s): afd0e9f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -157
app.py CHANGED
@@ -19,34 +19,30 @@ IMAGEGEN_API_URL = "https://api-inference.huggingface.co/models/Artples/LAI-Imag
19
  # Headers for Hugging Face API requests
20
  headers = {"Authorization": f"Bearer {HUGGINGFACE_API_KEY}"}
21
 
22
- # Inject custom CSS for green theme
23
  st.markdown("""
24
  <style>
25
- body {
26
- background-color: #ffffff;
27
- }
28
- .stApp {
29
- color: #2e7d32;
30
- font-family: 'Arial', sans-serif;
31
- }
32
- .stButton>button {
33
- background-color: #66bb6a;
34
- color: #fff;
35
- font-weight: bold;
36
- }
37
- .stTextInput>div>input {
38
- background-color: #e8f5e9;
39
- color: #2e7d32;
40
- }
41
- .stMarkdown h1, .stMarkdown h2, .stMarkdown h3, .stMarkdown p {
42
- color: #388e3c;
43
- }
44
- .stMarkdown h2 {
45
- font-weight: bold;
46
- }
47
  </style>
48
  """, unsafe_allow_html=True)
49
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # Function to fetch weather data
51
  def fetch_real_data(city: str) -> dict:
52
  weather_url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_API_KEY}&units=metric'
@@ -61,7 +57,7 @@ def fetch_real_data(city: str) -> dict:
61
  "weather_condition": weather_data['weather'][0].get('main', 'Data not available')
62
  }
63
 
64
- # Function to determine mood based on weather data
65
  def determine_mood(data: dict) -> str:
66
  weather_condition = data["weather_condition"].lower()
67
  temperature = data["temperature"]
@@ -94,62 +90,6 @@ def generate_story_with_ai(narrative: str, mood: str) -> str:
94
  )
95
  return response.choices[0].message['content'].strip()
96
 
97
- # Function to generate simulated environmental data
98
- def generate_simulated_data(city: str) -> dict:
99
- prompt = (
100
- f"Generate simulated environmental data for {city} in JSON format with fields:\n"
101
- f"1. AQI\n2. Deforestation Rate\n3. Water Quality\n4. Biodiversity Impact"
102
- )
103
- response = openai.ChatCompletion.create(
104
- model="gpt-3.5-turbo",
105
- messages=[{"role": "user", "content": prompt}],
106
- max_tokens=100,
107
- temperature=0.8
108
- )
109
- response_content = response.choices[0].message['content'].strip()
110
- try:
111
- return eval(response_content)
112
- except Exception as e:
113
- st.error(f"Error parsing simulated data: {e}")
114
- return {}
115
-
116
- # Function to generate music from Hugging Face API
117
- def generate_music(description: str) -> bytes:
118
- payload = {"inputs": description}
119
- response = requests.post(MUSICGEN_API_URL, headers=headers, json=payload)
120
- if response.status_code != 200:
121
- st.error(f"Error generating music: {response.status_code} {response.text}")
122
- return None
123
- return response.content
124
-
125
- # Function to generate an image based on the story
126
- def generate_image(description: str) -> bytes:
127
- payload = {"inputs": description}
128
- response = requests.post(IMAGEGEN_API_URL, headers=headers, json=payload)
129
- if response.status_code != 200:
130
- st.error(f"Error generating image: {response.status_code} {response.text}")
131
- return None
132
- return response.content
133
-
134
- # Function to create a dynamic music description
135
- def create_music_description(data):
136
- mood = data["mood"]
137
- weather_condition = data["real_data"]["weather_condition"].lower()
138
- temperature = data["real_data"]["temperature"]
139
-
140
- description = f"{mood} mood with {weather_condition} weather"
141
-
142
- if temperature < 10:
143
- description += " and a cold ambiance"
144
- elif 10 <= temperature <= 20:
145
- description += " and a cool feel"
146
- elif 20 < temperature <= 30:
147
- description += " and a warm, lively environment"
148
- else:
149
- description += " and a hot, energetic vibe"
150
-
151
- return description
152
-
153
  # Function to fetch NGOs using OpenAI
154
  def fetch_nearby_ngos_with_openai(city: str, interests: list) -> list:
155
  prompt = (
@@ -173,82 +113,45 @@ def fetch_nearby_ngos_with_openai(city: str, interests: list) -> list:
173
  st.title("🌿 Eco-Symphony 🎢")
174
  st.write("Enter a city to explore real-time environmental data, generate AI-created music, and see an AI-generated image based on the story.")
175
 
176
- # Input box for city
177
  city = st.text_input("Enter City Name:", placeholder="Type the name of a city...")
178
 
179
- # Generate Button
180
- if st.button("Generate Environmental Narrative, Music, and Image"):
181
- # Fetch real weather data
182
- real_data = fetch_real_data(city)
183
-
184
- if real_data:
185
- # Generate narrative and mood
186
- narrative = create_narrative(city, real_data)
187
- mood = determine_mood(real_data)
188
-
189
- # Generate AI story
190
- story = generate_story_with_ai(narrative, mood)
191
-
192
- # Generate Music and Image Based on Story and Mood
193
- music_description = create_music_description({"mood": mood, "real_data": real_data})
194
-
195
- st.subheader("🎢 Generated Music")
196
- st.write(f"Generating music based on: {music_description}")
197
- music_bytes = generate_music(music_description)
198
- if music_bytes:
199
- audio_data = BytesIO(music_bytes)
200
- st.audio(audio_data, format="audio/wav")
201
-
202
- st.subheader("πŸ–ΌοΈ Generated Image")
203
- st.write("Generating image based on the story...")
204
- image_bytes = generate_image(story)
205
- if image_bytes:
206
- image = Image.open(BytesIO(image_bytes))
207
- st.image(image, caption="Generated Image based on Story", use_column_width=True)
208
-
209
- # Display Environmental Narrative and Data
210
- st.subheader("πŸ“œ Environmental Narrative")
211
- st.write(narrative)
212
-
213
- st.subheader("πŸ’­ Mood")
214
- st.write(f"**Mood**: {mood}")
215
-
216
- st.subheader("🌈 AI-Generated Story")
217
- st.write(story)
218
-
219
- # Generate and Display Simulated Environmental Data
220
- simulated_data = generate_simulated_data(city)
221
- simulated_inner_data = simulated_data.get("data", {})
222
- st.subheader("πŸ“Š Real Weather Data")
223
- st.write("Temperature (Β°C):", real_data.get("temperature", "Data not available"))
224
- st.write("Humidity (%):", real_data.get("humidity", "Data not available"))
225
- st.write("Weather Condition:", real_data.get("weather_condition", "Data not available"))
226
-
227
- st.subheader("πŸ§ͺ Simulated Environmental Data")
228
- st.write("AQI:", simulated_inner_data.get("AQI", "Data not available"))
229
- st.write("Deforestation Rate:", simulated_inner_data.get("Deforestation Rate", "Data not available"))
230
- st.write("Water Quality:", simulated_inner_data.get("Water Quality", "Data not available"))
231
- st.write("Biodiversity Impact:", simulated_inner_data.get("Biodiversity Impact", "Data not available"))
232
-
233
- # Collect User's Environmental Interests
234
- st.subheader("🌍 Get Involved!")
235
- st.write("Choose your areas of interest for saving the environment:")
236
- interests = st.multiselect(
237
- "Select Areas of Interest:",
238
- ["Afforestation", "Water Conservation", "Biodiversity Protection", "Recycling", "Climate Change Awareness"]
239
- )
240
-
241
- if st.button("Find Nearby NGOs"):
242
- if interests:
243
- ngos = fetch_nearby_ngos_with_openai(city, interests)
244
- if ngos:
245
- st.subheader("🌟 NGOs Near You")
246
- for ngo in ngos:
247
- st.write(f"**{ngo['name']}**")
248
- st.write(f"πŸ“ Location: {ngo['location']}")
249
- st.write(f"🌱 Focus Area: {ngo['focus']}")
250
- st.write("---")
251
- else:
252
- st.write("No NGOs found nearby in your areas of interest.")
253
- else:
254
- st.warning("Please select at least one area of interest.")
 
19
  # Headers for Hugging Face API requests
20
  headers = {"Authorization": f"Bearer {HUGGINGFACE_API_KEY}"}
21
 
22
+ # CSS
23
  st.markdown("""
24
  <style>
25
+ body {background-color: #ffffff;}
26
+ .stApp {color: #2e7d32; font-family: 'Arial', sans-serif;}
27
+ .stButton>button {background-color: #66bb6a; color: #fff; font-weight: bold;}
28
+ .stTextInput>div>input {background-color: #e8f5e9; color: #2e7d32;}
29
+ .stMarkdown h1, .stMarkdown h2, .stMarkdown h3, .stMarkdown p {color: #388e3c;}
30
+ .stMarkdown h2 {font-weight: bold;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  </style>
32
  """, unsafe_allow_html=True)
33
 
34
+ # Initialize session state variables
35
+ if "real_data" not in st.session_state:
36
+ st.session_state.real_data = {}
37
+ if "story" not in st.session_state:
38
+ st.session_state.story = ""
39
+ if "music_bytes" not in st.session_state:
40
+ st.session_state.music_bytes = None
41
+ if "image_bytes" not in st.session_state:
42
+ st.session_state.image_bytes = None
43
+ if "ngos" not in st.session_state:
44
+ st.session_state.ngos = []
45
+
46
  # Function to fetch weather data
47
  def fetch_real_data(city: str) -> dict:
48
  weather_url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_API_KEY}&units=metric'
 
57
  "weather_condition": weather_data['weather'][0].get('main', 'Data not available')
58
  }
59
 
60
+ # Function to determine mood
61
  def determine_mood(data: dict) -> str:
62
  weather_condition = data["weather_condition"].lower()
63
  temperature = data["temperature"]
 
90
  )
91
  return response.choices[0].message['content'].strip()
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  # Function to fetch NGOs using OpenAI
94
  def fetch_nearby_ngos_with_openai(city: str, interests: list) -> list:
95
  prompt = (
 
113
  st.title("🌿 Eco-Symphony 🎢")
114
  st.write("Enter a city to explore real-time environmental data, generate AI-created music, and see an AI-generated image based on the story.")
115
 
 
116
  city = st.text_input("Enter City Name:", placeholder="Type the name of a city...")
117
 
118
+ if st.button("Generate Environmental Data"):
119
+ st.session_state.real_data = fetch_real_data(city)
120
+ if st.session_state.real_data:
121
+ narrative = create_narrative(city, st.session_state.real_data)
122
+ mood = determine_mood(st.session_state.real_data)
123
+ st.session_state.story = generate_story_with_ai(narrative, mood)
124
+
125
+ # Display environmental data
126
+ if st.session_state.real_data:
127
+ st.subheader("πŸ“Š Real Weather Data")
128
+ st.write("Temperature (Β°C):", st.session_state.real_data.get("temperature", "Data not available"))
129
+ st.write("Humidity (%):", st.session_state.real_data.get("humidity", "Data not available"))
130
+ st.write("Weather Condition:", st.session_state.real_data.get("weather_condition", "Data not available"))
131
+
132
+ if st.session_state.story:
133
+ st.subheader("🌈 AI-Generated Story")
134
+ st.write(st.session_state.story)
135
+
136
+ # Get User's Environmental Interests
137
+ st.subheader("🌍 Get Involved!")
138
+ st.write("Choose your areas of interest for saving the environment:")
139
+ interests = st.multiselect(
140
+ "Select Areas of Interest:",
141
+ ["Afforestation", "Water Conservation", "Biodiversity Protection", "Recycling", "Climate Change Awareness"]
142
+ )
143
+
144
+ if st.button("Find Nearby NGOs"):
145
+ if interests:
146
+ st.session_state.ngos = fetch_nearby_ngos_with_openai(city, interests)
147
+ else:
148
+ st.warning("Please select at least one area of interest.")
149
+
150
+ # Display NGO information
151
+ if st.session_state.ngos:
152
+ st.subheader("🌟 NGOs Near You")
153
+ for ngo in st.session_state.ngos:
154
+ st.write(f"**{ngo['name']}**")
155
+ st.write(f"πŸ“ Location: {ngo['location']}")
156
+ st.write(f"🌱 Focus Area: {ngo['focus']}")
157
+ st.write("---")