Spaces:
Runtime error
Runtime error
import streamlit as st | |
import requests | |
import os | |
import json | |
import pandas as pd | |
import plotly.graph_objects as go | |
import time | |
# Function to call the Together AI model for the initial analysis | |
def call_ai_model_initial(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 call the Together AI model for analyzing the text and computing performance score | |
def call_ai_model_analysis(analysis_text): | |
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": analysis_text}], | |
"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 | |
# Streamlit app layout | |
st.title("Climate Impact on Sports Performance and Infrastructure in Kenya") | |
st.write("Analyze and visualize the impact of climate conditions on sports performance and infrastructure, with a focus on Kenya.") | |
# 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) | |
# Kenya-specific inputs | |
region = st.text_input("Enter region in Kenya:") | |
elevation = st.number_input("Elevation (m):", min_value=0, max_value=5000, value=1000) | |
# Sports and athlete inputs | |
sports = st.multiselect("Select sports:", ["Athletics", "Football", "Rugby", "Volleyball", "Boxing", "Swimming"]) | |
athlete_types = st.multiselect("Select athlete types:", ["Professional", "Amateur", "Youth", "Senior"]) | |
# Infrastructure inputs | |
infrastructure_types = st.multiselect("Select infrastructure types:", ["Outdoor Stadium", "Indoor Arena", "Training Facility", "Community Sports Ground"]) | |
if st.button("Generate Prediction and Analysis"): | |
all_message = ( | |
f"Assess the impact on sports performance, athletes, and infrastructure in Kenya 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"Region: {region}, Elevation: {elevation}m. " | |
f"Sports: {', '.join(sports)}. Athlete types: {', '.join(athlete_types)}. " | |
f"Infrastructure types: {', '.join(infrastructure_types)}. " | |
f"Provide a detailed analysis of how these conditions affect performance, health, and infrastructure in Kenya. " | |
f"Include specific impacts for each sport, athlete type, and infrastructure type. " | |
f"Also, provide an overall performance score and an infrastructure impact score, both as percentages. " | |
f"Suggest mitigation strategies for both performance and infrastructure. " | |
f"Assess the socio-economic implications of these climate impacts on sports in Kenya, including equitable access to sports facilities. " | |
f"Organize the information in tables with the following columns: Climate Conditions, Impact on Sports Performance, " | |
f"Impact on Athletes' Health, Impact on Infrastructure, Mitigation Strategies, Socio-Economic Implications. " | |
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." | |
) | |
try: | |
stages = [ | |
"Analyzing climate conditions...", | |
"Checking location data...", | |
"Fetching historical data...", | |
"Running simulations...", | |
"Processing current weather...", | |
"Assessing environmental factors...", | |
"Calculating predictions...", | |
"Compiling results...", | |
"Finalizing analysis...", | |
"Preparing output..." | |
] | |
with st.spinner("Analyzing climate conditions and generating predictions..."): | |
# Loop through each stage, updating the spinner text and waiting for 2 seconds | |
for stage in stages: | |
st.spinner(stage) | |
time.sleep(2) | |
initial_response = call_ai_model_initial(all_message) | |
initial_text = "" | |
for line in initial_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: | |
initial_text += delta["content"] | |
except json.JSONDecodeError: | |
continue | |
st.success("Analysis completed!") | |
# Display prediction | |
st.subheader("Climate Impact Analysis for Sports in Kenya") | |
st.markdown(initial_text.strip()) | |
# Extract and display scores | |
performance_score = "N/A" | |
infrastructure_score = "N/A" | |
for line in initial_text.split('\n'): | |
if "performance score:" in line.lower(): | |
performance_score = line.split(":")[-1].strip() | |
elif "infrastructure impact score:" in line.lower(): | |
infrastructure_score = line.split(":")[-1].strip() | |
# Display performance and infrastructure scores | |
col1, col2 = st.columns(2) | |
with col1: | |
st.metric("Overall Performance Score", performance_score) | |
with col2: | |
st.metric("Infrastructure Impact Score", infrastructure_score) | |
# 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("Climate Conditions Summary") | |
st.table(results_df) | |
# Create a radar chart for climate conditions | |
fig = go.Figure(data=go.Scatterpolar( | |
r=[temperature/50*100, humidity, wind_speed/2, uv_index/11*100, air_quality_index/5, precipitation/5, (atmospheric_pressure-900)/2], | |
theta=results_df['Condition'], | |
fill='toself' | |
)) | |
fig.update_layout( | |
polar=dict( | |
radialaxis=dict(visible=True, range=[0, 100]) | |
), | |
showlegend=False | |
) | |
st.plotly_chart(fig) | |
# Display analyzed sports and infrastructure | |
st.subheader("Analyzed Components") | |
col1, col2, col3 = st.columns(3) | |
with col1: | |
st.write("**Sports:**") | |
for sport in sports: | |
st.write(f"- {sport}") | |
with col2: | |
st.write("**Athlete Types:**") | |
for athlete_type in athlete_types: | |
st.write(f"- {athlete_type}") | |
with col3: | |
st.write("**Infrastructure Types:**") | |
for infra_type in infrastructure_types: | |
st.write(f"- {infra_type}") | |
# Socio-economic impact analysis | |
st.subheader("Socio-Economic Impact Analysis") | |
socio_economic_prompt = ( | |
f"Based on the climate conditions and sports analysis for {region}, Kenya, " | |
f"provide a brief assessment of the socio-economic implications, including impacts on: " | |
f"1) Local economy, 2) Community health, 3) Sports tourism, 4) Equitable access to sports facilities. " | |
f"Consider the specific context of Kenya and the selected region. and make the response very precise and short, do not yap" | |
) | |
with st.spinner("Analyzing socio-economic impacts..."): | |
socio_economic_response = call_ai_model_analysis(socio_economic_prompt) | |
socio_economic_text = "" | |
for line in socio_economic_response.iter_lines(): | |
if line: | |
line_content = line.decode('utf-8') | |
if line_content.startswith("data: "): | |
line_content = line_content[6:] | |
try: | |
json_data = json.loads(line_content) | |
if "choices" in json_data: | |
delta = json_data["choices"][0]["delta"] | |
if "content" in delta: | |
socio_economic_text += delta["content"] | |
except json.JSONDecodeError: | |
continue | |
st.markdown(socio_economic_text.strip()) | |
# Mitigation strategies | |
st.subheader("Mitigation Strategies") | |
mitigation_prompt = ( | |
f"Based on the climate conditions and sports analysis for {region}, Kenya, " | |
f"suggest specific mitigation strategies for: " | |
f"1) Improving athlete performance and health, 2) Enhancing infrastructure resilience, " | |
f"3) Ensuring equitable access to sports facilities. " | |
f"Consider the specific context of Kenya and the selected region. And make the response very precise and short, do not yap" | |
) | |
with st.spinner("Generating mitigation strategies..."): | |
mitigation_response = call_ai_model_analysis(mitigation_prompt) | |
mitigation_text = "" | |
for line in mitigation_response.iter_lines(): | |
if line: | |
line_content = line.decode('utf-8') | |
if line_content.startswith("data: "): | |
line_content = line_content[6:] | |
try: | |
json_data = json.loads(line_content) | |
if "choices" in json_data: | |
delta = json_data["choices"][0]["delta"] | |
if "content" in delta: | |
mitigation_text += delta["content"] | |
except json.JSONDecodeError: | |
continue | |
st.markdown(mitigation_text.strip()) | |
# Display raw analysis result for debugging | |
with st.expander("Show Raw Analysis"): | |
st.text(initial_text) | |
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}") | |