File size: 2,373 Bytes
3636d4e
 
2f4074b
8015b2a
cab8f0d
584c24c
3636d4e
 
5b99258
8015b2a
a5c2bee
584c24c
 
 
 
a5c2bee
 
 
3636d4e
25201ed
c8ea80c
3636d4e
c8ea80c
 
3636d4e
c8ea80c
3636d4e
25201ed
3636d4e
 
 
584c24c
3636d4e
 
 
 
 
 
25201ed
c8ea80c
3636d4e
 
2f4074b
 
 
 
 
 
 
 
 
 
4c64cef
c8ea80c
5b99258
cab8f0d
584c24c
25201ed
5b99258
2f4074b
 
4c64cef
2f4074b
4c64cef
 
8015b2a
 
4c64cef
2f4074b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Shazam Playlist to Youtube Playlist"""

from pathlib import Path
import random
from typing import Optional
import logging
import pandas as pd
from pytube import Search, YouTube
from flask import Flask, request, send_from_directory
from sklearn.utils import shuffle as sklearn_shuffle

# https://github.com/pytube/pytube/issues/1270#issuecomment-2100372834
pytube_logger = logging.getLogger('pytube')
pytube_logger.setLevel(logging.ERROR)

app = Flask(__name__)

@app.route('/')
def index():
    """Route handler for the home page"""
    try:
        return send_from_directory('.', 'index.html')
    except Exception as e:
        return str(e)
    
@app.route('/video_id', methods=['POST'])
def video_id() -> str:
    """Route handler for retrieving the YouTube video ID"""
    try:
        title: str = request.json.get('title')
        artist: str = request.json.get('artist')
        youtube: YouTube = get_youtube_song(title, artist)
        return youtube.video_id
    except Exception as e:
        return str(e)

@app.route('/parse_csv', methods=['POST'])
def parse_csv():
    """Route handler for parsing the uploaded CSV file"""
    try:
        file = request.files['file']
        # Process the uploaded file
        return parse_csv_util(pd.read_csv(file, header=1))
    except Exception as e:
        return str(e)

@app.route('/parse_csv_test', methods=['GET'])
def parse_csv_test():
    """Route handler for parsing the test CSV file"""
    try:
        # Construct the path to the CSV file
        csv_path = Path(__file__).parent / 'shazamlibrary.test.csv'
        return parse_csv_util(pd.read_csv(csv_path, header=1), True)
    except Exception as e:
        return str(e)

def get_youtube_song(title: str, artist: str) -> Optional[YouTube]:
    """Searches for a YouTube video based on the given title and artist"""
    search_result = Search(f'{title} by {artist}')
    return search_result.results[0] if search_result.results else None

def parse_csv_util(df: pd.DataFrame, shuffle = False):
    try:
        df = df.drop_duplicates(subset=['TrackKey'])[['Title', 'Artist']]
        if shuffle:
            for random_state in random.sample(range(444, 44444), 3):
                df = sklearn_shuffle(df, random_state=random_state).reset_index(drop=True)
        return df.to_json(orient="records")
    except Exception as e:
        return str(e)