KeyarSrini commited on
Commit
bcae692
Β·
verified Β·
1 Parent(s): 5804df7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -68
app.py CHANGED
@@ -3,7 +3,6 @@ import requests
3
  import re
4
  import uvicorn
5
  import os
6
- import datetime
7
 
8
  # Initialize FastAPI app
9
  app = FastAPI()
@@ -13,113 +12,98 @@ CLIENT_ID = "39765"
13
  CLIENT_SECRET = "88afc8eccac348c38659eadb099a712d083b0313"
14
  REDIRECT_URI = "https://KeyarSrini-strava-activity-analyzer.hf.space/callback"
15
 
16
- # βœ… Store the Latest Refresh Token in a File
17
  TOKEN_FILE = "strava_tokens.txt"
18
 
19
- # βœ… Load the Latest Refresh Token from File
20
  def load_refresh_token():
21
  if os.path.exists(TOKEN_FILE):
22
  with open(TOKEN_FILE, "r") as f:
23
  return f.read().strip()
24
  return None
25
 
26
- # βœ… Save the Refresh Token to File
27
  def save_refresh_token(refresh_token):
28
  with open(TOKEN_FILE, "w") as f:
29
  f.write(refresh_token)
30
 
31
- # βœ… Exchange Authorization Code for Access Token
32
- def exchange_code_for_token(auth_code):
 
 
 
 
 
 
33
  url = "https://www.strava.com/api/v3/oauth/token"
34
  payload = {
35
  "client_id": CLIENT_ID,
36
  "client_secret": CLIENT_SECRET,
37
- "code": auth_code,
38
- "grant_type": "authorization_code",
39
- "redirect_uri": REDIRECT_URI
40
  }
41
  response = requests.post(url, data=payload)
42
 
43
  if response.status_code != 200:
44
- return {"error": "Failed to exchange code for token", "details": response.json()}
45
 
46
  token_data = response.json()
47
-
48
- # Save the new refresh token
49
  save_refresh_token(token_data.get("refresh_token"))
50
 
51
- return token_data
52
 
53
- # βœ… Refresh Access Token
54
- def refresh_access_token():
55
- refresh_token = load_refresh_token()
56
- if not refresh_token:
57
- return {"error": "No refresh token found. Please authorize again."}
 
 
 
 
 
 
 
 
 
 
 
58
 
 
 
 
59
  url = "https://www.strava.com/api/v3/oauth/token"
60
  payload = {
61
  "client_id": CLIENT_ID,
62
  "client_secret": CLIENT_SECRET,
63
- "refresh_token": refresh_token,
64
- "grant_type": "refresh_token",
 
65
  }
66
  response = requests.post(url, data=payload)
67
 
68
  if response.status_code != 200:
69
- return {"error": "Failed to refresh access token", "details": response.json()}
70
 
71
  token_data = response.json()
72
-
73
- # Save the new refresh token
74
  save_refresh_token(token_data.get("refresh_token"))
 
 
75
 
76
- return token_data.get("access_token")
77
-
78
- # βœ… OAuth Authorization Endpoint (Redirects to Strava)
79
- @app.get("/authorize")
80
- def authorize_user():
81
- auth_url = (
82
- f"https://www.strava.com/oauth/authorize?client_id={CLIENT_ID}"
83
- f"&response_type=code&redirect_uri={REDIRECT_URI}"
84
- f"&approval_prompt=force&scope=read,activity:read,activity:read_all"
85
- )
86
- return {"message": "Click the link to authorize", "authorization_url": auth_url}
87
-
88
- # βœ… OAuth Callback (Handles the Code & Exchanges for Tokens)
89
- @app.get("/callback")
90
- def handle_callback(code: str = Query(..., description="Authorization code from Strava")):
91
- token_response = exchange_code_for_token(code)
92
- return token_response
93
-
94
- # βœ… Extract Activity ID from Deep Link, Direct Link, or ID
95
- def extract_activity_id(activity_input):
96
- # Case 1: If input is a raw activity ID (only numbers)
97
- if activity_input.isdigit():
98
- return activity_input
99
-
100
- # Case 2: If input is a deep link (e.g., strava.app.link/XYZ)
101
- if "strava.app.link" in activity_input:
102
- try:
103
- response = requests.head(activity_input, allow_redirects=True)
104
- activity_input = response.url # Expand the deep link
105
- except requests.RequestException:
106
- return None # Failed to expand deep link
107
-
108
- # Case 3: Extract Activity ID from direct Strava URL
109
- match = re.search(r"/activities/(\d+)", activity_input)
110
- return match.group(1) if match else None
111
-
112
- # βœ… Fetch Strava Activity Data & Analyze It
113
  @app.get("/analyze")
114
- def analyze_activity(activity_input: str = Query(..., description="Strava Activity URL, Deep Link, or ID")):
 
 
 
 
 
 
115
  activity_id = extract_activity_id(activity_input)
116
  if not activity_id:
117
- return {"error": "Invalid input. Could not extract a valid Activity ID."}
118
-
119
- access_token = refresh_access_token()
120
- if not access_token:
121
- return {"error": "Failed to fetch access token. Please authorize again."}
122
 
 
123
  url = f"https://www.strava.com/api/v3/activities/{activity_id}"
124
  headers = {"Authorization": f"Bearer {access_token}"}
125
  response = requests.get(url, headers=headers)
@@ -133,7 +117,7 @@ def analyze_activity(activity_input: str = Query(..., description="Strava Activi
133
 
134
  activity_data = response.json()
135
 
136
- # Extract Key Metrics
137
  summary = {
138
  "activity_name": activity_data.get("name", "Unknown"),
139
  "distance_km": round(activity_data.get("distance", 0) / 1000, 2),
@@ -147,7 +131,7 @@ def analyze_activity(activity_input: str = Query(..., description="Strava Activi
147
  "start_time": activity_data.get("start_date", "Unknown"),
148
  }
149
 
150
- # Pace Calculation (min/km)
151
  if summary["distance_km"] > 0:
152
  summary["average_pace_min_per_km"] = round(summary["moving_time_min"] / summary["distance_km"], 2)
153
  else:
 
3
  import re
4
  import uvicorn
5
  import os
 
6
 
7
  # Initialize FastAPI app
8
  app = FastAPI()
 
12
  CLIENT_SECRET = "88afc8eccac348c38659eadb099a712d083b0313"
13
  REDIRECT_URI = "https://KeyarSrini-strava-activity-analyzer.hf.space/callback"
14
 
15
+ # βœ… File to Store Refresh Token
16
  TOKEN_FILE = "strava_tokens.txt"
17
 
18
+ # βœ… Function to Load the Latest Refresh Token
19
  def load_refresh_token():
20
  if os.path.exists(TOKEN_FILE):
21
  with open(TOKEN_FILE, "r") as f:
22
  return f.read().strip()
23
  return None
24
 
25
+ # βœ… Function to Save the Refresh Token
26
  def save_refresh_token(refresh_token):
27
  with open(TOKEN_FILE, "w") as f:
28
  f.write(refresh_token)
29
 
30
+ # βœ… Function to Refresh Access Token
31
+ def refresh_access_token():
32
+ refresh_token = load_refresh_token()
33
+
34
+ if not refresh_token:
35
+ # πŸš€ Automatically trigger OAuth authorization
36
+ return {"authorize_url": f"https://www.strava.com/oauth/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&approval_prompt=force&scope=read,activity:read,activity:read_all"}
37
+
38
  url = "https://www.strava.com/api/v3/oauth/token"
39
  payload = {
40
  "client_id": CLIENT_ID,
41
  "client_secret": CLIENT_SECRET,
42
+ "refresh_token": refresh_token,
43
+ "grant_type": "refresh_token",
 
44
  }
45
  response = requests.post(url, data=payload)
46
 
47
  if response.status_code != 200:
48
+ return {"error": "Failed to refresh access token", "details": response.json()}
49
 
50
  token_data = response.json()
 
 
51
  save_refresh_token(token_data.get("refresh_token"))
52
 
53
+ return token_data.get("access_token")
54
 
55
+ # βœ… Function to Expand Strava Deep Link
56
+ def expand_short_url(short_url):
57
+ try:
58
+ response = requests.head(short_url, allow_redirects=True)
59
+ return response.url
60
+ except requests.RequestException:
61
+ return None # Return None if expansion fails
62
+
63
+ # βœ… Function to Extract Activity ID
64
+ def extract_activity_id(deep_link):
65
+ expanded_url = expand_short_url(deep_link)
66
+ if not expanded_url:
67
+ return None
68
+
69
+ match = re.search(r"/activities/(\d+)", expanded_url)
70
+ return match.group(1) if match else None
71
 
72
+ # βœ… OAuth Callback - Handles the Code & Stores Refresh Token
73
+ @app.get("/callback")
74
+ def handle_callback(code: str = Query(..., description="Authorization code from Strava")):
75
  url = "https://www.strava.com/api/v3/oauth/token"
76
  payload = {
77
  "client_id": CLIENT_ID,
78
  "client_secret": CLIENT_SECRET,
79
+ "code": code,
80
+ "grant_type": "authorization_code",
81
+ "redirect_uri": REDIRECT_URI
82
  }
83
  response = requests.post(url, data=payload)
84
 
85
  if response.status_code != 200:
86
+ return {"error": "Failed to exchange code for token", "details": response.json()}
87
 
88
  token_data = response.json()
 
 
89
  save_refresh_token(token_data.get("refresh_token"))
90
+
91
+ return {"message": "Authorization successful! You can now fetch activities."}
92
 
93
+ # βœ… Main API - Automatically Handles Authorization & Fetches Activity
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  @app.get("/analyze")
95
+ def analyze_activity(activity_input: str = Query(..., description="Strava Deep Link")):
96
+ # πŸš€ Step 1: Check Authorization & Refresh Token
97
+ access_token = refresh_access_token()
98
+ if isinstance(access_token, dict): # If returned a URL, redirect user
99
+ return access_token
100
+
101
+ # πŸš€ Step 2: Extract Activity ID
102
  activity_id = extract_activity_id(activity_input)
103
  if not activity_id:
104
+ return {"error": "Invalid input. Could not extract a valid Activity ID from Deep Link."}
 
 
 
 
105
 
106
+ # πŸš€ Step 3: Fetch Activity Data
107
  url = f"https://www.strava.com/api/v3/activities/{activity_id}"
108
  headers = {"Authorization": f"Bearer {access_token}"}
109
  response = requests.get(url, headers=headers)
 
117
 
118
  activity_data = response.json()
119
 
120
+ # πŸš€ Step 4: Extract & Analyze Data
121
  summary = {
122
  "activity_name": activity_data.get("name", "Unknown"),
123
  "distance_km": round(activity_data.get("distance", 0) / 1000, 2),
 
131
  "start_time": activity_data.get("start_date", "Unknown"),
132
  }
133
 
134
+ # πŸš€ Step 5: Calculate Pace
135
  if summary["distance_km"] > 0:
136
  summary["average_pace_min_per_km"] = round(summary["moving_time_min"] / summary["distance_km"], 2)
137
  else: