Spaces:
Sleeping
Sleeping
Download app.py from KeyarSrini/strava-activity-analyzer: direct link, hf CLI and curl.
- Browser
- Download file 4.95 kB
-
https://huggingface.co/spaces/KeyarSrini/strava-activity-analyzer/resolve/main/app.py
- Command line
-
hf download hf://spaces/KeyarSrini/strava-activity-analyzer/app.py
-
curl -L -o app.py https://huggingface.co/spaces/KeyarSrini/strava-activity-analyzer/resolve/main/app.py
4.95 kB
| from fastapi import FastAPI, Query | |
| import requests | |
| import re | |
| import uvicorn | |
| import os | |
| # Initialize FastAPI app | |
| app = FastAPI() | |
| # β Strava API Credentials | |
| CLIENT_ID = "39765" | |
| CLIENT_SECRET = "88afc8eccac348c38659eadb099a712d083b0313" | |
| REDIRECT_URI = "https://KeyarSrini-strava-activity-analyzer.hf.space/callback" | |
| # β File to Store Refresh Token | |
| TOKEN_FILE = "strava_tokens.txt" | |
| # β Function to Load the Latest Refresh Token | |
| def load_refresh_token(): | |
| if os.path.exists(TOKEN_FILE): | |
| with open(TOKEN_FILE, "r") as f: | |
| return f.read().strip() | |
| return None | |
| # β Function to Save the Refresh Token | |
| def save_refresh_token(refresh_token): | |
| with open(TOKEN_FILE, "w") as f: | |
| f.write(refresh_token) | |
| # β Function to Refresh Access Token | |
| def refresh_access_token(): | |
| refresh_token = load_refresh_token() | |
| if not refresh_token: | |
| 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"} | |
| url = "https://www.strava.com/api/v3/oauth/token" | |
| payload = { | |
| "client_id": CLIENT_ID, | |
| "client_secret": CLIENT_SECRET, | |
| "refresh_token": refresh_token, | |
| "grant_type": "refresh_token", | |
| } | |
| response = requests.post(url, data=payload) | |
| if response.status_code != 200: | |
| return {"error": "Failed to refresh access token", "details": response.json()} | |
| token_data = response.json() | |
| save_refresh_token(token_data.get("refresh_token")) | |
| print(f"β New Access Token: {token_data.get('access_token')}") # Debugging | |
| return token_data.get("access_token") | |
| # β Function to Expand Strava Deep Link | |
| def expand_short_url(short_url): | |
| try: | |
| response = requests.head(short_url, allow_redirects=True) | |
| return response.url | |
| except requests.RequestException: | |
| return None # Return None if expansion fails | |
| # β Function to Extract Activity ID | |
| def extract_activity_id(deep_link): | |
| expanded_url = expand_short_url(deep_link) | |
| if not expanded_url: | |
| return None | |
| match = re.search(r"/activities/(\d+)", expanded_url) | |
| if match: | |
| return match.group(1) | |
| return None # Return None if extraction fails | |
| # β OAuth Callback - Handles the Code & Stores Refresh Token | |
| def handle_callback(code: str = Query(..., description="Authorization code from Strava")): | |
| url = "https://www.strava.com/api/v3/oauth/token" | |
| payload = { | |
| "client_id": CLIENT_ID, | |
| "client_secret": CLIENT_SECRET, | |
| "code": code, | |
| "grant_type": "authorization_code", | |
| "redirect_uri": REDIRECT_URI | |
| } | |
| response = requests.post(url, data=payload) | |
| if response.status_code != 200: | |
| return {"error": "Failed to exchange code for token", "details": response.json()} | |
| token_data = response.json() | |
| save_refresh_token(token_data.get("refresh_token")) | |
| return {"message": "Authorization successful! You can now fetch activities."} | |
| # β Main API - Automatically Handles Authorization & Fetches Activity | |
| def analyze_activity(activity_input: str = Query(..., description="Strava Deep Link")): | |
| access_token = refresh_access_token() | |
| if isinstance(access_token, dict): | |
| return access_token | |
| activity_id = extract_activity_id(activity_input) | |
| if not activity_id: | |
| return {"error": "Invalid input. Could not extract a valid Activity ID from Deep Link."} | |
| url = f"https://www.strava.com/api/v3/activities/{activity_id}" | |
| headers = {"Authorization": f"Bearer {access_token}"} | |
| response = requests.get(url, headers=headers) | |
| if response.status_code != 200: | |
| return { | |
| "error": "Failed to fetch activity data.", | |
| "status_code": response.status_code, | |
| "response_text": response.text | |
| } | |
| activity_data = response.json() | |
| summary = { | |
| "activity_name": activity_data.get("name", "Unknown"), | |
| "distance_km": round(activity_data.get("distance", 0) / 1000, 2), | |
| "average_speed_kmh": round(activity_data.get("average_speed", 0) * 3.6, 2), | |
| "max_speed_kmh": round(activity_data.get("max_speed", 0) * 3.6, 2), | |
| "average_heart_rate": activity_data.get("average_heartrate", "N/A"), | |
| "max_heart_rate": activity_data.get("max_heartrate", "N/A"), | |
| "elevation_gain_m": activity_data.get("total_elevation_gain", 0), | |
| "moving_time_min": round(activity_data.get("moving_time", 0) / 60, 2), | |
| "elapsed_time_min": round(activity_data.get("elapsed_time", 0) / 60, 2), | |
| "start_time": activity_data.get("start_date", "Unknown"), | |
| } | |
| return {"summary": summary, "message": "Activity analyzed successfully!"} | |
| # β Run FastAPI App in Hugging Face | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |