Spaces:
Sleeping
Sleeping
import streamlit as st | |
import requests | |
import os | |
import json | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
# Function to call the Together API with the provided 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 | |
# Streamlit app layout | |
st.title("Impact of Climate on Sports Using AI") | |
st.write("Predict and mitigate the impacts of climate change on sports performance and infrastructure.") | |
# Input fields for user to enter data | |
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) | |
if st.button("Generate Prediction"): | |
all_message = ( | |
f"Predict the impact on sports performance and infrastructure given the following climate conditions: " | |
f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, UV Index {uv_index}." | |
) | |
try: | |
with st.spinner("Generating response..."): | |
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 | |
# Display concise response and conclusion | |
st.success("Response generated!") | |
# Constructing the summary and conclusion | |
summary = f"**Impact Summary:** {generated_text.strip()}\n" | |
conclusion = "**Conclusion:** Proper adaptation to these climate conditions is essential for maintaining sports performance and infrastructure resilience." | |
# Display text | |
st.markdown(summary) | |
st.markdown(conclusion) | |
# Example data for charts | |
data = { | |
'Condition': ['Temperature', 'Humidity', 'Wind Speed', 'UV Index'], | |
'Value': [temperature, humidity, wind_speed, uv_index] | |
} | |
df = pd.DataFrame(data) | |
# Displaying a table | |
st.table(df) | |
# Plotting a bar chart | |
fig, ax = plt.subplots() | |
ax.bar(data['Condition'], data['Value'], color=['blue', 'green', 'orange', 'red']) | |
ax.set_ylabel('Value') | |
ax.set_title('Climate Condition Impact Indicators') | |
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}") | |