You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
165 lines
6.1 KiB
165 lines
6.1 KiB
import os
|
|
import sys
|
|
import base64
|
|
import requests
|
|
import urllib.parse
|
|
import pandas as pd
|
|
import qrcode
|
|
import logging
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
from dotenv import load_dotenv
|
|
from reportlab.pdfgen import canvas
|
|
|
|
env_path = "./.env"
|
|
|
|
# Laad de .env bestand expliciet
|
|
load_dotenv(env_path)
|
|
|
|
# Haal API-sleutels op
|
|
CLIENT_ID = os.getenv('SPOTIFY_CLIENT_ID')
|
|
CLIENT_SECRET = os.getenv('SPOTIFY_CLIENT_SECRET')
|
|
YOUTUBE_API_KEY = os.getenv('YOUTUBE_API_KEY')
|
|
|
|
# Configureren van logging
|
|
logging.basicConfig(filename="log.txt", level=logging.INFO,
|
|
format="%(asctime)s - %(message)s")
|
|
|
|
|
|
def log_message(message):
|
|
logging.info(f"{sys.argv[0]} - {message}")
|
|
|
|
|
|
def get_spotify_access_token():
|
|
auth_url = "https://accounts.spotify.com/api/token"
|
|
auth_data = {'grant_type': 'client_credentials'}
|
|
auth_headers = {
|
|
'Authorization': f"Basic {base64.b64encode(f'{CLIENT_ID}:{CLIENT_SECRET}'.encode('utf-8')).decode('utf-8')}"
|
|
}
|
|
response = requests.post(auth_url, data=auth_data, headers=auth_headers)
|
|
if response.status_code == 200:
|
|
log_message(f"Succesvol Spotify toegangstoken verkregen.")
|
|
return response.json().get('access_token')
|
|
else:
|
|
log_message(
|
|
f"Fout bij het verkrijgen van Spotify toegangstoken: {response.status_code}")
|
|
return None
|
|
|
|
|
|
def get_spotify_track_url(title, artist):
|
|
access_token = get_spotify_access_token()
|
|
if not access_token:
|
|
log_message(
|
|
f"Geen toegangstoken voor Spotify beschikbaar voor {title} - {artist}.")
|
|
return None
|
|
query = urllib.parse.quote_plus(f"{title} {artist}")
|
|
search_url = f"https://api.spotify.com/v1/search?q={query}&type=track&limit=1"
|
|
headers = {'Authorization': f"Bearer {access_token}"}
|
|
response = requests.get(search_url, headers=headers)
|
|
tracks = response.json().get('tracks', {}).get(
|
|
'items', []) if response.status_code == 200 else []
|
|
if tracks:
|
|
log_message(f"URL voor '{title} - {artist}' gevonden.")
|
|
return tracks[0]['external_urls']['spotify']
|
|
else:
|
|
log_message(f"Geen URL gevonden voor '{title} - {artist}' op Spotify.")
|
|
return None
|
|
|
|
|
|
def get_youtube_video_url(title, artist):
|
|
query = urllib.parse.quote_plus(f"{title} {artist}")
|
|
search_url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&q={query}&key={YOUTUBE_API_KEY}&maxResults=1&type=video"
|
|
response = requests.get(search_url)
|
|
items = response.json().get('items', []) if response.status_code == 200 else []
|
|
if items and 'videoId' in items[0]['id']:
|
|
log_message(f"URL voor '{title} - {artist}' gevonden op YouTube.")
|
|
return f"https://www.youtube.com/watch?v={items[0]['id']['videoId']}"
|
|
else:
|
|
log_message(f"Geen URL gevonden voor '{title} - {artist}' op YouTube.")
|
|
return None
|
|
|
|
|
|
def get_x_pos(text, c, font, fontsize):
|
|
text = "Dit is gecentreerde tekst"
|
|
text_width = c.stringWidth(text, font, fontsize) # Bereken tekstbreedte
|
|
page_width, _ = c._pagesize # Haal pagina-afmetingen op
|
|
|
|
x_position = (page_width - text_width) / 2 # Horizontaal centreren
|
|
|
|
return x_position
|
|
|
|
|
|
def generate_qr_codes_and_pdf(csv_file, output_pdf, position_col, title_col, artist_col, year_col, platform):
|
|
data = pd.read_csv(csv_file, delimiter=";")
|
|
c = canvas.Canvas(output_pdf)
|
|
|
|
for _, row in data.iterrows():
|
|
position, title, artist, year = row[position_col], row[title_col], row[artist_col], row[year_col]
|
|
url = get_spotify_track_url(
|
|
title, artist) if platform == "spotify" else get_youtube_video_url(title, artist)
|
|
|
|
if url:
|
|
qr = qrcode.QRCode(
|
|
version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4)
|
|
qr.add_data(url)
|
|
qr.make(fit=True)
|
|
qr_img = qr.make_image(
|
|
fill='black', back_color='white').convert("RGB")
|
|
|
|
qr_image_path = f"temp_qr.png"
|
|
qr_img.save(qr_image_path)
|
|
|
|
qr_width, qr_height = qr_img.size
|
|
page_width = qr_width + 100
|
|
page_height = qr_height + 200
|
|
|
|
c.setPageSize((page_width, page_height))
|
|
|
|
c.drawImage(qr_image_path, 0, page_height - qr_height,
|
|
width=qr_width, height=qr_height)
|
|
|
|
# c.drawImage(qr_image_path, x_center - (qr_width / 2),
|
|
# y_center, width=qr_width, height=qr_height)
|
|
c.showPage()
|
|
|
|
text_artist = f" {artist}"
|
|
text_title = f" {title}"
|
|
text_year = f" {year}"
|
|
# text_url = f"Link: {url}"
|
|
|
|
c.setFont("Helvetica", 12)
|
|
c.drawString(get_x_pos(text_artist, c, "Helvetica", 12), page_height -
|
|
qr_height - 20, text_artist)
|
|
c.setFont("Helvetica-Bold", 50)
|
|
c.drawString(140, page_height - qr_height - 80, text_year)
|
|
c.setFont("Courier", 11)
|
|
c.drawString(get_x_pos(text_title, c, "Courier", 11),
|
|
page_height - qr_height - 100, text_title)
|
|
# c.setFont("Helvetica", 12)
|
|
# c.drawString(50, page_height - qr_height - 100, text_url)
|
|
|
|
c.showPage()
|
|
os.remove(qr_image_path)
|
|
else:
|
|
log_message(f"Geen link gevonden voor '{title} - {artist}'.")
|
|
|
|
c.save()
|
|
log_message(f"PDF succesvol gegenereerd: {output_pdf}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 2 or sys.argv[1] not in ["spotify", "youtube"]:
|
|
log_message("Gebruik: python scriptnaam.py <mode>")
|
|
log_message("<mode> moet 'spotify' of 'youtube' zijn.")
|
|
print("Gebruik: python scriptnaam.py <mode>")
|
|
sys.exit(1)
|
|
|
|
platform = sys.argv[1]
|
|
csv_file = "nummers.csv"
|
|
output_pdf = "nummers_met_qr.pdf"
|
|
position_col, title_col, artist_col, year_col = "positie", "titel", "artiest", "jaar"
|
|
|
|
log_message(
|
|
f"Script gestart voor platform: {platform}. CSV bestand: {csv_file}, Output PDF: {output_pdf}")
|
|
generate_qr_codes_and_pdf(csv_file, output_pdf, position_col,
|
|
title_col, artist_col, year_col, platform)
|