ogegadavis254 commited on
Commit
9104631
·
verified ·
1 Parent(s): 65e9088

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -110
app.py CHANGED
@@ -105,7 +105,7 @@ if st.button("Generate Prediction and Analysis"):
105
  f"Be as accurate and specific to Kenya as possible in your analysis. And please do not generate long texts, make it as short and precise as possible, i am stressing on this please, generate something short."
106
  )
107
 
108
- try:
109
  stages = [
110
  "Analyzing climate conditions...",
111
  "Checking location data...",
@@ -143,131 +143,131 @@ if st.button("Generate Prediction and Analysis"):
143
  continue
144
 
145
  st.success("Analysis completed!")
146
- # Display prediction
147
- st.subheader("Climate Impact Analysis for Sports in Kenya")
148
- st.markdown(initial_text.strip())
149
 
150
- # Extract and display scores
151
- performance_score = "N/A"
152
- infrastructure_score = "N/A"
153
- for line in initial_text.split('\n'):
154
- if "performance score:" in line.lower():
155
- performance_score = line.split(":")[-1].strip()
156
- elif "infrastructure impact score:" in line.lower():
157
- infrastructure_score = line.split(":")[-1].strip()
158
 
159
- # Display performance and infrastructure scores
160
- col1, col2 = st.columns(2)
161
- with col1:
162
- st.metric("Overall Performance Score", performance_score)
163
- with col2:
164
- st.metric("Infrastructure Impact Score", infrastructure_score)
165
 
166
- # Prepare data for visualization
167
- results_data = {
168
- "Condition": ["Temperature", "Humidity", "Wind Speed", "UV Index", "Air Quality Index", "Precipitation", "Atmospheric Pressure"],
169
- "Value": [temperature, humidity, wind_speed, uv_index, air_quality_index, precipitation, atmospheric_pressure]
170
- }
171
- results_df = pd.DataFrame(results_data)
172
 
173
- # Display results in a table
174
- st.subheader("Climate Conditions Summary")
175
- st.table(results_df)
176
 
177
- # Create a radar chart for climate conditions
178
- fig = go.Figure(data=go.Scatterpolar(
179
- r=[temperature/50*100, humidity, wind_speed/2, uv_index/11*100, air_quality_index/5, precipitation/5, (atmospheric_pressure-900)/2],
180
- theta=results_df['Condition'],
181
- fill='toself'
182
- ))
183
- fig.update_layout(
184
- polar=dict(
185
- radialaxis=dict(visible=True, range=[0, 100])
186
- ),
187
- showlegend=False
188
- )
189
- st.plotly_chart(fig)
190
 
191
- # Display analyzed sports and infrastructure
192
- st.subheader("Analyzed Components")
193
- col1, col2, col3 = st.columns(3)
194
- with col1:
195
- st.write("**Sports:**")
196
- for sport in sports:
197
- st.write(f"- {sport}")
198
- with col2:
199
- st.write("**Athlete Types:**")
200
- for athlete_type in athlete_types:
201
- st.write(f"- {athlete_type}")
202
- with col3:
203
- st.write("**Infrastructure Types:**")
204
- for infra_type in infrastructure_types:
205
- st.write(f"- {infra_type}")
206
 
207
- # Socio-economic impact analysis
208
- st.subheader("Socio-Economic Impact Analysis")
209
- socio_economic_prompt = (
210
- f"Based on the climate conditions and sports analysis for {region}, Kenya, "
211
- f"provide a brief assessment of the socio-economic implications, including impacts on: "
212
- f"1) Local economy, 2) Community health, 3) Sports tourism, 4) Equitable access to sports facilities. "
213
- f"Consider the specific context of Kenya and the selected region. and make the response very precise and short, do not yap"
214
- )
215
 
216
- with st.spinner("Analyzing socio-economic impacts..."):
217
- socio_economic_response = call_ai_model_analysis(socio_economic_prompt)
218
- socio_economic_text = ""
219
- for line in socio_economic_response.iter_lines():
220
- if line:
221
- line_content = line.decode('utf-8')
222
- if line_content.startswith("data: "):
223
- line_content = line_content[6:]
224
- try:
225
- json_data = json.loads(line_content)
226
- if "choices" in json_data:
227
- delta = json_data["choices"][0]["delta"]
228
- if "content" in delta:
229
- socio_economic_text += delta["content"]
230
- except json.JSONDecodeError:
231
- continue
232
 
233
- st.markdown(socio_economic_text.strip())
234
 
235
- # Mitigation strategies
236
- st.subheader("Mitigation Strategies")
237
- mitigation_prompt = (
238
- f"Based on the climate conditions and sports analysis for {region}, Kenya, "
239
- f"suggest specific mitigation strategies for: "
240
- f"1) Improving athlete performance and health, 2) Enhancing infrastructure resilience, "
241
- f"3) Ensuring equitable access to sports facilities. "
242
- f"Consider the specific context of Kenya and the selected region. And make the response very precise and short, do not yap"
243
- )
244
 
245
- with st.spinner("Generating mitigation strategies..."):
246
- mitigation_response = call_ai_model_analysis(mitigation_prompt)
247
- mitigation_text = ""
248
- for line in mitigation_response.iter_lines():
249
- if line:
250
- line_content = line.decode('utf-8')
251
- if line_content.startswith("data: "):
252
- line_content = line_content[6:]
253
- try:
254
- json_data = json.loads(line_content)
255
- if "choices" in json_data:
256
- delta = json_data["choices"][0]["delta"]
257
- if "content" in delta:
258
- mitigation_text += delta["content"]
259
- except json.JSONDecodeError:
260
- continue
261
 
262
- st.markdown(mitigation_text.strip())
263
 
264
- # Display raw analysis result for debugging
265
- with st.expander("Show Raw Analysis"):
266
- st.text(initial_text)
267
 
268
  except ValueError as ve:
269
  st.error(f"Configuration error: {ve}")
270
  except requests.exceptions.RequestException as re:
271
  st.error(f"Request error: {re}")
272
  except Exception as e:
273
- st.error(f"An unexpected error occurred: {e}")
 
105
  f"Be as accurate and specific to Kenya as possible in your analysis. And please do not generate long texts, make it as short and precise as possible, i am stressing on this please, generate something short."
106
  )
107
 
108
+ try:
109
  stages = [
110
  "Analyzing climate conditions...",
111
  "Checking location data...",
 
143
  continue
144
 
145
  st.success("Analysis completed!")
146
+ # Display prediction
147
+ st.subheader("Climate Impact Analysis for Sports in Kenya")
148
+ st.markdown(initial_text.strip())
149
 
150
+ # Extract and display scores
151
+ performance_score = "N/A"
152
+ infrastructure_score = "N/A"
153
+ for line in initial_text.split('\n'):
154
+ if "performance score:" in line.lower():
155
+ performance_score = line.split(":")[-1].strip()
156
+ elif "infrastructure impact score:" in line.lower():
157
+ infrastructure_score = line.split(":")[-1].strip()
158
 
159
+ # Display performance and infrastructure scores
160
+ col1, col2 = st.columns(2)
161
+ with col1:
162
+ st.metric("Overall Performance Score", performance_score)
163
+ with col2:
164
+ st.metric("Infrastructure Impact Score", infrastructure_score)
165
 
166
+ # Prepare data for visualization
167
+ results_data = {
168
+ "Condition": ["Temperature", "Humidity", "Wind Speed", "UV Index", "Air Quality Index", "Precipitation", "Atmospheric Pressure"],
169
+ "Value": [temperature, humidity, wind_speed, uv_index, air_quality_index, precipitation, atmospheric_pressure]
170
+ }
171
+ results_df = pd.DataFrame(results_data)
172
 
173
+ # Display results in a table
174
+ st.subheader("Climate Conditions Summary")
175
+ st.table(results_df)
176
 
177
+ # Create a radar chart for climate conditions
178
+ fig = go.Figure(data=go.Scatterpolar(
179
+ r=[temperature/50*100, humidity, wind_speed/2, uv_index/11*100, air_quality_index/5, precipitation/5, (atmospheric_pressure-900)/2],
180
+ theta=results_df['Condition'],
181
+ fill='toself'
182
+ ))
183
+ fig.update_layout(
184
+ polar=dict(
185
+ radialaxis=dict(visible=True, range=[0, 100])
186
+ ),
187
+ showlegend=False
188
+ )
189
+ st.plotly_chart(fig)
190
 
191
+ # Display analyzed sports and infrastructure
192
+ st.subheader("Analyzed Components")
193
+ col1, col2, col3 = st.columns(3)
194
+ with col1:
195
+ st.write("**Sports:**")
196
+ for sport in sports:
197
+ st.write(f"- {sport}")
198
+ with col2:
199
+ st.write("**Athlete Types:**")
200
+ for athlete_type in athlete_types:
201
+ st.write(f"- {athlete_type}")
202
+ with col3:
203
+ st.write("**Infrastructure Types:**")
204
+ for infra_type in infrastructure_types:
205
+ st.write(f"- {infra_type}")
206
 
207
+ # Socio-economic impact analysis
208
+ st.subheader("Socio-Economic Impact Analysis")
209
+ socio_economic_prompt = (
210
+ f"Based on the climate conditions and sports analysis for {region}, Kenya, "
211
+ f"provide a brief assessment of the socio-economic implications, including impacts on: "
212
+ f"1) Local economy, 2) Community health, 3) Sports tourism, 4) Equitable access to sports facilities. "
213
+ f"Consider the specific context of Kenya and the selected region. and make the response very precise and short, do not yap"
214
+ )
215
 
216
+ with st.spinner("Analyzing socio-economic impacts..."):
217
+ socio_economic_response = call_ai_model_analysis(socio_economic_prompt)
218
+ socio_economic_text = ""
219
+ for line in socio_economic_response.iter_lines():
220
+ if line:
221
+ line_content = line.decode('utf-8')
222
+ if line_content.startswith("data: "):
223
+ line_content = line_content[6:]
224
+ try:
225
+ json_data = json.loads(line_content)
226
+ if "choices" in json_data:
227
+ delta = json_data["choices"][0]["delta"]
228
+ if "content" in delta:
229
+ socio_economic_text += delta["content"]
230
+ except json.JSONDecodeError:
231
+ continue
232
 
233
+ st.markdown(socio_economic_text.strip())
234
 
235
+ # Mitigation strategies
236
+ st.subheader("Mitigation Strategies")
237
+ mitigation_prompt = (
238
+ f"Based on the climate conditions and sports analysis for {region}, Kenya, "
239
+ f"suggest specific mitigation strategies for: "
240
+ f"1) Improving athlete performance and health, 2) Enhancing infrastructure resilience, "
241
+ f"3) Ensuring equitable access to sports facilities. "
242
+ f"Consider the specific context of Kenya and the selected region. And make the response very precise and short, do not yap"
243
+ )
244
 
245
+ with st.spinner("Generating mitigation strategies..."):
246
+ mitigation_response = call_ai_model_analysis(mitigation_prompt)
247
+ mitigation_text = ""
248
+ for line in mitigation_response.iter_lines():
249
+ if line:
250
+ line_content = line.decode('utf-8')
251
+ if line_content.startswith("data: "):
252
+ line_content = line_content[6:]
253
+ try:
254
+ json_data = json.loads(line_content)
255
+ if "choices" in json_data:
256
+ delta = json_data["choices"][0]["delta"]
257
+ if "content" in delta:
258
+ mitigation_text += delta["content"]
259
+ except json.JSONDecodeError:
260
+ continue
261
 
262
+ st.markdown(mitigation_text.strip())
263
 
264
+ # Display raw analysis result for debugging
265
+ with st.expander("Show Raw Analysis"):
266
+ st.text(initial_text)
267
 
268
  except ValueError as ve:
269
  st.error(f"Configuration error: {ve}")
270
  except requests.exceptions.RequestException as re:
271
  st.error(f"Request error: {re}")
272
  except Exception as e:
273
+ st.error(f"An unexpected error occurred: {e}")