Skip to content

Commit

Permalink
flask upgrades (#452)
Browse files Browse the repository at this point in the history
Add player and team data to flask ui
  • Loading branch information
nealmick authored Dec 21, 2024
1 parent bfafa9a commit 9313a6c
Show file tree
Hide file tree
Showing 5 changed files with 724 additions and 16 deletions.
192 changes: 187 additions & 5 deletions Flask/app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from datetime import date
import json
from flask import Flask, render_template
from flask import Flask, render_template,jsonify
from functools import lru_cache
import subprocess
import re
import time
import subprocess, requests, re, time


@lru_cache()
Expand Down Expand Up @@ -68,4 +66,188 @@ def index():
draftkings = fetch_draftkings(ttl_hash=get_ttl_hash())
betmgm = fetch_betmgm(ttl_hash=get_ttl_hash())

return render_template('index.html', today=date.today(), data={"fanduel": fanduel, "draftkings": draftkings, "betmgm": betmgm})
return render_template('index.html', today=date.today(), data={"fanduel": fanduel, "draftkings": draftkings, "betmgm": betmgm})




def get_player_data(team_abv):
"""Fetch player data for a given team abbreviation"""
url = "https://tank01-fantasy-stats.p.rapidapi.com/getNBATeamRoster"
headers = {
"x-rapidapi-key": "a0f0cd0b5cmshfef96ed37a9cda6p1f67bajsnfcdd16f37df8",
"x-rapidapi-host": "tank01-fantasy-stats.p.rapidapi.com"
}
querystring = {"teamAbv": team_abv}

try:
response = requests.get(url, headers=headers, params=querystring)
data = response.json()

if data.get('statusCode') == 200:
formatted_players = []
roster = data.get('body', {}).get('roster', [])

for player in roster:
# Format injury status
injury_status = "Healthy"
if player.get('injury'):
injury_info = player['injury']
if injury_info.get('designation'):
injury_status = injury_info['designation']
if injury_info.get('description'):
injury_status += f" - {injury_info['description']}"

formatted_player = {
'name': player.get('longName'),
'shortName': player.get('shortName'),
'headshot': player.get('nbaComHeadshot'),
'injury': injury_status,
'position': player.get('pos'),
'height': player.get('height'),
'weight': player.get('weight'),
'college': player.get('college'),
'experience': player.get('exp'),
'jerseyNum': player.get('jerseyNum'),
'playerId': player.get('playerID'),
'birthDate': player.get('bDay')
}
formatted_players.append(formatted_player)

return {
'success': True,
'players': formatted_players
}

return {
'success': False,
'error': 'Failed to fetch team data'
}

except Exception as e:
print(f"Error in get_player_data: {str(e)}")
return {
'success': False,
'error': str(e)
}


@app.route("/team-data/<team_name>")
def team_data(team_name):
# Convert full team name to abbreviation using the existing dictionary
team_abv = team_abbreviations.get(team_name)

if not team_abv:
return jsonify({
'success': False,
'error': f'Team abbreviation not found for {team_name}'
})

# Fetch and return the player data
result = get_player_data(team_abv)
return jsonify(result)



@app.route("/player-stats/<player_id>")
def player_stats(player_id):
headers = {
"x-rapidapi-key": "a0f0cd0b5cmshfef96ed37a9cda6p1f67bajsnfcdd16f37df8",
"x-rapidapi-host": "tank01-fantasy-stats.p.rapidapi.com"
}

# First get player info
info_url = "https://tank01-fantasy-stats.p.rapidapi.com/getNBAPlayerInfo"
info_querystring = {"playerID": player_id}

# Then get game stats
games_url = "https://tank01-fantasy-stats.p.rapidapi.com/getNBAGamesForPlayer"
games_querystring = {
"playerID": player_id,
"season": "2024",
}

try:
# Get both responses
info_response = requests.get(info_url, headers=headers, params=info_querystring)
games_response = requests.get(games_url, headers=headers, params=games_querystring)

info_data = info_response.json()
games_data = games_response.json()

if info_data.get('statusCode') == 200 and games_data.get('statusCode') == 200:
# Process games data
games = list(games_data['body'].values())
games.sort(key=lambda x: x['gameID'], reverse=True)
recent_games = games[:10]

# Get player info
player_info = info_data['body']

# Format injury info
injury_status = "Healthy"
if player_info.get('injury'):
injury_info = player_info['injury']
injury_status = injury_info

# Combine and return all data
return jsonify({
'success': True,
'games': recent_games,
'player': {
'name': player_info.get('longName'),
'position': player_info.get('pos'),
'number': player_info.get('jerseyNum'),
'height': player_info.get('height'),
'weight': player_info.get('weight'),
'team': player_info.get('team'),
'college': player_info.get('college'),
'experience': player_info.get('exp'),
'headshot': player_info.get('nbaComHeadshot'),
'injury': injury_status
}
})

return jsonify({
'success': False,
'error': 'Failed to fetch player data'
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
})


team_abbreviations = {
'Orlando Magic': 'ORL',
'Minnesota Timberwolves': 'MIN',
'Miami Heat': 'MIA',
'Boston Celtics': 'BOS',
'LA Clippers': 'LAC',
'Denver Nuggets': 'DEN',
'Detroit Pistons': 'DET',
'Atlanta Hawks': 'ATL',
'Cleveland Cavaliers': 'CLE',
'Toronto Raptors': 'TOR',
'Washington Wizards': 'WAS',
'Phoenix Suns': 'PHO',
'San Antonio Spurs': 'SA',
'Chicago Bulls': 'CHI',
'Charlotte Hornets': 'CHA',
'Philadelphia 76ers': 'PHI',
'New Orleans Pelicans': 'NO',
'Sacramento Kings': 'SAC',
'Dallas Mavericks': 'DAL',
'Houston Rockets': 'HOU',
'Brooklyn Nets': 'BKN',
'New York Knicks': 'NY',
'Utah Jazz': 'UTA',
'Oklahoma City Thunder': 'OKC',
'Portland Trail Blazers': 'POR',
'Indiana Pacers': 'IND',
'Milwaukee Bucks': 'MIL',
'Golden State Warriors': 'GS',
'Memphis Grizzlies': 'MEM',
'Los Angeles Lakers': 'LAL'
}
23 changes: 18 additions & 5 deletions Flask/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.tailwindcss.com"></script>
<!-- Add Bootstrap CSS and JS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

<title>NBA Machine Learning Picks</title>
<script>
tailwind.config = {
Expand All @@ -14,6 +18,7 @@
}
}
</script>

</head>
<body class="bg-gray-900">
<main class="relative isolate">
Expand All @@ -30,7 +35,7 @@ <h1 class="py-8 text-left text-4xl font-medium text-white">πŸ€ NBA AI Model Pic
<th class="py-2.5 text-left text-base font-semibold text-white">BetMGM</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-700">
<tbody class="divide-y divide-gray-700" style="z-index: 9;">
<tr>
{% for game_key in data.get('fanduel') %}
{% set teams = game_key.split(':') %}
Expand All @@ -44,10 +49,15 @@ <h1 class="py-8 text-left text-4xl font-medium text-white">πŸ€ NBA AI Model Pic
</thead>
<tbody>
<tr>
<td class="whitespace-nowrap py-1 pl-4 pr-3 text-base font-medium text-white sm:pl-0">{{ teams[0] }}</td>
<td class="whitespace-nowrap py-1 pl-4 pr-3 text-base font-medium text-white sm:pl-0">
<span class="team-name" data-bs-toggle="modal" data-bs-target="#modal-{{ teams[0]|replace(' ', '-')|lower }}">{{ teams[0] }}</span>
</td>
</tr>
<tr>
<td class="whitespace-nowrap py-1 pl-4 pr-3 text-base font-medium text-white sm:pl-0"><span class="text-gray-600">@</span> {{ teams[1] }}</td>
<td class="whitespace-nowrap py-1 pl-4 pr-3 text-base font-medium text-white sm:pl-0">
<span class="text-gray-600">@</span>
<span class="team-name" data-bs-toggle="modal" data-bs-target="#modal-{{ teams[1]|replace(' ', '-')|lower }}">{{ teams[1] }}</span>
</td>
</tr>
</tbody>
</table>
Expand Down Expand Up @@ -120,13 +130,14 @@ <h1 class="py-8 text-left text-4xl font-medium text-white">πŸ€ NBA AI Model Pic
</table>
</section>
</section>

<div class="absolute inset-x-0 -top-16 -z-10 flex transform-gpu justify-center overflow-hidden blur-3xl" aria-hidden="true">
<div class="aspect-[1318/752] w-[82.375rem] flex-none bg-gradient-to-r from-[#80caff] to-[#4f46e5] opacity-15" style="clip-path: polygon(73.6% 51.7%, 91.7% 11.8%, 100% 46.4%, 97.4% 82.2%, 92.5% 84.9%, 75.7% 64%, 55.3% 47.5%, 46.5% 49.4%, 45% 62.9%, 50.3% 87.2%, 21.3% 64.1%, 0.1% 100%, 5.4% 51.1%, 21.4% 63.9%, 58.9% 0.2%, 73.6% 51.7%)"></div>
</div>
<div class="absolute inset-x-0 -bottom-24 -z-10 flex transform-gpu justify-center overflow-hidden blur-3xl" aria-hidden="true">
<div class="aspect-[1318/752] w-[82.375rem] flex-none rotate-180 bg-gradient-to-r from-[#80caff] to-[#4f46e5] opacity-15" style="clip-path: polygon(73.6% 51.7%, 91.7% 11.8%, 100% 46.4%, 97.4% 82.2%, 92.5% 84.9%, 75.7% 64%, 55.3% 47.5%, 46.5% 49.4%, 45% 62.9%, 50.3% 87.2%, 21.3% 64.1%, 0.1% 100%, 5.4% 51.1%, 21.4% 63.9%, 58.9% 0.2%, 73.6% 51.7%)"></div>
</div>

</main>
<script>
function perc2color(perc, min, max) {
Expand Down Expand Up @@ -189,5 +200,7 @@ <h1 class="py-8 text-left text-4xl font-medium text-white">πŸ€ NBA AI Model Pic
ous[i].classList.add('text-' + perc2color(parsePerc(ous[i].textContent), 0, 100))
}
</script>
{% include 'team_modal.html' %}
{% include 'player_modal.html' %}
</body>
</html>
</html>
Loading

0 comments on commit 9313a6c

Please sign in to comment.