Spaces:
Sleeping
Sleeping
File size: 7,867 Bytes
9f54a3b 71ec4a8 9f54a3b 0e00146 b4026e6 0c48822 251086d a9c7401 f689a87 71ec4a8 8092b5a 71ec4a8 5531c71 71ec4a8 f689a87 71ec4a8 f689a87 b4026e6 8f7d62b 251086d e897423 71ec4a8 b4026e6 f689a87 251086d 5531c71 b4026e6 8f7d62b 71ec4a8 0c48822 8092b5a 8f7d62b 8092b5a e13723a 8f7d62b b4026e6 f689a87 b4026e6 f689a87 b4026e6 5531c71 e003f26 5531c71 251086d 5531c71 e003f26 251086d 71ec4a8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
import streamlit as st
import requests
import os
import json
import pandas as pd
import time
import matplotlib.pyplot as plt
# Function to call the Together AI model
def call_ai_model(all_message):
url = "https://api.together.xyz/v1/chat/completions"
payload = {
"model": "NousResearch/Nous-Hermes-2-Yi-34B",
"temperature": 1.05,
"top_p": 0.9,
"top_k": 50,
"repetition_penalty": 1,
"n": 1,
"messages": [{"role": "user", "content": all_message}],
"stream_tokens": True,
}
TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')
if TOGETHER_API_KEY is None:
raise ValueError("TOGETHER_API_KEY environment variable not set.")
headers = {
"accept": "application/json",
"content-type": "application/json",
"Authorization": f"Bearer {TOGETHER_API_KEY}",
}
response = requests.post(url, json=payload, headers=headers, stream=True)
response.raise_for_status() # Ensure HTTP request was successful
return response
# Function to generate performance data
def generate_performance_data(temperature_range):
performance_data = []
for temp in temperature_range:
message = (
f"Generate performance data for a sport under the following condition: "
f"Temperature {temp}°C. Provide a single value for performance."
)
response = call_ai_model(message)
performance_value = ""
for line in response.iter_lines():
if line:
line_content = line.decode('utf-8')
if line_content.startswith("data: "):
line_content = line_content[6:] # Strip "data: " prefix
try:
json_data = json.loads(line_content)
if "choices" in json_data:
delta = json_data["choices"][0]["delta"]
if "content" in delta:
performance_value += delta["content"]
except json.JSONDecodeError:
continue
performance_data.append(float(performance_value.strip()))
return performance_data
# Streamlit app layout
st.title("Climate Impact on Sports Performance and Infrastructure")
st.write("Analyze and visualize the impact of climate conditions on sports performance and infrastructure.")
# Inputs for climate conditions
temperature = st.number_input("Temperature (°C):", min_value=-50, max_value=50, value=25)
humidity = st.number_input("Humidity (%):", min_value=0, max_value=100, value=50)
wind_speed = st.number_input("Wind Speed (km/h):", min_value=0.0, max_value=200.0, value=15.0)
uv_index = st.number_input("UV Index:", min_value=0, max_value=11, value=5)
air_quality_index = st.number_input("Air Quality Index:", min_value=0, max_value=500, value=100)
precipitation = st.number_input("Precipitation (mm):", min_value=0.0, max_value=500.0, value=10.0)
atmospheric_pressure = st.number_input("Atmospheric Pressure (hPa):", min_value=900, max_value=1100, value=1013)
# Geographic location input
latitude = st.number_input("Latitude:", min_value=-90.0, max_value=90.0, value=0.0)
longitude = st.number_input("Longitude:", min_value=-180.0, max_value=180.0, value=0.0)
if st.button("Generate Prediction"):
all_message = (
f"Assess the impact on sports performance and infrastructure based on climate conditions: "
f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, UV Index {uv_index}, "
f"Air Quality Index {air_quality_index}, Precipitation {precipitation} mm, Atmospheric Pressure {atmospheric_pressure} hPa. "
f"Location: Latitude {latitude}, Longitude {longitude}."
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"
)
try:
placeholder = st.empty()
with placeholder.container():
st.info("Collecting climate data...")
time.sleep(1)
placeholder.empty()
with placeholder.container():
st.info("Analyzing temperature data...")
time.sleep(1)
placeholder.empty()
with placeholder.container():
st.info("Evaluating humidity levels...")
time.sleep(1)
placeholder.empty()
with placeholder.container():
st.info("Assessing wind conditions...")
time.sleep(1)
placeholder.empty()
with placeholder.container():
st.info("Checking UV index...")
time.sleep(1)
placeholder.empty()
with placeholder.container():
st.info("Measuring air quality...")
time.sleep(1)
placeholder.empty()
with placeholder.container():
st.info("Calculating precipitation effects...")
time.sleep(1)
placeholder.empty()
with placeholder.container():
st.info("Analyzing atmospheric pressure...")
time.sleep(1)
placeholder.empty()
with st.spinner("Finalizing predictions..."):
response = call_ai_model(all_message)
generated_text = ""
for line in response.iter_lines():
if line:
line_content = line.decode('utf-8')
if line_content.startswith("data: "):
line_content = line_content[6:] # Strip "data: " prefix
try:
json_data = json.loads(line_content)
if "choices" in json_data:
delta = json_data["choices"][0]["delta"]
if "content" in delta:
generated_text += delta["content"]
except json.JSONDecodeError:
continue
st.success("Response generated!")
# Prepare data for visualization
results_data = {
"Condition": ["Temperature", "Humidity", "Wind Speed", "UV Index", "Air Quality Index", "Precipitation", "Atmospheric Pressure"],
"Value": [temperature, humidity, wind_speed, uv_index, air_quality_index, precipitation, atmospheric_pressure]
}
results_df = pd.DataFrame(results_data)
# Display results in a table
st.subheader("Results Summary")
st.table(results_df)
# Display prediction
st.markdown("**Predicted Impact on Performance and Infrastructure:**")
st.markdown(generated_text.strip())
# Generate performance data for different temperatures
temp_range = [temperature - 5, temperature, temperature + 5]
performance_values = generate_performance_data(temp_range)
# Create a dataframe for performance values
performance_df = pd.DataFrame({
"Temperature": temp_range,
"Performance": performance_values
})
# Generate a line chart to show the relationship between temperature and performance
fig, ax = plt.subplots()
ax.plot(performance_df["Temperature"], performance_df["Performance"], marker='o', label="Performance")
ax.set_xlabel('Temperature (°C)')
ax.set_ylabel('Performance')
ax.set_title('Relationship Between Temperature and Sports Performance')
ax.legend()
st.pyplot(fig)
except ValueError as ve:
st.error(f"Configuration error: {ve}")
except requests.exceptions.RequestException as re:
st.error(f"Request error: {re}")
except Exception as e:
st.error(f"An unexpected error occurred: {e}")
|