ogegadavis254 commited on
Commit
a645649
1 Parent(s): 0957448

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -20
app.py CHANGED
@@ -2,9 +2,10 @@ import streamlit as st
2
  import requests
3
  import os
4
  import json
 
5
 
6
- # Function to call the Together AI model
7
- def call_ai_model(all_message):
8
  url = "https://api.together.xyz/v1/chat/completions"
9
  payload = {
10
  "model": "NousResearch/Nous-Hermes-2-Yi-34B",
@@ -32,9 +33,38 @@ def call_ai_model(all_message):
32
 
33
  return response
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  # Streamlit app layout
36
- st.title("Climate Impact on Sports Performance")
37
- st.write("Analyze and visualize the impact of climate conditions on sports performance.")
38
 
39
  # Inputs for climate conditions
40
  temperature = st.number_input("Temperature (°C):", min_value=-50, max_value=50, value=25)
@@ -45,31 +75,87 @@ air_quality_index = st.number_input("Air Quality Index:", min_value=0, max_value
45
  precipitation = st.number_input("Precipitation (mm):", min_value=0.0, max_value=500.0, value=10.0)
46
  atmospheric_pressure = st.number_input("Atmospheric Pressure (hPa):", min_value=900, max_value=1100, value=1013)
47
 
48
- # Button to generate predictions
 
 
 
49
  if st.button("Generate Prediction"):
50
  all_message = (
51
- f"Assess the impact on sports performance based on climate conditions: "
52
- f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, "
53
- f"UV Index {uv_index}, Air Quality Index {air_quality_index}, "
54
- f"Precipitation {precipitation} mm, Atmospheric Pressure {atmospheric_pressure} hPa."
 
55
  )
56
 
57
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  with st.spinner("Generating predictions..."):
59
- # Call AI model to get qualitative analysis
60
- qualitative_analysis = (
61
- f"Analyze the impact on sports performance under the following conditions: "
62
- f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, "
63
- f"UV Index {uv_index}, Air Quality Index {air_quality_index}, "
64
- f"Precipitation {precipitation} mm, Atmospheric Pressure {atmospheric_pressure} hPa."
65
  )
66
- qualitative_result = call_ai_model(qualitative_analysis)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- st.success("Predictions generated.")
 
 
69
 
70
- # Display qualitative analysis
71
- st.subheader("Qualitative Analysis")
72
- st.write(qualitative_result)
73
 
74
  except ValueError as ve:
75
  st.error(f"Configuration error: {ve}")
 
2
  import requests
3
  import os
4
  import json
5
+ import pandas as pd
6
 
7
+ # Function to call the Together AI model for the initial analysis
8
+ def call_ai_model_initial(all_message):
9
  url = "https://api.together.xyz/v1/chat/completions"
10
  payload = {
11
  "model": "NousResearch/Nous-Hermes-2-Yi-34B",
 
33
 
34
  return response
35
 
36
+ # Function to call the Together AI model for analyzing the text and computing performance score
37
+ def call_ai_model_analysis(analysis_text):
38
+ url = "https://api.together.xyz/v1/chat/completions"
39
+ payload = {
40
+ "model": "NousResearch/Nous-Hermes-2-Yi-34B",
41
+ "temperature": 1.05,
42
+ "top_p": 0.9,
43
+ "top_k": 50,
44
+ "repetition_penalty": 1,
45
+ "n": 1,
46
+ "messages": [{"role": "user", "content": analysis_text}],
47
+ "stream_tokens": True,
48
+ }
49
+
50
+ TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')
51
+ if TOGETHER_API_KEY is None:
52
+ raise ValueError("TOGETHER_API_KEY environment variable not set.")
53
+
54
+ headers = {
55
+ "accept": "application/json",
56
+ "content-type": "application/json",
57
+ "Authorization": f"Bearer {TOGETHER_API_KEY}",
58
+ }
59
+
60
+ response = requests.post(url, json=payload, headers=headers, stream=True)
61
+ response.raise_for_status() # Ensure HTTP request was successful
62
+
63
+ return response
64
+
65
  # Streamlit app layout
66
+ st.title("Climate Impact on Sports Performance and Infrastructure")
67
+ st.write("Analyze and visualize the impact of climate conditions on sports performance and infrastructure.")
68
 
69
  # Inputs for climate conditions
70
  temperature = st.number_input("Temperature (°C):", min_value=-50, max_value=50, value=25)
 
75
  precipitation = st.number_input("Precipitation (mm):", min_value=0.0, max_value=500.0, value=10.0)
76
  atmospheric_pressure = st.number_input("Atmospheric Pressure (hPa):", min_value=900, max_value=1100, value=1013)
77
 
78
+ # Geographic location input
79
+ latitude = st.number_input("Latitude:", min_value=-90.0, max_value=90.0, value=0.0)
80
+ longitude = st.number_input("Longitude:", min_value=-180.0, max_value=180.0, value=0.0)
81
+
82
  if st.button("Generate Prediction"):
83
  all_message = (
84
+ f"Assess the impact on sports performance and infrastructure based on climate conditions: "
85
+ f"Temperature {temperature}°C, Humidity {humidity}%, Wind Speed {wind_speed} km/h, UV Index {uv_index}, "
86
+ f"Air Quality Index {air_quality_index}, Precipitation {precipitation} mm, Atmospheric Pressure {atmospheric_pressure} hPa. "
87
+ f"Location: Latitude {latitude}, Longitude {longitude}."
88
+ f"After analyzing that, I want you to 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."
89
  )
90
 
91
  try:
92
+ with st.spinner("Analyzing climate conditions..."):
93
+ initial_response = call_ai_model_initial(all_message)
94
+
95
+ initial_text = ""
96
+ for line in initial_response.iter_lines():
97
+ if line:
98
+ line_content = line.decode('utf-8')
99
+ if line_content.startswith("data: "):
100
+ line_content = line_content[6:] # Strip "data: " prefix
101
+ try:
102
+ json_data = json.loads(line_content)
103
+ if "choices" in json_data:
104
+ delta = json_data["choices"][0]["delta"]
105
+ if "content" in delta:
106
+ initial_text += delta["content"]
107
+ except json.JSONDecodeError:
108
+ continue
109
+
110
+ st.success("Initial analysis completed!")
111
+
112
  with st.spinner("Generating predictions..."):
113
+ analysis_text = (
114
+ f"Analyze the following text and extract a performance score based on the climate conditions and their impact: {initial_text}"
 
 
 
 
115
  )
116
+ analysis_response = call_ai_model_analysis(analysis_text)
117
+
118
+ analysis_result = ""
119
+ for line in analysis_response.iter_lines():
120
+ if line:
121
+ line_content = line.decode('utf-8')
122
+ if line_content.startswith("data: "):
123
+ line_content = line_content[6:] # Strip "data: " prefix
124
+ try:
125
+ json_data = json.loads(line_content)
126
+ if "choices" in json_data:
127
+ delta = json_data["choices"][0]["delta"]
128
+ if "content" in delta:
129
+ analysis_result += delta["content"]
130
+ except json.JSONDecodeError:
131
+ continue
132
+
133
+ st.success("Predictions generated!")
134
+
135
+ # Extract performance score from the analysis result
136
+ # Assuming the performance score is provided in the text as "Performance Score: XX%"
137
+ performance_score = "N/A"
138
+ for line in analysis_result.split('\n'):
139
+ if "Performance Score:" in line:
140
+ performance_score = line.split(":")[1].strip()
141
+
142
+ # Prepare data for visualization
143
+ results_data = {
144
+ "Condition": ["Temperature", "Humidity", "Wind Speed", "UV Index", "Air Quality Index", "Precipitation", "Atmospheric Pressure"],
145
+ "Value": [temperature, humidity, wind_speed, uv_index, air_quality_index, precipitation, atmospheric_pressure]
146
+ }
147
+ results_df = pd.DataFrame(results_data)
148
+
149
+ # Display results in a table
150
+ st.subheader("Results Summary")
151
+ st.table(results_df)
152
 
153
+ # Display prediction
154
+ st.markdown("**Predicted Impact on Performance and Infrastructure:**")
155
+ st.markdown(initial_text.strip())
156
 
157
+ # Display performance score
158
+ st.markdown(f"**Performance Score:** {performance_score}")
 
159
 
160
  except ValueError as ve:
161
  st.error(f"Configuration error: {ve}")