Prashanthsrn commited on
Commit
787ee06
Β·
verified Β·
1 Parent(s): a398d45

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -26
app.py CHANGED
@@ -26,11 +26,86 @@ model = genai.GenerativeModel('gemini-pro')
26
  # Streamlit app
27
  st.set_page_config(page_title="Strava Run Analysis", layout="wide")
28
 
29
- # (Custom CSS remains the same)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  st.title("πŸƒβ€β™‚οΈ Strava Run Analysis")
32
 
33
- # (Strava authentication remains the same)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  if 'access_token' in st.session_state:
36
  client.access_token = st.session_state.access_token
@@ -51,20 +126,17 @@ if 'access_token' in st.session_state:
51
  df = pd.DataFrame([{
52
  'name': run.name,
53
  'distance': float(run.distance) / 1000, # Convert to km
54
- 'moving_time': run.moving_time.total_seconds() / 60 if run.moving_time else None, # Convert to minutes, handle None
55
- 'total_elevation_gain': float(run.total_elevation_gain) if run.total_elevation_gain else 0,
56
- 'average_speed': float(run.average_speed) * 3.6 if run.average_speed else None, # Convert to km/h
57
  'average_heartrate': float(run.average_heartrate) if run.average_heartrate else None,
58
- 'start_date': run.start_date.replace(tzinfo=None) if run.start_date else None
59
  } for run in runs])
60
- df['pace'] = df['moving_time'] / df['distance'] if df['moving_time'] is not None else None # Calculate pace (min/km)
61
  return df
62
 
63
  try:
64
  df = fetch_run_activities()
65
- if df.empty:
66
- st.warning("No running activities found. Make sure you have some runs in your Strava account.")
67
- st.stop()
68
  except Exception as e:
69
  st.error(f"Error fetching activities: {str(e)}. Please try again later.")
70
  st.stop()
@@ -79,10 +151,7 @@ if 'access_token' in st.session_state:
79
  st.markdown("<div class='stat-card'><h3>{:.0f} km</h3><p>Total Distance</p></div>".format(df['distance'].sum()), unsafe_allow_html=True)
80
  with col3:
81
  total_time = df['moving_time'].sum()
82
- if pd.notna(total_time):
83
- st.markdown("<div class='stat-card'><h3>{:.0f}h {:.0f}m</h3><p>Total Time</p></div>".format(total_time // 60, total_time % 60), unsafe_allow_html=True)
84
- else:
85
- st.markdown("<div class='stat-card'><h3>N/A</h3><p>Total Time</p></div>", unsafe_allow_html=True)
86
  with col4:
87
  st.markdown("<div class='stat-card'><h3>{:.0f} m</h3><p>Total Elevation Gain</p></div>".format(df['total_elevation_gain'].sum()), unsafe_allow_html=True)
88
 
@@ -90,7 +159,6 @@ if 'access_token' in st.session_state:
90
  st.markdown("<h2 class='section-header'>πŸ“ˆ Run Analysis</h2>", unsafe_allow_html=True)
91
 
92
  # Weekly distance
93
- df['start_date'] = pd.to_datetime(df['start_date'])
94
  weekly_distance = df.resample('W', on='start_date')['distance'].sum().reset_index()
95
  fig_weekly = px.bar(weekly_distance, x='start_date', y='distance',
96
  title="Weekly Running Distance",
@@ -99,17 +167,14 @@ if 'access_token' in st.session_state:
99
  st.plotly_chart(fig_weekly, use_container_width=True)
100
 
101
  # Pace improvement
102
- if df['pace'].notna().any():
103
- df_sorted = df.sort_values('start_date')
104
- fig_pace = px.scatter(df_sorted, x='start_date', y='pace',
105
- title="Running Pace Over Time",
106
- labels={'pace': 'Pace (min/km)', 'start_date': 'Date'})
107
- fig_pace.add_trace(go.Scatter(x=df_sorted['start_date'], y=df_sorted['pace'].rolling(window=10).mean(),
108
- mode='lines', name='10-run moving average'))
109
- fig_pace.update_layout(yaxis_title="Pace (min/km)")
110
- st.plotly_chart(fig_pace, use_container_width=True)
111
- else:
112
- st.info("No pace data available for analysis.")
113
 
114
  # Heart rate improvement (if data available)
115
  if df['average_heartrate'].notna().any():
 
26
  # Streamlit app
27
  st.set_page_config(page_title="Strava Run Analysis", layout="wide")
28
 
29
+ # Custom CSS for better UI
30
+ st.markdown("""
31
+ <style>
32
+ .stApp {
33
+ background-color: #f0f2f6;
34
+ }
35
+ .stButton>button {
36
+ background-color: #fc4c02;
37
+ color: white;
38
+ font-weight: bold;
39
+ border-radius: 5px;
40
+ border: none;
41
+ padding: 0.5rem 1rem;
42
+ }
43
+ .stButton>button:hover {
44
+ background-color: #e34402;
45
+ }
46
+ .stSelectbox {
47
+ color: #333333;
48
+ }
49
+ .stPlotlyChart {
50
+ background-color: white;
51
+ border-radius: 10px;
52
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
53
+ padding: 1rem;
54
+ margin-bottom: 2rem;
55
+ }
56
+ .stat-card {
57
+ background-color: white;
58
+ border-radius: 10px;
59
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
60
+ padding: 1.5rem;
61
+ text-align: center;
62
+ }
63
+ .stat-card h3 {
64
+ color: #fc4c02;
65
+ font-size: 2.5rem;
66
+ margin-bottom: 0.5rem;
67
+ }
68
+ .stat-card p {
69
+ color: #666;
70
+ font-size: 1rem;
71
+ margin: 0;
72
+ }
73
+ .section-header {
74
+ color: #333;
75
+ font-size: 1.8rem;
76
+ font-weight: bold;
77
+ margin-top: 2rem;
78
+ margin-bottom: 1rem;
79
+ }
80
+ </style>
81
+ """, unsafe_allow_html=True)
82
 
83
  st.title("πŸƒβ€β™‚οΈ Strava Run Analysis")
84
 
85
+ # Strava manual authentication
86
+ if 'access_token' not in st.session_state:
87
+ st.write("To use this app, you need to authorize it with Strava. Follow these steps:")
88
+ st.write("1. Click the button below to go to Strava's authorization page:")
89
+ auth_url = f"https://www.strava.com/oauth/authorize?client_id={STRAVA_CLIENT_ID}&response_type=code&redirect_uri=http://localhost&approval_prompt=force&scope=read_all,profile:read_all,activity:read_all"
90
+ st.markdown(f"<a href='{auth_url}' target='_blank'><button style='background-color: #fc4c02; color: white; padding: 0.5rem 1rem; border: none; border-radius: 5px; cursor: pointer;'>Authorize Strava</button></a>", unsafe_allow_html=True)
91
+ st.write("2. Log in to Strava if needed and click 'Authorize'")
92
+ st.write("3. After authorizing, you'll be redirected to a page that may show an error. This is expected!")
93
+ st.write("4. Copy the 'code' parameter from the URL of that page.")
94
+ st.write("5. Paste that code below:")
95
+
96
+ auth_code = st.text_input("Paste the authorization code here:")
97
+ if auth_code:
98
+ try:
99
+ token_response = client.exchange_code_for_token(
100
+ client_id=STRAVA_CLIENT_ID,
101
+ client_secret=STRAVA_CLIENT_SECRET,
102
+ code=auth_code
103
+ )
104
+ st.session_state.access_token = token_response['access_token']
105
+ st.success("Authorization successful! Refreshing the app...")
106
+ st.rerun()
107
+ except Exception as e:
108
+ st.error(f"An error occurred: {str(e)}. Please try authorizing again.")
109
 
110
  if 'access_token' in st.session_state:
111
  client.access_token = st.session_state.access_token
 
126
  df = pd.DataFrame([{
127
  'name': run.name,
128
  'distance': float(run.distance) / 1000, # Convert to km
129
+ 'moving_time': run.moving_time.total_seconds() / 60 if run.moving_time else None, # Convert to minutes
130
+ 'total_elevation_gain': float(run.total_elevation_gain),
131
+ 'average_speed': float(run.average_speed) * 3.6, # Convert to km/h
132
  'average_heartrate': float(run.average_heartrate) if run.average_heartrate else None,
133
+ 'start_date': run.start_date.replace(tzinfo=None)
134
  } for run in runs])
135
+ df['pace'] = df['moving_time'] / df['distance'] # Calculate pace (min/km)
136
  return df
137
 
138
  try:
139
  df = fetch_run_activities()
 
 
 
140
  except Exception as e:
141
  st.error(f"Error fetching activities: {str(e)}. Please try again later.")
142
  st.stop()
 
151
  st.markdown("<div class='stat-card'><h3>{:.0f} km</h3><p>Total Distance</p></div>".format(df['distance'].sum()), unsafe_allow_html=True)
152
  with col3:
153
  total_time = df['moving_time'].sum()
154
+ st.markdown("<div class='stat-card'><h3>{:.0f}h {:.0f}m</h3><p>Total Time</p></div>".format(total_time // 60, total_time % 60), unsafe_allow_html=True)
 
 
 
155
  with col4:
156
  st.markdown("<div class='stat-card'><h3>{:.0f} m</h3><p>Total Elevation Gain</p></div>".format(df['total_elevation_gain'].sum()), unsafe_allow_html=True)
157
 
 
159
  st.markdown("<h2 class='section-header'>πŸ“ˆ Run Analysis</h2>", unsafe_allow_html=True)
160
 
161
  # Weekly distance
 
162
  weekly_distance = df.resample('W', on='start_date')['distance'].sum().reset_index()
163
  fig_weekly = px.bar(weekly_distance, x='start_date', y='distance',
164
  title="Weekly Running Distance",
 
167
  st.plotly_chart(fig_weekly, use_container_width=True)
168
 
169
  # Pace improvement
170
+ df_sorted = df.sort_values('start_date')
171
+ fig_pace = px.scatter(df_sorted, x='start_date', y='pace',
172
+ title="Running Pace Over Time",
173
+ labels={'pace': 'Pace (min/km)', 'start_date': 'Date'})
174
+ fig_pace.add_trace(go.Scatter(x=df_sorted['start_date'], y=df_sorted['pace'].rolling(window=10).mean(),
175
+ mode='lines', name='10-run moving average'))
176
+ fig_pace.update_layout(yaxis_title="Pace (min/km)")
177
+ st.plotly_chart(fig_pace, use_container_width=True)
 
 
 
178
 
179
  # Heart rate improvement (if data available)
180
  if df['average_heartrate'].notna().any():