thanks gpt
This commit is contained in:
@@ -0,0 +1,25 @@
|
|||||||
|
import spotipy
|
||||||
|
from spotipy.oauth2 import SpotifyOAuth
|
||||||
|
|
||||||
|
# Set your Spotify API credentials
|
||||||
|
client_id = ''
|
||||||
|
client_secret = ''
|
||||||
|
redirect_uri = 'http://localhost:8888/callback' # Provide a valid redirect URI
|
||||||
|
|
||||||
|
# Create an authorization flow object
|
||||||
|
auth_manager = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
|
||||||
|
|
||||||
|
# Get the authorization URL
|
||||||
|
auth_url = auth_manager.get_authorize_url()
|
||||||
|
|
||||||
|
# Print the authorization URL and follow it in your browser
|
||||||
|
print(f"Please visit this URL to authorize the application: {auth_url}")
|
||||||
|
|
||||||
|
# Once authorized, you will be redirected to the specified redirect URI, and the authorization code will be appended to the URL.
|
||||||
|
# Extract the authorization code from the redirected URL and provide it to the auth_manager to obtain the access token.
|
||||||
|
authorization_code = input("Enter the authorization code: ")
|
||||||
|
auth_manager.get_access_token(authorization_code)
|
||||||
|
|
||||||
|
# Retrieve the access token
|
||||||
|
access_token = auth_manager.get_access_token()['access_token']
|
||||||
|
print(f"Access Token: {access_token}")
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
from pymongo import MongoClient
|
||||||
|
from collections import Counter
|
||||||
|
from datetime import datetime
|
||||||
|
import requests
|
||||||
|
|
||||||
|
client = MongoClient('MANGODBSRV')
|
||||||
|
db = client['cluster0']
|
||||||
|
collection = db['spotify']
|
||||||
|
|
||||||
|
# Retrieve all the song documents from the collection
|
||||||
|
songs = collection.find()
|
||||||
|
|
||||||
|
# Initialize counters for song counts per month
|
||||||
|
song_counts = {}
|
||||||
|
|
||||||
|
# Group songs by month and calculate statistics for each month
|
||||||
|
for song in songs:
|
||||||
|
song_name = song['song_name'] # Replace 'name' with the correct field name for song name
|
||||||
|
artist_name = song['artist'] # Replace 'artist' with the correct field name for artist name
|
||||||
|
song_id = song['song_id'] # Replace 'song_id' with the correct field name for the song ID
|
||||||
|
play_date = song['date'] # Replace 'date' with the correct field name for the date
|
||||||
|
|
||||||
|
# Parse the play date as a datetime object
|
||||||
|
play_date = datetime.strptime(play_date, "%B %d, %Y at %I:%M%p")
|
||||||
|
|
||||||
|
# Extract the month and year from the play date
|
||||||
|
month = play_date.strftime("%B %Y")
|
||||||
|
|
||||||
|
# Initialize the counter for the month if not already present
|
||||||
|
if month not in song_counts:
|
||||||
|
song_counts[month] = Counter()
|
||||||
|
|
||||||
|
# Increment the song count for the month
|
||||||
|
song_counts[month][(song_name, artist_name, song_id)] += 1
|
||||||
|
|
||||||
|
# Calculate the total plays for each month
|
||||||
|
total_plays = {month: sum(songs.values()) for month, songs in song_counts.items()}
|
||||||
|
|
||||||
|
# Spotify API endpoint for retrieving track information
|
||||||
|
endpointArtists = 'https://api.spotify.com/v1/artists'
|
||||||
|
endpointTracks = 'https://api.spotify.com/v1/tracks'
|
||||||
|
|
||||||
|
# Spotify API access token
|
||||||
|
access_token = 'ACCESSTOKENSPOTIFY' # Replace with your actual access token
|
||||||
|
|
||||||
|
# Function to retrieve the genre for a given song ID
|
||||||
|
def get_song_info(song_id):
|
||||||
|
headers = {'Authorization': f'Bearer {access_token}'}
|
||||||
|
url = f"{endpointTracks}/{song_id}"
|
||||||
|
response = requests.get(url, headers=headers)
|
||||||
|
data = response.json()
|
||||||
|
|
||||||
|
if 'artists' in data and data['artists']:
|
||||||
|
artist = data['artists'][0]
|
||||||
|
artist_id = artist['id']
|
||||||
|
|
||||||
|
if 'genres' in artist and artist['genres']:
|
||||||
|
genre = artist['genres'][0]
|
||||||
|
else:
|
||||||
|
genre = 'Unknown Genre'
|
||||||
|
else:
|
||||||
|
artist_id = 'Unknown Artist'
|
||||||
|
genre = 'Unknown Genre'
|
||||||
|
|
||||||
|
return genre, artist_id
|
||||||
|
|
||||||
|
# Function to retrieve the genre for a given song ID
|
||||||
|
def get_song_genre(artist_id):
|
||||||
|
headers = {'Authorization': f'Bearer {access_token}'}
|
||||||
|
url = f"{endpointArtists}/{artist_id}"
|
||||||
|
response = requests.get(url, headers=headers)
|
||||||
|
data = response.json()
|
||||||
|
if 'genres' in data and data['genres']:
|
||||||
|
genres = data['genres'][0]
|
||||||
|
return genres
|
||||||
|
return 'Unknown Genre'
|
||||||
|
|
||||||
|
# Print the statistics for each month
|
||||||
|
print("Song Statistics by Month:")
|
||||||
|
for month, songs in song_counts.items():
|
||||||
|
print(f"Month: {month}")
|
||||||
|
print(f"Total Plays: {total_plays[month]}")
|
||||||
|
|
||||||
|
most_played_song = songs.most_common(1)[0]
|
||||||
|
most_played_song_name = most_played_song[0][0]
|
||||||
|
most_played_song_artist = most_played_song[0][1]
|
||||||
|
most_played_song_id = most_played_song[0][2]
|
||||||
|
|
||||||
|
genre = get_song_genre(get_song_info(most_played_song_id)[1])
|
||||||
|
print(f"Most Played Song: {most_played_song_name} by {most_played_song_artist} ({most_played_song[1]} plays)")
|
||||||
|
print(f"Most Played Song Genre: {genre}")
|
||||||
|
|
||||||
|
print() # Add a new line for better readability
|
||||||
|
|
||||||
|
# Calculate the total plays of all time
|
||||||
|
total_plays_all_time = sum(total_plays.values())
|
||||||
|
|
||||||
|
# Print the total plays of all time
|
||||||
|
print(f"Total Plays of All Time: {total_plays_all_time}")
|
||||||
|
|
||||||
|
# Close the MongoDB connection
|
||||||
|
client.close()
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import os
|
||||||
|
import gspread
|
||||||
|
from google.auth.transport.requests import Request
|
||||||
|
from googleapiclient.discovery import build
|
||||||
|
from google.oauth2 import service_account
|
||||||
|
from pymongo import MongoClient
|
||||||
|
|
||||||
|
# Replace 'credentials.json' with the path to your downloaded credentials JSON file
|
||||||
|
credentials = service_account.Credentials.from_service_account_file('credentials.json', scopes=['https://www.googleapis.com/auth/drive'])
|
||||||
|
|
||||||
|
# Create a Drive API service client
|
||||||
|
drive_service = build('drive', 'v3', credentials=credentials)
|
||||||
|
|
||||||
|
def get_google_sheets_in_folder(folder_id):
|
||||||
|
results = drive_service.files().list(
|
||||||
|
q=f"'{folder_id}' in parents and mimeType='application/vnd.google-apps.spreadsheet'",
|
||||||
|
fields='files(id, name)'
|
||||||
|
).execute()
|
||||||
|
|
||||||
|
sheets = results.get('files', [])
|
||||||
|
|
||||||
|
return sheets
|
||||||
|
|
||||||
|
# Replace 'folder_id' with the actual ID of the folder you want to retrieve sheets from
|
||||||
|
folder_id = '1TaG1w1UemFNFzOENX34TjHu-4YWkGRGw'
|
||||||
|
|
||||||
|
# Call the function to get the Google Sheets in the folder
|
||||||
|
sheets = get_google_sheets_in_folder(folder_id)
|
||||||
|
|
||||||
|
# Check if the credentials are expired and refresh them if necessary
|
||||||
|
if credentials.expired and credentials.refresh_token:
|
||||||
|
credentials.refresh(Request())
|
||||||
|
|
||||||
|
# Create a gspread client using the refreshed credentials
|
||||||
|
gc = gspread.authorize(credentials)
|
||||||
|
|
||||||
|
# Connect to your MongoDB server
|
||||||
|
client = MongoClient('MONGODBSRV')
|
||||||
|
|
||||||
|
# Replace 'mydatabase' and 'mycollection' with your actual database and collection names
|
||||||
|
db = client['cluster0']
|
||||||
|
collection = db['spotify']
|
||||||
|
|
||||||
|
# Loop through the sheets
|
||||||
|
for sheet in sheets:
|
||||||
|
sheet_id = sheet['id']
|
||||||
|
|
||||||
|
# Open the Google Sheet by its ID
|
||||||
|
sheet = gc.open_by_key(sheet_id)
|
||||||
|
|
||||||
|
# Access a specific worksheet (e.g., the first sheet)
|
||||||
|
worksheet = sheet.get_worksheet(0)
|
||||||
|
|
||||||
|
# Extract the data from the worksheet
|
||||||
|
data = worksheet.get_all_values()
|
||||||
|
|
||||||
|
# Convert the data into a list of dictionaries
|
||||||
|
headers = data[0]
|
||||||
|
rows = data[1:]
|
||||||
|
rows_dict = []
|
||||||
|
|
||||||
|
# Map the data to the desired field names
|
||||||
|
field_names = ['date', 'song_name', 'artist', 'song_id', 'song_url']
|
||||||
|
for row in rows:
|
||||||
|
row_dict = {}
|
||||||
|
for i, field_name in enumerate(field_names):
|
||||||
|
row_dict[field_name] = row[i]
|
||||||
|
rows_dict.append(row_dict)
|
||||||
|
print("-----------------")
|
||||||
|
print(row_dict)
|
||||||
|
print("-----------------")
|
||||||
|
|
||||||
|
# Insert the data into MongoDB
|
||||||
|
collection.insert_many(rows_dict)
|
||||||
|
|
||||||
|
client.close()
|
||||||
Reference in New Issue
Block a user