ogegadavis254 commited on
Commit
df306bb
·
verified ·
1 Parent(s): 27e53dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -118
app.py CHANGED
@@ -35,34 +35,31 @@ def call_ai_model(all_message):
35
 
36
  return response
37
 
38
- # Function to generate performance data
39
- def generate_performance_data(temperature_range):
40
- performance_data = []
41
- for temp in temperature_range:
42
- message = (
43
- f"Generate performance data for a sport under the following condition: "
44
- f"Temperature {temp}°C. Provide a single value for performance."
45
- )
46
- response = call_ai_model(message)
47
-
48
- performance_value = ""
49
- for line in response.iter_lines():
50
- if line:
51
- line_content = line.decode('utf-8')
52
- if line_content.startswith("data: "):
53
- line_content = line_content[6:] # Strip "data: " prefix
54
- try:
55
- json_data = json.loads(line_content)
56
- if "choices" in json_data:
57
- delta = json_data["choices"][0]["delta"]
58
- if "content" in delta:
59
- performance_value += delta["content"]
60
- except json.JSONDecodeError:
61
- continue
62
-
63
- performance_data.append(float(performance_value.strip()))
64
-
65
- return performance_data
66
 
67
  # Streamlit app layout
68
  st.title("Climate Impact on Sports Performance and Infrastructure")
@@ -77,114 +74,86 @@ air_quality_index = st.number_input("Air Quality Index:", min_value=0, max_value
77
  precipitation = st.number_input("Precipitation (mm):", min_value=0.0, max_value=500.0, value=10.0)
78
  atmospheric_pressure = st.number_input("Atmospheric Pressure (hPa):", min_value=900, max_value=1100, value=1013)
79
 
80
- # Geographic location input
81
  latitude = st.number_input("Latitude:", min_value=-90.0, max_value=90.0, value=0.0)
82
  longitude = st.number_input("Longitude:", min_value=-180.0, max_value=180.0, value=0.0)
83
 
 
 
 
 
 
 
 
 
 
 
84
  if st.button("Generate Prediction"):
85
  all_message = (
86
  f"Assess the impact on sports performance and infrastructure based on climate conditions: "
87
  f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, UV Index {uv_index}, "
88
  f"Air Quality Index {air_quality_index}, Precipitation {precipitation} mm, Atmospheric Pressure {atmospheric_pressure} hPa. "
89
- f"Location: Latitude {latitude}, Longitude {longitude}."
90
- f"After analyzing that, visualize the data in the best way possible, might be in a table, using a chart or any other way so that it could be easy to understand"
91
  )
92
 
93
  try:
94
- placeholder = st.empty()
95
-
96
- with placeholder.container():
97
- st.info("Collecting climate data...")
98
- time.sleep(1)
99
- placeholder.empty()
100
-
101
- with placeholder.container():
102
- st.info("Analyzing temperature data...")
103
- time.sleep(1)
104
- placeholder.empty()
105
-
106
- with placeholder.container():
107
- st.info("Evaluating humidity levels...")
108
- time.sleep(1)
109
- placeholder.empty()
110
-
111
- with placeholder.container():
112
- st.info("Assessing wind conditions...")
113
- time.sleep(1)
114
- placeholder.empty()
115
 
116
- with placeholder.container():
117
- st.info("Checking UV index...")
118
- time.sleep(1)
119
- placeholder.empty()
120
 
121
- with placeholder.container():
122
- st.info("Measuring air quality..")
123
- time.sleep(1)
124
- placeholder.empty()
125
-
126
- with placeholder.container():
127
- st.info("Calculating precipitation effects...")
128
- time.sleep(1)
129
- placeholder.empty()
 
 
 
 
 
130
 
131
- with placeholder.container():
132
- st.info("Analyzing atmospheric pressure...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  time.sleep(1)
134
- placeholder.empty()
135
-
136
- with st.spinner("Finalizing predictions..."):
137
- response = call_ai_model(all_message)
138
 
139
- generated_text = ""
140
- for line in response.iter_lines():
141
- if line:
142
- line_content = line.decode('utf-8')
143
- if line_content.startswith("data: "):
144
- line_content = line_content[6:] # Strip "data: " prefix
145
- try:
146
- json_data = json.loads(line_content)
147
- if "choices" in json_data:
148
- delta = json_data["choices"][0]["delta"]
149
- if "content" in delta:
150
- generated_text += delta["content"]
151
- except json.JSONDecodeError:
152
- continue
153
-
154
- st.success("Response generated!")
155
-
156
- # Prepare data for visualization
157
- results_data = {
158
- "Condition": ["Temperature", "Humidity", "Wind Speed", "UV Index", "Air Quality Index", "Precipitation", "Atmospheric Pressure"],
159
- "Value": [temperature, humidity, wind_speed, uv_index, air_quality_index, precipitation, atmospheric_pressure]
160
- }
161
- results_df = pd.DataFrame(results_data)
162
-
163
- # Display results in a table
164
- st.subheader("Results Summary")
165
- st.table(results_df)
166
-
167
- # Display prediction
168
- st.markdown("**Predicted Impact on Performance and Infrastructure:**")
169
- st.markdown(generated_text.strip())
170
-
171
- # Generate performance data for different temperatures
172
- temp_range = [temperature - 5, temperature, temperature + 5]
173
- performance_values = generate_performance_data(temp_range)
174
-
175
- # Create a dataframe for performance values
176
- performance_df = pd.DataFrame({
177
- "Temperature": temp_range,
178
- "Performance": performance_values
179
- })
180
-
181
- # Generate a line chart to show the relationship between temperature and performance
182
  fig, ax = plt.subplots()
183
- ax.plot(performance_df["Temperature"], performance_df["Performance"], marker='o', label="Performance")
184
  ax.set_xlabel('Temperature (°C)')
185
- ax.set_ylabel('Performance')
186
- ax.set_title('Relationship Between Temperature and Sports Performance')
187
- ax.legend()
188
  st.pyplot(fig)
189
 
190
  except ValueError as ve:
 
35
 
36
  return response
37
 
38
+ # Function to request numerical performance data from AI
39
+ def get_performance_data(temperature):
40
+ all_message = (
41
+ f"Provide the expected sports performance value (as a numerical score) at a temperature of {temperature}°C."
42
+ )
43
+ response = call_ai_model(all_message)
44
+ generated_text = ""
45
+ for line in response.iter_lines():
46
+ if line:
47
+ line_content = line.decode('utf-8')
48
+ if line_content.startswith("data: "):
49
+ line_content = line_content[6:] # Strip "data: " prefix
50
+ try:
51
+ json_data = json.loads(line_content)
52
+ if "choices" in json_data:
53
+ delta = json_data["choices"][0]["delta"]
54
+ if "content" in delta:
55
+ generated_text += delta["content"]
56
+ except json.JSONDecodeError:
57
+ continue
58
+ try:
59
+ return float(generated_text.strip())
60
+ except ValueError:
61
+ st.warning(f"Could not convert the response to a float: {generated_text}")
62
+ return None
 
 
 
63
 
64
  # Streamlit app layout
65
  st.title("Climate Impact on Sports Performance and Infrastructure")
 
74
  precipitation = st.number_input("Precipitation (mm):", min_value=0.0, max_value=500.0, value=10.0)
75
  atmospheric_pressure = st.number_input("Atmospheric Pressure (hPa):", min_value=900, max_value=1100, value=1013)
76
 
77
+ # Geographical location input
78
  latitude = st.number_input("Latitude:", min_value=-90.0, max_value=90.0, value=0.0)
79
  longitude = st.number_input("Longitude:", min_value=-180.0, max_value=180.0, value=0.0)
80
 
81
+ # Athlete-specific data
82
+ age = st.number_input("Athlete Age:", min_value=0, max_value=100, value=25)
83
+ sport = st.selectbox("Select Sport:", ["Running", "Cycling", "Swimming", "Football", "Basketball"])
84
+ performance_history = st.text_area("Athlete Performance History:")
85
+
86
+ # Infrastructure characteristics
87
+ facility_type = st.selectbox("Facility Type:", ["Stadium", "Gymnasium", "Outdoor Field"])
88
+ facility_age = st.number_input("Facility Age (years):", min_value=0, max_value=100, value=10)
89
+ materials_used = st.text_input("Materials Used in Construction:")
90
+
91
  if st.button("Generate Prediction"):
92
  all_message = (
93
  f"Assess the impact on sports performance and infrastructure based on climate conditions: "
94
  f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, UV Index {uv_index}, "
95
  f"Air Quality Index {air_quality_index}, Precipitation {precipitation} mm, Atmospheric Pressure {atmospheric_pressure} hPa. "
96
+ f"Location: Latitude {latitude}, Longitude {longitude}. "
97
+ f"Athlete (Age: {age}, Sport: {sport}), Facility (Type: {facility_type}, Age: {facility_age}, Materials: {materials_used})."
98
  )
99
 
100
  try:
101
+ with st.spinner("Analyzing climate conditions..."):
102
+ response = call_ai_model(all_message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
+ st.success("Initial analysis complete. Generating detailed predictions...")
 
 
 
105
 
106
+ generated_text = ""
107
+ for line in response.iter_lines():
108
+ if line:
109
+ line_content = line.decode('utf-8')
110
+ if line_content.startswith("data: "):
111
+ line_content = line_content[6:] # Strip "data: " prefix
112
+ try:
113
+ json_data = json.loads(line_content)
114
+ if "choices" in json_data:
115
+ delta = json_data["choices"][0]["delta"]
116
+ if "content" in delta:
117
+ generated_text += delta["content"]
118
+ except json.JSONDecodeError:
119
+ continue
120
 
121
+ st.success("Detailed predictions generated. Preparing visualizations...")
122
+
123
+ # Prepare data for visualization
124
+ results_data = {
125
+ "Condition": ["Temperature", "Humidity", "Wind Speed", "UV Index", "Air Quality Index", "Precipitation", "Atmospheric Pressure"],
126
+ "Value": [temperature, humidity, wind_speed, uv_index, air_quality_index, precipitation, atmospheric_pressure]
127
+ }
128
+ results_df = pd.DataFrame(results_data)
129
+
130
+ # Display results in a table
131
+ st.subheader("Results Summary")
132
+ st.table(results_df)
133
+
134
+ # Display prediction
135
+ st.markdown("**Predicted Impact on Performance and Infrastructure:**")
136
+ st.markdown(generated_text.strip())
137
+
138
+ st.success("Visualizations ready. Generating performance data...")
139
+
140
+ # Generate performance data for different temperatures
141
+ temperatures = range(-10, 41, 5) # Temperatures from -10°C to 40°C in 5°C increments
142
+ performance_values = []
143
+ for temp in temperatures:
144
+ st.spinner(f"Fetching performance data for {temp}°C...")
145
+ performance_value = get_performance_data(temp)
146
+ if performance_value is not None:
147
+ performance_values.append(performance_value)
148
  time.sleep(1)
 
 
 
 
149
 
150
+ if performance_values:
151
+ # Generate line graph
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  fig, ax = plt.subplots()
153
+ ax.plot(temperatures, performance_values, marker='o')
154
  ax.set_xlabel('Temperature (°C)')
155
+ ax.set_ylabel('Performance Score')
156
+ ax.set_title('Temperature vs. Sports Performance')
 
157
  st.pyplot(fig)
158
 
159
  except ValueError as ve: