ogegadavis254 commited on
Commit
bf0b824
1 Parent(s): 7fcff87

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -70
app.py CHANGED
@@ -3,7 +3,6 @@ import requests
3
  import os
4
  import json
5
  import pandas as pd
6
- import time
7
  import matplotlib.pyplot as plt
8
 
9
  # Function to call the Together AI model
@@ -35,10 +34,14 @@ def call_ai_model(all_message):
35
 
36
  return response
37
 
38
- # Function to request numeric performance data from AI
39
- def get_numeric_performance_data(temperature):
40
  all_message = (
41
- f"Provide the expected numeric sports performance value (as a score) at a temperature of {temperature}°C."
 
 
 
 
42
  )
43
  response = call_ai_model(all_message)
44
  generated_text = ""
@@ -51,15 +54,20 @@ def get_numeric_performance_data(temperature):
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 and delta["content"].strip().replace('.', '', 1).isdigit():
55
- return float(delta["content"].strip())
56
  except json.JSONDecodeError:
57
  continue
58
- return None
 
 
 
 
 
59
 
60
  # Streamlit app layout
61
- st.title("Climate Impact on Sports Performance and Infrastructure")
62
- st.write("Analyze and visualize the impact of climate conditions on sports performance and infrastructure.")
63
 
64
  # Inputs for climate conditions
65
  temperature = st.number_input("Temperature (°C):", min_value=-50, max_value=50, value=25)
@@ -70,70 +78,57 @@ air_quality_index = st.number_input("Air Quality Index:", min_value=0, max_value
70
  precipitation = st.number_input("Precipitation (mm):", min_value=0.0, max_value=500.0, value=10.0)
71
  atmospheric_pressure = st.number_input("Atmospheric Pressure (hPa):", min_value=900, max_value=1100, value=1013)
72
 
 
73
  if st.button("Generate Prediction"):
74
- all_message = (
75
- f"Assess the impact on sports performance and infrastructure based on climate conditions: "
76
- f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, UV Index {uv_index}, "
77
- f"Air Quality Index {air_quality_index}, Precipitation {precipitation} mm, Atmospheric Pressure {atmospheric_pressure} hPa."
78
- )
 
 
 
 
79
 
80
  try:
81
- with st.spinner("Analyzing climate conditions..."):
82
- response = call_ai_model(all_message)
83
-
84
- st.success("Initial analysis complete. Generating detailed predictions...")
85
-
86
- generated_text = ""
87
- for line in response.iter_lines():
88
- if line:
89
- line_content = line.decode('utf-8')
90
- if line_content.startswith("data: "):
91
- line_content = line_content[6:] # Strip "data: " prefix
92
- try:
93
- json_data = json.loads(line_content)
94
- if "choices" in json_data:
95
- delta = json_data["choices"][0]["delta"]
96
- if "content" in delta and delta["content"].strip().replace('.', '', 1).isdigit():
97
- generated_text += delta["content"]
98
- except json.JSONDecodeError:
99
- continue
100
-
101
- st.success("Detailed predictions generated.")
102
-
103
- # Prepare data for visualization
104
- results_data = {
105
- "Condition": ["Temperature", "Humidity", "Wind Speed", "UV Index", "Air Quality Index", "Precipitation", "Atmospheric Pressure"],
106
- "Value": [temperature, humidity, wind_speed, uv_index, air_quality_index, precipitation, atmospheric_pressure]
107
- }
108
- results_df = pd.DataFrame(results_data)
109
-
110
- # Display results in a table
111
- st.subheader("Results Summary")
112
- st.table(results_df)
113
-
114
- # Display prediction
115
- st.markdown("**Predicted Impact on Performance and Infrastructure:**")
116
- st.markdown(generated_text.strip())
117
-
118
- st.success("Generating performance data...")
119
-
120
- # Generate numeric performance data for different temperatures
121
- temperatures = range(-10, 41, 5) # Temperatures from -10°C to 40°C in 5°C increments
122
- performance_values = []
123
- for temp in temperatures:
124
- st.spinner(f"Fetching performance data for {temp}°C...")
125
- performance_value = get_numeric_performance_data(temp)
126
- if performance_value is not None:
127
- performance_values.append(performance_value)
128
- time.sleep(1)
129
-
130
- if performance_values:
131
- # Generate line graph
132
- fig, ax = plt.subplots()
133
- ax.plot(temperatures, performance_values, marker='o')
134
- ax.set_xlabel('Temperature (°C)')
135
- ax.set_ylabel('Performance Score')
136
- ax.set_title('Temperature vs. Numeric Sports Performance')
137
  st.pyplot(fig)
138
 
139
  except ValueError as ve:
 
3
  import os
4
  import json
5
  import pandas as pd
 
6
  import matplotlib.pyplot as plt
7
 
8
  # Function to call the Together AI model
 
34
 
35
  return response
36
 
37
+ # Function to request performance data from AI
38
+ def get_performance_data(conditions):
39
  all_message = (
40
+ f"Provide the expected sports performance score at conditions: "
41
+ f"Temperature {conditions['temperature']}°C, Humidity {conditions['humidity']}%, "
42
+ f"Wind Speed {conditions['wind_speed']} km/h, UV Index {conditions['uv_index']}, "
43
+ f"Air Quality Index {conditions['air_quality_index']}, Precipitation {conditions['precipitation']} mm, "
44
+ f"Atmospheric Pressure {conditions['atmospheric_pressure']} hPa."
45
  )
46
  response = call_ai_model(all_message)
47
  generated_text = ""
 
54
  json_data = json.loads(line_content)
55
  if "choices" in json_data:
56
  delta = json_data["choices"][0]["delta"]
57
+ if "content" in delta:
58
+ generated_text += delta["content"]
59
  except json.JSONDecodeError:
60
  continue
61
+
62
+ try:
63
+ return float(generated_text.strip())
64
+ except ValueError:
65
+ st.warning(f"Could not convert the response to a float: {generated_text}")
66
+ return None
67
 
68
  # Streamlit app layout
69
+ st.title("Climate Impact on Sports Performance")
70
+ st.write("Analyze and visualize the impact of climate conditions on sports performance.")
71
 
72
  # Inputs for climate conditions
73
  temperature = st.number_input("Temperature (°C):", min_value=-50, max_value=50, value=25)
 
78
  precipitation = st.number_input("Precipitation (mm):", min_value=0.0, max_value=500.0, value=10.0)
79
  atmospheric_pressure = st.number_input("Atmospheric Pressure (hPa):", min_value=900, max_value=1100, value=1013)
80
 
81
+ # Button to generate predictions
82
  if st.button("Generate Prediction"):
83
+ conditions = {
84
+ "temperature": temperature,
85
+ "humidity": humidity,
86
+ "wind_speed": wind_speed,
87
+ "uv_index": uv_index,
88
+ "air_quality_index": air_quality_index,
89
+ "precipitation": precipitation,
90
+ "atmospheric_pressure": atmospheric_pressure
91
+ }
92
 
93
  try:
94
+ with st.spinner("Generating predictions..."):
95
+ # Call AI model to get initial prediction and qualitative assessment
96
+ response = call_ai_model(f"Assess the impact on sports performance at conditions: "
97
+ f"Temperature {temperature}°C, Humidity {humidity}%, "
98
+ f"Wind Speed {wind_speed} km/h, UV Index {uv_index}, "
99
+ f"Air Quality Index {air_quality_index}, Precipitation {precipitation} mm, "
100
+ f"Atmospheric Pressure {atmospheric_pressure} hPa.")
101
+
102
+ st.success("Initial analysis complete.")
103
+
104
+ # Get performance score for specified conditions
105
+ performance_score = get_performance_data(conditions)
106
+ if performance_score is not None:
107
+ st.success("Performance data fetched successfully.")
108
+ else:
109
+ st.warning("Failed to fetch performance data.")
110
+
111
+ # Plotting the data
112
+ if performance_score is not None:
113
+ # Prepare data for plotting
114
+ climate_conditions = list(conditions.keys())
115
+ climate_values = list(conditions.values())
116
+
117
+ fig, ax1 = plt.subplots()
118
+
119
+ # Plot climate conditions on the primary y-axis
120
+ ax1.plot(climate_conditions, climate_values, marker='o', color='b', label='Climate Conditions')
121
+ ax1.set_xlabel('Climate Conditions')
122
+ ax1.set_ylabel('Values', color='b')
123
+ ax1.tick_params(axis='y', labelcolor='b')
124
+
125
+ # Create a secondary y-axis for performance score
126
+ ax2 = ax1.twinx()
127
+ ax2.plot(['Performance Score'], [performance_score], marker='s', color='r', label='Performance Score')
128
+ ax2.set_ylabel('Performance Score', color='r')
129
+ ax2.tick_params(axis='y', labelcolor='r')
130
+
131
+ fig.tight_layout()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  st.pyplot(fig)
133
 
134
  except ValueError as ve: