File size: 3,994 Bytes
9f54a3b
71ec4a8
9f54a3b
0e00146
b4026e6
251086d
a9c7401
f689a87
71ec4a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8092b5a
71ec4a8
fa025b1
bf0b824
df306bb
bf0b824
c1cf6d8
df306bb
7fcff87
 
 
 
 
 
 
 
 
 
 
bf0b824
 
7fcff87
 
bf0b824
0efa70b
 
 
7fcff87
 
bf0b824
c1cf6d8
7fcff87
c1cf6d8
7fcff87
 
bf0b824
7fcff87
bf0b824
c1cf6d8
bf0b824
7fcff87
 
bf0b824
0efa70b
fa025b1
c1cf6d8
 
fa025b1
 
 
 
0efa70b
bf0b824
fa025b1
bf0b824
fa025b1
 
 
 
 
 
0efa70b
bf0b824
 
c1cf6d8
fa025b1
c1cf6d8
0efa70b
c1cf6d8
 
0efa70b
c1cf6d8
0efa70b
fa025b1
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
import streamlit as st
import requests
import os
import json
import pandas as pd
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 get performance data from AI
def get_performance_data(conditions):
    all_message = (
        f"Provide the expected sports performance score at conditions: "
        f"Temperature {conditions['temperature']}°C."
    )
    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

    # Example: Replace with actual data from API
    performance_scores = [75, 80, 70, 85, 78, 72, 82]  # Replace with actual data from API
    return performance_scores

# Streamlit app layout
st.title("Climate Impact on Sports Performance")
st.write("Analyze and visualize the impact of temperature on sports performance.")

# Input for temperature
temperature = st.number_input("Temperature (°C):", min_value=-50, max_value=50, value=25)

# Button to generate predictions
if st.button("Generate Prediction"):
    conditions = {
        "temperature": temperature
    }

    try:
        with st.spinner("Generating predictions..."):
            # Call AI model to get qualitative analysis
            qualitative_analysis = (
                f"Assess the impact on sports performance at temperature: "
                f"{temperature}°C."
            )
            qualitative_result = call_ai_model(qualitative_analysis)

            # Get performance score for specified conditions
            performance_scores = get_performance_data(conditions)

        st.success("Predictions generated.")

        # Display qualitative analysis
        st.subheader("Qualitative Analysis")
        st.write(qualitative_result)

        # Display performance score
        st.subheader("Performance Score")
        st.write(f"Predicted Performance Scores: {performance_scores}")

        # Plotting the data
        st.subheader("Performance Score vs Temperature")

        # Plot performance score against temperature
        fig, ax = plt.subplots()
        ax.plot(conditions['temperature'], performance_scores, marker='o', linestyle='-', color='b')
        ax.set_xlabel('Temperature (°C)')
        ax.set_ylabel('Performance Score')
        ax.set_title('Performance Score vs Temperature')
        ax.grid(True)
        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}")