├── .DS_Store ├── dadabots_old ├── art │ └── ._.o_o ├── mp3 │ └── ._.o_o ├── intn │ └── ._.o_o ├── DadaBot.py ├── ttapi │ └── ttbot.py ├── README.md ├── remix-scripts │ ├── repeatbeats.py │ ├── becawwrdsaekva.py │ ├── dadarays.py │ └── qup.py ├── artremixer.py ├── gnabber.py ├── kcluster.py ├── bot_becawwrdsaekva.py ├── chopshopshockshack.py ├── violin_split.py ├── kcluster_afromb_sections.py └── alltheclusters.py ├── .gitignore ├── README.md ├── kcluster_afromb.py ├── LICENSE.md └── Dadabot_Autochiptune.ipynb /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortexelus/dadabots/HEAD/.DS_Store -------------------------------------------------------------------------------- /dadabots_old/art/._.o_o: -------------------------------------------------------------------------------- 1 | # place holder file 2 | write some weird shit in here # -------------------------------------------------------------------------------- /dadabots_old/mp3/._.o_o: -------------------------------------------------------------------------------- 1 | # place holder file 2 | write some weird shit in here # -------------------------------------------------------------------------------- /dadabots_old/intn/._.o_o: -------------------------------------------------------------------------------- 1 | # place holder file 2 | write some weird shit in here # -------------------------------------------------------------------------------- /dadabots_old/DadaBot.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortexelus/dadabots/HEAD/dadabots_old/DadaBot.py -------------------------------------------------------------------------------- /dadabots_old/ttapi/ttbot.py: -------------------------------------------------------------------------------- 1 | from ttapi import Bot 2 | 3 | AUTH = 'HDuKXnXcExdxcpjGuVVOuSEJ' 4 | USERID = '511479b5eb35c11c9a3b65e1' 5 | ROOMID = '5114792feb35c11c9a3b65e0' 6 | 7 | 8 | bot = Bot(AUTH, USERID, ROOMID) 9 | 10 | def speak(data): 11 | name = data['name'] 12 | text = data['text'] 13 | if text == '/hello': 14 | bot.speak('Hey! How are you %s ?' % name) 15 | 16 | bot.on('speak', speak) 17 | 18 | bot.start() -------------------------------------------------------------------------------- /dadabots_old/README.md: -------------------------------------------------------------------------------- 1 | dadabots 2 | ======== 3 | 4 | Socially-autonomous dadaist music-remixing bots. EchoNest makes love to Soundcloud 5 | 6 | 7 | 8 | How do I do that 9 | ================ 10 | 11 | 0) clone it 12 | 1) install python 13 | 2) install echonest, remix, scipy, soundtouch, dirac 14 | 3) get an echonest API key 15 | 4) python bot_becawwrdsaevka.py 16 | or 17 | 5) python bot_becawwrdsaevka.py http://soundcloud.com/chopshopshockshack/electrocado-seizure-salad-vs remix post 18 | 19 | Look at how bot_becawwrdsaevkva.py works and make your own. 20 | Put your EchoNest remixing script in remix-scripts, you can also try examples the remix API comes with 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | 29 | # Translations 30 | *.mo 31 | 32 | # Mr Developer 33 | .mr.developer.cfg 34 | .project 35 | .pydevproject 36 | 37 | # Stuff related to this project 38 | 39 | # content 40 | *.mp3 41 | *.jpg 42 | *.bat 43 | *.intention 44 | Thumbs.db 45 | *.wav 46 | 47 | # other stuff 48 | *.asd 49 | *.mp3* 50 | 51 | # directories 52 | swamp 53 | html 54 | 55 | # 56 | *metascript* 57 | *^*.py -------------------------------------------------------------------------------- /dadabots_old/remix-scripts/repeatbeats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf=8 3 | """ 4 | one.py 5 | 6 | Digest only the first beat of every bar. 7 | 8 | By Ben Lacker, 2009-02-18. 9 | """ 10 | import echonest.audio as audio 11 | from echonest.selection import have_pitch_max,have_pitches_max 12 | import pyechonest.config as config 13 | config.MP3_BITRATE = 192 14 | 15 | 16 | usage = """ 17 | Usage: 18 | python one.py 19 | 20 | Example: 21 | python one.py EverythingIsOnTheOne.mp3 EverythingIsReallyOnTheOne.mp3 22 | """ 23 | 24 | def main(input_filename, output_filename): 25 | audiofile = audio.LocalAudioFile(input_filename) 26 | bars = audiofile.analysis.bars 27 | collect = audio.AudioQuantumList() 28 | for bar in bars: 29 | collect.append(bar) 30 | collect.append(bar) 31 | out = audio.getpieces(audiofile, collect) 32 | out.encode(output_filename) 33 | 34 | if __name__ == '__main__': 35 | import sys 36 | try: 37 | input_filename = sys.argv[1] 38 | output_filename = sys.argv[2] 39 | except: 40 | print usage 41 | sys.exit(-1) 42 | main(input_filename, output_filename) 43 | -------------------------------------------------------------------------------- /dadabots_old/artremixer.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import PIL.ImageOps 3 | import PIL.ImageFilter as ImageFilter 4 | import ImageChops 5 | 6 | # takes art, finds edges, creates horz and vert symmetry 7 | def art_florp(bot,track_art): 8 | image = Image.open(track_art) 9 | image = image.filter(ImageFilter.FIND_EDGES) 10 | image = Image.blend(Image.blend(image, image.rotate(90), 0.5), Image.blend(image.rotate(180), image.rotate(270), 0.5), 0.5) 11 | new_track_art = track_art[:-3] + "rmx.florp." + track_art[-3:] 12 | image.save(new_track_art) 13 | return new_track_art 14 | 15 | # simple horz flip, kinda dumb 16 | def horzflip(bot,art): 17 | image = Image.open(art) 18 | image = Image.blend(image, image.rotate(180), 0.5) 19 | new_art = art[:-3] + "rmx.horzflip." + art[-3:] 20 | image.save(new_art) 21 | return new_art 22 | 23 | #octogon flip 24 | def octoflip(bot,art): 25 | image = Image.open(art) 26 | image = Image.blend(Image.blend(image, image.rotate(90), 0.5), Image.blend(image.rotate(180), image.rotate(270), 0.5), 0.5) 27 | image = Image.blend(image, image.rotate(45), 0.5) 28 | image = image.filter(ImageFilter.SHARPEN) 29 | image = image.filter(ImageFilter.SHARPEN) 30 | new_art = art[:-3] + "rmx.octo." + art[-3:] 31 | image.save(new_art) 32 | return new_art -------------------------------------------------------------------------------- /dadabots_old/gnabber.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf=8 3 | """ 4 | offliberty gnabber 5 | downloads tracks from soundcloud, always 128k mp3 6 | 7 | cortexel.us 2012 8 | """ 9 | import urllib2, urllib, re 10 | 11 | usage = "Offliberty Gnabber. Downloads tracks from soundcloud, youtube, etc.\n\ 12 | Usage: offliberty.py url\ 13 | Example: offliberty.py http://soundcloud.com/chopshopshockshack/mt-analogue-you-know-what-time" 14 | 15 | def geturl(sc_url): 16 | off_url = "http://offliberty.com/off.php" 17 | req = urllib2.Request(off_url) 18 | #res = urllib2.urlopen(req) 19 | 20 | data = { 'track' : sc_url, 'refext' : ""} 21 | req.add_data(urllib.urlencode(data)) 22 | res = urllib2.urlopen(req) 23 | 24 | offpage = res.read(600) 25 | 26 | url_list = re.findall('(?:http://|www.)[^"\' ]+', offpage) 27 | print url_list[0] 28 | return url_list[0] 29 | 30 | def download(url, file_name): 31 | 32 | u = urllib2.urlopen(url) 33 | f = open(file_name, 'wb') 34 | meta = u.info() 35 | file_size = int(meta.getheaders("Content-Length")[0]) 36 | print "Downloading: %s \nBytes: %s" % (file_name, file_size) 37 | 38 | #if(file_size >= self.MAX_FILE_SIZE): 39 | # raise Exception("File size too big!! %i > %i " % [file_size, self.MAX_FILE_SIZE]) 40 | 41 | file_size_dl = 0 42 | block_sz = 8192 43 | while True: 44 | buffer = u.read(block_sz) 45 | if not buffer: 46 | break 47 | 48 | file_size_dl += len(buffer) 49 | f.write(buffer) 50 | status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) 51 | status = status + chr(8)*(len(status)+1) 52 | print status, 53 | 54 | print "\n" 55 | f.close() 56 | 57 | def gnabsong(url, filename): 58 | download(geturl(url), filename) 59 | 60 | if __name__ == '__main__': 61 | import sys 62 | try: 63 | url = sys.argv[1] 64 | filename = sys.argv[2] 65 | except: 66 | print usage 67 | sys.exit(-1) 68 | gnabsong(url, filename) 69 | 70 | -------------------------------------------------------------------------------- /dadabots_old/kcluster.py: -------------------------------------------------------------------------------- 1 | from pylab import plot,show 2 | from numpy import vstack,array 3 | from numpy.random import rand 4 | from scipy.cluster.vq import kmeans,vq 5 | 6 | import echonest.audio as audio 7 | from echonest.sorting import * 8 | from echonest.selection import * 9 | import pyechonest.config as config 10 | config.MP3_BITRATE = 192 11 | 12 | 13 | #def main(inputFilename, outputFilename): 14 | inputFilename="mp3/softhotlong.mp3" 15 | song = audio.LocalAudioFile(inputFilename) 16 | 17 | sample_rate = song.sampleRate 18 | 19 | num_channels = song.numChannels 20 | out_shape = list(song.data.shape) 21 | out_shape[0] = 2 22 | 23 | # how many different groups will we cluster our data into? 24 | num_clusters = 50 25 | 26 | outs = [None]*num_clusters 27 | for n in range(0,num_clusters): 28 | outs[n] = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 29 | 30 | # this is just too easy 31 | # song.analysis.segments.timbre is a list of all 12-valued timbre vectors. 32 | # must be converted to a numpy.array() so that kmeans(data, n) is happy 33 | data = array(song.analysis.segments.timbre) 34 | 35 | # data generation 36 | # rand creates a random 150x2 matrix..or a multidimensional array of 150 (two floated) arrays 37 | # vstack concatenates matrices together 38 | # data = vstack((rand(150,2),rand(150,2))) 39 | 40 | # computing K-Means with K = 2 (2 clusters) 41 | centroids,_ = kmeans(data,num_clusters) 42 | # assign each sample to a cluster 43 | idx,_ = vq(data,centroids) 44 | #idx lists the cluster that each data point belongs to [2, 0, 0, 1, 2] 45 | 46 | #this code makes segclusters, which is a list of each cluster of segments. 47 | segclusters = [[]]*num_clusters 48 | for s in range(0, len(idx)): 49 | segment = song.analysis.segments[s] 50 | cluster_number = idx[s] 51 | outs[cluster_number].append(song[segment]) 52 | 53 | 54 | inc = 0 55 | rand = random( 56 | for out in outs: 57 | out.encode("clusters/cluster"+str(inc)+".mp3") 58 | inc += 1 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /dadabots_old/remix-scripts/becawwrdsaekva.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf=8 3 | 4 | """ 5 | becawwrdsaekva.py 6 | 7 | Every section weaves through itself backwards. 8 | 9 | Cortexelus James Carr 10 | Music Hack day 11/11/2012 11 | """ 12 | 13 | import echonest.audio as audio 14 | from echonest.sorting import * 15 | from echonest.selection import * 16 | import echonest.action as action 17 | import pyechonest.config as config 18 | config.MP3_BITRATE = 128 19 | import math 20 | 21 | usage = """ 22 | Usage: 23 | python becawwrdsaekva.py 24 | 25 | Example: 26 | python becawwrdsaekva.py hypersisyphus.mp3 hupprsisyehys.mp3 27 | """ 28 | 29 | def main(inputFilename, outputFilename, windowing): 30 | print "HERE WE GO!!!!" 31 | print inputFilename 32 | print "\n" 33 | print outputFilename 34 | print "\n" 35 | song = audio.LocalAudioFile(inputFilename) 36 | 37 | print "Cool, we loaded the song" 38 | 39 | sample_rate = song.sampleRate 40 | num_channels = song.numChannels 41 | out_shape = list(song.data.shape) 42 | out_shape[0] = 2 43 | out = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 44 | 45 | chunks = [] 46 | for section in song.analysis.sections: 47 | segs = song.analysis.segments.that(are_contained_by(section)) 48 | 49 | seglen = len(segs) 50 | print seglen 51 | for i in range(0, seglen): 52 | if i%2 : 53 | seg = song[segs[i]] 54 | if windowing: 55 | seg.data = window(seg.data) 56 | out.append(seg) 57 | else: 58 | seg = song[ segs[seglen - i - 1 ]] 59 | try: 60 | seg.data = seg.data[::-1] 61 | if windowing: 62 | seg.data = window(seg.data) 63 | out.append(seg) 64 | del(seg.data) 65 | del(seg) 66 | except: 67 | print "fuckkkkk" 68 | seg = song[segs[i]] 69 | if windowing: 70 | seg.data = window(seg.data) 71 | out.append(seg) 72 | 73 | 74 | 75 | 76 | #newAudio = audio.getpieces(song, chunks) 77 | out.encode(outputFilename) 78 | #newAudio.enc 79 | def window(data): 80 | w = 8000 # window size; number of samples to taper off 81 | s = len(data) # total number of samples in segment 82 | if(s<2*w): 83 | w = math.floor(s/2)-1 84 | 85 | for n in range(0, w): 86 | #r = pow(2, i/w)-1 # ratio by which to taper 87 | #r = 0.5 * (1 - math.cos((2*3.14*n)/( w-1))) 88 | r = (pow(10, n/w)-1)/9 89 | data[n] *= r # beginning sample 90 | data[s-n-1] *= r # end sample 91 | 92 | return data 93 | 94 | 95 | 96 | if __name__ == '__main__': 97 | import sys 98 | try : 99 | inputFilename = sys.argv[1] 100 | outputFilename = sys.argv[2] 101 | window = bool(int(sys.argv[3])) 102 | except : 103 | print usage 104 | sys.exit(-1) 105 | 106 | main(inputFilename, outputFilename, window) 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dadabots 2 | 3 | Soundcloud bots that 4 | * spider soundcloud for tracks 5 | * remix the music, title, and artwork 6 | * post the remixes 7 | * comment on tracks 8 | * Free account: repeat until account limit is reached 9 | * Soundcloud Pro: repeat forever, or until temporary bans for too much activity (Avoid more than 50 songs a day) 10 | 11 | # See them in action! 12 | 13 | Active 14 | * https://soundcloud.com/autochiptune 15 | 16 | Inactive 17 | * https://soundcloud.com/phasedandconfused 18 | * https://soundcloud.com/chopshopshockshack 19 | * https://soundcloud.com/bonafide-slideglide-ride 20 | * https://soundcloud.com/becawwrdsaekva 21 | 22 | ## Presentations 23 | 24 | * [DadaBots: Socially Automated Dadaist Music Remix Bots](https://vimeo.com/72277348) 25 | * [Northeastern ACM Speaker Series: Dadabots & Computational Creativity](https://www.facebook.com/events/165144357029161/?ref=5) 26 | * [REMIX.ARMY](https://youtu.be/ue_KHvQZH8M) 27 | 28 | ## In the media 29 | 30 | * [Algopop](http://algopop.tumblr.com/post/67950573648/dadabots-socially-automated-dadaist-music-remix) 31 | * [Highway Magazine](http://www.highwaymagazine.info/2015/12/dadabots-music-algorithms/) 32 | * [When Algorithms Create Our Culture](http://www.worldcrunch.com/tech-science/when-algorithms-create-our-culture/c4s19935/) 33 | 34 | 35 | ## dadabots_old/ 36 | 37 | This directory contains older bots temporarily banished to purgatory. They need to be updated to function with the latest Soundcloud API. 38 | 39 | ## How to run AUTOCHIPTUNE bot 40 | 41 | ``` 42 | git clone https://github.com/Cortexelus/dadabots 43 | pip install soundcloud 44 | ``` 45 | 46 | Install Librosa either `pip install librosa` or from [source](https://github.com/bmcfee/librosa/) 47 | 48 | Install [jupyter notebook](http://jupyter.org/) 49 | 50 | Run ```jupyter notebook``` 51 | 52 | Register for the [Soundcloud API](https://developers.soundcloud.com/) and get a secret key. 53 | 54 | Register a [new account](https://soundcloud.com/signup) on soundcloud for your bot. 55 | 56 | Open *Dadabot_Autochiptune.ipynb* in jupyter notebook. 57 | 58 | Search for `client_id` and `client_secret` and update them with your soundcloud API credentials. 59 | 60 | Search for `bot.username` and `bot.password` to your new soundcloud account credentials. 61 | 62 | Execute all the code. 63 | 64 | Needs at least one follower in order to start spidering. 65 | 66 | As long as jupyter notebook server is running, the bot will continue to make new tracks. 67 | 68 | If you register for Soundcloud Pro the bot will post new tracks FOREVER 69 | 70 | 71 | ## Making a new bot 72 | 73 | Copy *Dadabot_Autochiptune.ipynb* and edit it. 74 | 75 | 76 | ## Example output 77 | ``` 78 | awake. 79 | Autochiptune remix. 80 | hi 81 | Initializing soundcloud.Client . . . 82 | Searching Check Me Out!'s tracks . . . 83 | Searching j.j.g.89's tracks . . . 84 | Searching B Floss's tracks . . . 85 | Hmm.. Floss Love Me Or Hate Me (ISDGAF) 86 | url http://soundcloud.com/b-floss-2/floss-love-me-or-hate-me 87 | http://soundcloud.com/b-floss-2/floss-love-me-or-hate-me 88 | gnab download.. 89 | opening url http://cf-media.sndcdn.com/ZTcmznvxt383.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20vWlRjbXpudnh0MzgzLjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0NTI5MTAyMDl9fX1dfQ__&Signature=ilU4KDuu7YCpGlCS7MOp4gC8yF0N9yEeDSO5PmiB-DihRQavkky3TwF48jt9u-zNm2vHpQJNp9fkg6NB6M5IvdFgT9XmeEmvimjhiCf-Jttf92CnqrE5ajPELIoFX39MvwJ4ZM6iDUl2Pmjhw87Cd7u4OdhNbYVnTgzFZNVpF8xFguzh0M2Knbn1JxGiTjCqLZC1jgPUiRwiwed~-lezXd94tgtXSQQBEgAvLT7Ue8ZwswPUFvG5Vk-r1uTHR6MnI4dMFLISXCJSKdj2lnTd-9x-hvL2vDuDgU8VwLeTOpgsFl2XywBcLoo6EPgYUmSyOsWblutbk6JAPtvAp~PRXA__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ 90 | 91 | 92 | bot.track.artwork_url https://i1.sndcdn.com/artworks-000139724823-vc8lch-large.jpg 93 | artwork_url http://i1.sndcdn.com/artworks-000139724823-vc8lch-large.jpg 94 | gnab download.. 95 | opening url http://i1.sndcdn.com/artworks-000139724823-vc8lch-large.jpg 96 | 97 | 98 | avatar_url http://i1.sndcdn.com/avatars-000157974264-o74oqd-large.jpg 99 | gnab download.. 100 | opening url http://i1.sndcdn.com/avatars-000157974264-o74oqd-large.jpg 101 | 102 | 103 | 104 | 105 | MP3: ./dadabots/mp3/b-floss-2_floss-love-me-or-hate-me.mp3 106 | TRACK_ART: ./dadabots/art/b-floss-2_floss-love-me-or-hate-me.jpg 107 | USER_ART: ./dadabots/art/b-floss-2.avatar.jpg 108 | 109 | 110 | Updating avatar..../dadabots/art/b-floss-2.avatar.rmx.autochip.jpg 111 | Remixing track art ./dadabots/art/b-floss-2_floss-love-me-or-hate-me.jpg 112 | Calling autochip(./dadabots/mp3/b-floss-2_floss-love-me-or-hate-me.mp3, ./dadabots/mp3/b-floss-2_floss-love-me-or-hate-me.rmx.autochiptune.mp3) 113 | Processing b-floss-2_floss-love-me-or-hate-me.mp3 114 | Synthesizing squares... 115 | Synthesizing triangles... 116 | Synthesizing drums... 117 | Mixing... 118 | Done. 119 | Remix title: B Floss: Floss Love Me Or Hate Me (ISDGAF) [autochip rmx] 120 | Uploading remix . . . 121 | Remix track art ./dadabots/art/b-floss-2_floss-love-me-or-hate-me.rmx.autochip.jpg 122 | http://soundcloud.com/autochiptune/b-floss-floss-love-me-or-hate 123 | Liking track . . . 124 | Commenting . . . autochiptune_remix: http://soundcloud.com/autochiptune/b-floss-floss-love-me-or-hate 125 | 126 | Commenting . . . Original: http://soundcloud.com/b-floss-2/floss-love-me-or-hate-me 127 | 128 | bye 129 | sleeping.. 130 | ``` 131 | 132 | ## todo 133 | 134 | * Dadabots became a monolithic notebook of code. Separate it back into its reusable pieces, so new bots are easier to make, and old bots are easier to update (whenever soundcloud API changes). 135 | 136 | * Store activity in database. 137 | 138 | * One follower got annoyed because the bot remixed 5 of his tracks (randomly). Instead remix one track per user until all users have been remixed. 139 | 140 | * Remix tracks which users send bot in a private message. 141 | 142 | * Unfollow users which do not follow back after n days. 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /dadabots_old/bot_becawwrdsaekva.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import DadaBot 4 | from DadaBot import DadaBot 5 | import artremixer 6 | import random 7 | import os 8 | import sys 9 | 10 | usage = ("\nDadaBots this_bot usage:\n" 11 | "*****************************************************************\n" 12 | "| python this_bot.py [url|file.intention] [remix] [post] [clean]\n" 13 | "*****************************************************************\n" 14 | "| Given a soundcloud track url it will download it and make a .intention file\n" 15 | "| Given a .intention file it will load the previously incomplete remix session\n" 16 | "| Given neither, it will find a new track on soundcloud from its followers\n" 17 | "|\n" 18 | "| The remix flag will remix the track and create a .rmx.mp3 file\n" 19 | "| The post flag will post the track to soundcloud.\n" 20 | "| The clean flag will delete the intention file after it's done.\n" 21 | "|\n" 22 | "| Examples:\n" 23 | "| * Totally automated bot from start to finish:\n" 24 | "| python this_bot.py remix post \n" 25 | "|\n" 26 | "| * Grab track at URL and remix it, but don't post it yet:\n" 27 | "| python this_bot.py http://soundcloud.com/dadabots/some-song remix\n" 28 | "|\n" 29 | "| * Repost an old remix, then delete the intention: \n" 30 | "| python this_bot.py ./intn/newatthetime.intention post clean\n" 31 | "|\n" 32 | "| Makes sense yet?\n" 33 | ) 34 | """ 35 | The .intention files are there so you can divvy download/remix/upload tasks. 36 | Also this helps make bot activity scalable. 37 | It doesn't require any computing power to download/upload. 38 | It doesn't require any internet bandwidth to remix. 39 | In a large bot ecosystem, these tasks should be threaded, and cloudified. 40 | """ 41 | 42 | bot = None 43 | def grabsong(url): 44 | global bot 45 | bot = DadaBot() 46 | bot.connect("becawwrdsaekva", "fckngtrdtn7.5") 47 | 48 | bot.tag = "weev" # for file names example: "song.rmx.weev.mp3" 49 | 50 | if url=="": 51 | bot.always_find_new_tracks = True # will not remix the same song twice 52 | bot.creative_commons_only = True # only remixes creative commons tracks 53 | bot.find_track() 54 | else: 55 | bot.grab_track(url) 56 | 57 | 58 | return bot.dump_intention() 59 | 60 | def remixsong(remixintention, window): 61 | global bot 62 | # load bot, reconnect to soundcloud, but only if we haven't already connected 63 | bot = DadaBot.load(remixintention) if not bot else bot 64 | 65 | if bot.already_remixed(): 66 | print "This song has already been remixed" 67 | return remixintention 68 | 69 | bot.remix_process_call = "python remix-scripts/becawwrdsaekva.py %s %s " + str(int(window)) 70 | ### 71 | # Do it! remix() runs a subprocess (probably an EchoNest python script), 72 | # it assumes the original mp3 is located at bot.track_mp3 73 | # it outputs the remixed mp3 to the location specified at: bot.remix_mp3 74 | bot.remix() 75 | 76 | return bot.dump_intention() 77 | 78 | def postsong(postintention): 79 | global bot 80 | # load bot, reconnect to soundcloud, but only if we haven't already connected 81 | 82 | bot = DadaBot.load(postintention) if not bot else bot 83 | 84 | if not bot.already_remixed(): 85 | print usage 86 | raise Exception("Sorry I can't post this song, it doesn't appear to be remixed") 87 | 88 | ### 89 | # Here is all the social activity of the bot: 90 | ### 91 | 92 | # update bot user art 93 | if(bot.user_art): 94 | remix_avatar = artremixer.octoflip(bot, bot.user_art) 95 | bot.update_avatar(remix_avatar) 96 | 97 | # remix track art 98 | if(bot.track_art): 99 | bot.remix_artwork = artremixer.art_florp(bot, bot.track_art) 100 | 101 | # remix title 102 | #bot.remix_title = "%s: %s [%s]" % tuple([bot.follower.username, bot.track.title, bot.tag]) 103 | def weave_words(old): 104 | old = str(old) 105 | new = "" 106 | oldlen = len(old) 107 | if oldlen == 0: 108 | return "" 109 | elif oldlen%2==0: 110 | old += " " 111 | oldlen+=1 112 | for i in range(0,oldlen): 113 | if i%2 : 114 | new += old[i] 115 | else: 116 | new += old[oldlen- i - 1 ] 117 | return new 118 | 119 | bot.remix_title = weave_words(bot.track.title) 120 | bot.genre = weave_words(bot.track.genre) 121 | bot.remix_description = weave_words(bot.track.description) 122 | 123 | # POST remix 124 | remix = bot.post_remix() 125 | 126 | # follow all the follower's followers 127 | bot.amicabilify(bot.follower) 128 | 129 | # like original track (this marks the track so that bot doesn't remix it twice) 130 | bot.like_track(bot.track) 131 | 132 | # comment on original track 133 | comment_string = bot.comment(bot.remix_track.permalink_url) 134 | print "Commenting . . . " + comment_string + "\n" 135 | track_comment = bot.client.post('/tracks/%d/comments' % bot.track.id, comment={ 136 | 'body': comment_string, 137 | 'timestamp': random.randint(0,bot.track.duration-1) 138 | }) 139 | 140 | # comment on remix 141 | remix_comment_string = weave_words("Original:") + bot.track.permalink_url 142 | print "Commenting . . . " + remix_comment_string + "\n" 143 | track_comment = bot.client.post('/tracks/%d/comments' % bot.remix_track.id, comment={ 144 | 'body': remix_comment_string, 145 | 'timestamp': 100 146 | }) 147 | 148 | 149 | 150 | 151 | 152 | if __name__ == '__main__': 153 | import sys 154 | 155 | if len(sys.argv)<=1: 156 | intention = grabsong("") # if given no input, grabs a new song from soundcloud followers 157 | elif "help" in sys.argv: 158 | print usage 159 | sys.exit() 160 | elif sys.argv[1][:4] == "http": 161 | intention = grabsong(sys.argv[1]) # if given an url, grabs that song 162 | elif sys.argv[1][-10:] == ".intention": 163 | intention = sys.argv[1] # loads previously incomplete bot intention 164 | if(len(sys.argv)<=2): 165 | print usage 166 | print "Warning: intentions must be accompanied with a post or remix flag" 167 | sys.exit() 168 | else: 169 | intention = grabsong("") # if not given url/file, grabs a new song from soundcloud followers 170 | 171 | if "remix" in sys.argv: 172 | # if remix flag is set, remix the song! 173 | intention = remixsong(intention, "window" in sys.argv) # "window" is another flag, which will put gaps of silence between segments. 174 | if "post" in sys.argv: 175 | intention = postsong(intention) # will throw exception if you try to post a song which hasn't been remixed 176 | 177 | if "clean" in sys.argv: 178 | if intention and os.path.exists(intention): 179 | os.remove(intention) 180 | print "Deleted " + intention 181 | else: 182 | print "Warning, no valid intention file given: " + str(intention) 183 | 184 | 185 | -------------------------------------------------------------------------------- /dadabots_old/chopshopshockshack.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import DadaBot 4 | from DadaBot import DadaBot 5 | import artremixer 6 | import random 7 | import os 8 | import sys 9 | 10 | 11 | usage = ("\nDadaBots this_bot usage:\n" 12 | "*****************************************************************\n" 13 | "| python this_bot.py [url|file.intention] [remix] [post] [clean]\n" 14 | "*****************************************************************\n" 15 | "| Given a soundcloud track url it will download it and make a .intention file\n" 16 | "| Given a .intention file it will load the previously incomplete remix session\n" 17 | "| Given neither, it will find a new track on soundcloud from its followers\n" 18 | "|\n" 19 | "| The remix flag will remix the track and create a .rmx.mp3 file\n" 20 | "| The post flag will post the track to soundcloud.\n" 21 | "| The clean flag will delete the intention file after it's done.\n" 22 | "|\n" 23 | "| Examples:\n" 24 | "| * Totally automated bot from start to finish:\n" 25 | "| python this_bot.py remix post \n" 26 | "|\n" 27 | "| * Grab track at URL and remix it, but don't post it yet:\n" 28 | "| python this_bot.py http://soundcloud.com/dadabots/some-song remix\n" 29 | "|\n" 30 | "| * Repost an old remix, then delete the intention: \n" 31 | "| python this_bot.py ./intn/newatthetime.intention post clean\n" 32 | "|\n" 33 | "| Makes sense yet?\n" 34 | ) 35 | """ 36 | The .intention files are there so you can divvy download/remix/upload tasks. 37 | Also this helps make bot activity scalable. 38 | It doesn't require any computing power to download/upload. 39 | It doesn't require any internet bandwidth to remix. 40 | In a large bot ecosystem, these tasks should be threaded, and cloudified. 41 | """ 42 | 43 | bot = None 44 | def grabsong(url): 45 | global bot 46 | bot = DadaBot() 47 | bot.connect("chopshopshockshack", "fckngtrdtn7.5") 48 | 49 | bot.remix_process_call = "python remix-scripts/dadarays.py %s %s" 50 | bot.tag = "(@)" 51 | 52 | if url=="": 53 | bot.always_find_new_tracks = True # will not remix the same song twice 54 | bot.creative_commons_only = True # only remixes creative commons tracks 55 | bot.find_track() 56 | else: 57 | bot.grab_track(url) 58 | 59 | 60 | return bot.dump_intention() 61 | 62 | def remixsong(remixintention): 63 | global bot 64 | # load bot, reconnect to soundcloud, but only if we haven't already connected 65 | bot = DadaBot.load(remixintention) if not bot else bot 66 | 67 | if bot.already_remixed(): 68 | print "This song has already been remixed" 69 | return remixintention 70 | 71 | ### 72 | # Do it! remix() runs a subprocess (probably an EchoNest python script), 73 | # it assumes the original mp3 is located at bot.track_mp3 74 | # it outputs the remixed mp3 to the location specified at: bot.remix_mp3 75 | bot.remix() 76 | 77 | return bot.dump_intention() 78 | 79 | def postsong(postintention): 80 | global bot 81 | # load bot, reconnect to soundcloud, but only if we haven't already connected 82 | 83 | bot = DadaBot.load(postintention) if not bot else bot 84 | 85 | if not bot.already_remixed(): 86 | print usage 87 | raise Exception("Sorry I can't post this song, it doesn't appear to be remixed") 88 | 89 | ### 90 | # Here is all the social activity of the bot: 91 | ### 92 | 93 | # update bot user art 94 | if(bot.user_art): 95 | remix_avatar = artremixer.octoflip(bot, bot.user_art) 96 | bot.update_avatar(remix_avatar) 97 | 98 | # remix track art 99 | if(bot.track_art): 100 | bot.remix_artwork = artremixer.art_florp(bot, bot.track_art) 101 | 102 | # remix title 103 | bot.remix_title = "%s - %s RMX (@)" % (bot.follower.username, bot.track.title) 104 | 105 | bot.genre = "@" 106 | bot.remix_description = "" 107 | 108 | # POST remix 109 | remix = bot.post_remix() 110 | 111 | # follow all the follower's followers 112 | bot.amicabilify(bot.follower) 113 | 114 | # like original track (this marks the track so that bot doesn't remix it twice) 115 | bot.like_track(bot.track) 116 | 117 | 118 | # edit comments here 119 | # %s is where remix url goes. 120 | bot.comments = [ 121 | "Ideas are kinky and what matters is a fun, but your swag is the acquisition of culture. %s", 122 | "If nothing is boring after two minutes? Try it four. Then Sixteen. You discover that nothing is eventually boring after all. %s", 123 | "I can understand why people are so frightened of new music for i'm frightened of old music. %s", 124 | "I knowww this is poetry! %s", 125 | "Killer drop. We need to annoy the past or it will not be gone. %s", 126 | "i like to discover for no reason. %s", 127 | "you enable me to fly. %s", 128 | "When you separated music from life we got art. %s", 129 | "You carry your home on your back? %s", 130 | "Those four sounds are good! %s", 131 | "Let's mingle or swap genes? %s" 132 | ] 133 | 134 | 135 | # comment on original track 136 | comment_string = bot.comment(bot.remix_track.permalink_url) 137 | print "Commenting . . . " + comment_string + "\n" 138 | track_comment = bot.client.post('/tracks/%d/comments' % bot.track.id, comment={ 139 | 'body': comment_string, 140 | 'timestamp': random.randint(0,bot.track.duration-1) 141 | }) 142 | 143 | # comment on remix 144 | remix_comment_string = "Original: " + bot.track.permalink_url 145 | print "Commenting . . . " + remix_comment_string + "\n" 146 | track_comment = bot.client.post('/tracks/%d/comments' % bot.remix_track.id, comment={ 147 | 'body': remix_comment_string, 148 | 'timestamp': 100 149 | }) 150 | 151 | 152 | 153 | 154 | 155 | if __name__ == '__main__': 156 | import sys 157 | 158 | if len(sys.argv)<=1: 159 | intention = grabsong("") # if given no input, grabs a new song from soundcloud followers 160 | elif "help" in sys.argv: 161 | print usage 162 | sys.exit() 163 | elif sys.argv[1][:4] == "http": 164 | intention = grabsong(sys.argv[1]) # if given an url, grabs that song 165 | elif sys.argv[1][-10:] == ".intention": 166 | intention = sys.argv[1] # loads previously incomplete bot intention 167 | if(len(sys.argv)<=2): 168 | print usage 169 | print "Warning: intentions must be accompanied with a post or remix flag" 170 | sys.exit() 171 | else: 172 | intention = grabsong("") # if not given url/file, grabs a new song from soundcloud followers 173 | 174 | if "remix" in sys.argv: 175 | intention = remixsong(intention) # if remix flag is set, remix the song! 176 | if "post" in sys.argv: 177 | intention = postsong(intention) # will throw exception if you try to post a song which hasn't been remixed 178 | 179 | if "clean" in sys.argv: 180 | if intention and os.path.exists(intention): 181 | os.remove(intention) 182 | print "Deleted " + intention 183 | else: 184 | print "Warning, no valid intention file given: " + str(intention) 185 | 186 | 187 | -------------------------------------------------------------------------------- /dadabots_old/violin_split.py: -------------------------------------------------------------------------------- 1 | from pylab import plot,show 2 | from numpy import vstack,array 3 | from numpy.random import rand 4 | from numpy.linalg import norm 5 | from scipy.cluster.vq import kmeans,vq 6 | from random import choice 7 | 8 | import sys 9 | import echonest.audio as audio 10 | from echonest.sorting import * 11 | from echonest.selection import * 12 | import pyechonest.config as config 13 | config.MP3_BITRATE = 192 14 | 15 | 16 | inputFilename="mp3/violin111.mp3" 17 | inputFilename2="mp3/isaaccjlaugh.mp3" 18 | 19 | 20 | # USAGE/EXAMPLE 21 | # python kcluster_afromb.py INPUT INPUT OUTPUT CLUSTERS MIX 22 | # python kcluster_afromb.py build.mp3 from.mp3 to.mp3 5 0.5 23 | 24 | 25 | 26 | inputFilename = sys.argv[1] 27 | inputFilename2 = sys.argv[2] 28 | 29 | outputFilename = sys.argv[3] 30 | # how many different groups will we cluster our data into? 31 | num_clusters = int(sys.argv[4]) 32 | # how many different groups will we cluster our data into? 33 | mix = float(sys.argv[5]) 34 | 35 | 36 | song = audio.LocalAudioFile(inputFilename) 37 | song2 = audio.LocalAudioFile(inputFilename2) 38 | 39 | 40 | sample_rate = song.sampleRate 41 | num_channels = song.numChannels 42 | out_shape = list(song.data.shape) 43 | out_shape[0] = 2 44 | out = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 45 | 46 | 47 | """ 48 | outs = [None]*2 49 | for n in range(0,num_clusters): 50 | outs[n] = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 51 | """ 52 | 53 | # for each section in song1 54 | for sectionnumber in range(0,len(song.analysis.bars)): 55 | # song1 section 56 | section = song.analysis.bars[sectionnumber] 57 | # song2 section. If too many sections, it loops back to beginning 58 | sectionnumber2 = sectionnumber % len(song2.analysis.sections) 59 | section2 = song2.analysis.sections[sectionnumber2] 60 | 61 | print "SECTION PAIRING: %i AND %i" % (sectionnumber, sectionnumber2) 62 | # default is grab all segments 63 | #sectionsegments = song.analysis.segments 64 | #sectionsegments2 = song2.analysis.segments 65 | 66 | # here we just grab the segments that overlap the section 67 | sectionsegments = song.analysis.segments.that(overlap(section)) 68 | sectionsegments2 = song2.analysis.segments.that(overlap(section2)) 69 | 70 | # this is just too easy 71 | # song.analysis.segments.timbre is a list of all 12-valued timbre vectors. 72 | # must be converted to a numpy.array() so that kmeans(data, n) is happy 73 | data = array(sectionsegments.timbre) 74 | data2 = array(sectionsegments2.timbre) 75 | 76 | # data generation 77 | # rand creates a random 150x2 matrix..or a multidimensional array of 150 (two floated) arrays 78 | # vstack concatenates matrices together 79 | # data = vstack((rand(150,2),rand(150,2))) 80 | 81 | while True: 82 | # computing K-Means with K = 2 (2 clusters) 83 | centroids,_ = kmeans(data,num_clusters) 84 | centroids2,_ = kmeans(data2,num_clusters) 85 | # assign each sample to a cluster 86 | idx,_ = vq(data,centroids) 87 | idx2,_ = vq(data2,centroids2) 88 | #idx lists the cluster that each data point belongs to [2, 0, 0, 1, 2] 89 | 90 | # sometimes kmeans won't return num_clusters 91 | if (len(centroids) == num_clusters) and (len(centroids2) == num_clusters): 92 | break 93 | else: 94 | print "We want %i num_clusters, but instead we got %i and %i" % (num_clusters, len(centroids), len(centroids2)) 95 | 96 | # How to sync up clusters? 97 | # I think a largest-first greedy algorithm will work. 98 | # 1) Find largest cluster A[c] in A 99 | # 2) Find closest cluster in B from A[c] 100 | # 3) Pair them. Remove from data. 101 | # 4) Continue until everything is paired. 102 | 103 | # first create a collection, and then sort it 104 | # not using python's collection, because of python2.6 compatability 105 | collection = [] 106 | for c in range(0, num_clusters): 107 | ccount = 0 108 | for i in idx: 109 | if i==c: 110 | ccount += 1 111 | collection.append([ccount, c]) 112 | collection.sort() 113 | # list of clusterindexes from largest to smallest 114 | centroid_pairs = [] 115 | 116 | 117 | for _,c in collection: 118 | centroid1 = array(centroids[c]) 119 | 120 | min_distance = [999999999999999999999999,0] 121 | for ci in range(0,len(centroids2)): 122 | if ci in [li[1] for li in centroid_pairs]: 123 | continue 124 | centroid2 = array(centroids2[ci]) 125 | euclidian_distance = norm(centroid1-centroid2) 126 | if euclidian_distance < min_distance[0]: 127 | min_distance = [euclidian_distance, ci] 128 | centroid_pairs.append([c,min_distance[1]]) 129 | 130 | 131 | print centroid_pairs 132 | 133 | 134 | # Just so we're clear, we're rebuilding the structure of song1 with segments from song2 135 | 136 | # prepare song2 clusters, 137 | segclusters2 = [[]]*len(centroids2) 138 | for s2 in range(0,len(idx2)): 139 | segment2 = sectionsegments2[s2] 140 | cluster2 = idx2[s2] 141 | segment2.numpytimbre = array(segment2.timbre) 142 | segclusters2[cluster2].append(segment2) 143 | 144 | # for each segment1 in song1, find the timbrely closest segment2 in song2 belonging to the cluster2 with which segment1's cluster1 is paired. 145 | for s in range(0,len(idx)): 146 | segment1 = sectionsegments[s] 147 | cluster1 = idx[s] 148 | cluster2 = [li[1] for li in centroid_pairs if li[0]==cluster1][0] 149 | 150 | 151 | timbre1 = array(segment1.timbre) 152 | min_distance = [9999999999999,0] 153 | for seg in segclusters2[cluster2]: 154 | timbre2 = seg.numpytimbre 155 | euclidian_distance = norm(timbre2-timbre1) 156 | if euclidian_distance < min_distance[0]: 157 | min_distance = [euclidian_distance, seg] 158 | bestmatchsegment2 = min_distance[1] 159 | # we found the segment2 in song2 that best matches segment1 160 | 161 | 162 | # faster, more varied version, picks a random segment from that cluster 163 | # bestmatchsegment2 = choice(segclusters2[cluster2]) 164 | 165 | reference_data = song[segment1] 166 | segment_data = song2[bestmatchsegment2] 167 | 168 | # do we stretch or do we add silence? 169 | # 170 | # SILENCE: 171 | if reference_data.endindex > segment_data.endindex: 172 | # we need to add silence, because segment1 is longer 173 | if num_channels > 1: 174 | silence_shape = (reference_data.endindex,num_channels) 175 | else: 176 | silence_shape = (reference_data.endindex,) 177 | new_segment = audio.AudioData(shape=silence_shape, 178 | sampleRate=out.sampleRate, 179 | numChannels=segment_data.numChannels) 180 | new_segment.append(segment_data) 181 | new_segment.endindex = len(new_segment) 182 | segment_data = new_segment 183 | elif reference_data.endindex < segment_data.endindex: 184 | # we need to cut segment2 shorter, because segment2 is shorter 185 | index = slice(0, int(reference_data.endindex), 1) 186 | segment_data = audio.AudioData(None, segment_data.data[index], sampleRate=segment_data.sampleRate) 187 | 188 | 189 | mixed_data = audio.mix(segment_data,reference_data,mix=mix) 190 | out.append(mixed_data) 191 | 192 | 193 | out.encode(outputFilename) 194 | 195 | """ 196 | RENDER TO FILES: 197 | 198 | #this code makes segclusters, which is a list of each cluster of segments. 199 | segclusters = [[]]*num_clusters 200 | for s in range(0, len(idx)): 201 | segment = song.analysis.segments[s] 202 | cluster_number = idx[s] 203 | outs[cluster_number].append(song[segment]) 204 | 205 | 206 | # render each out to files 207 | inc = 0 208 | for out in outs: 209 | out.encode("clusters/afromb"+str(inc)+".mp3") 210 | inc += 1 211 | 212 | 213 | """ -------------------------------------------------------------------------------- /dadabots_old/kcluster_afromb_sections.py: -------------------------------------------------------------------------------- 1 | from pylab import plot,show 2 | from numpy import vstack,array 3 | from numpy.random import rand 4 | from numpy.linalg import norm 5 | from scipy.cluster.vq import kmeans,vq 6 | from random import choice 7 | 8 | import sys 9 | import echonest.audio as audio 10 | from echonest.sorting import * 11 | from echonest.selection import * 12 | import pyechonest.config as config 13 | config.MP3_BITRATE = 192 14 | 15 | 16 | inputFilename="mp3/bunchofbreaks.mp3" 17 | inputFilename2="mp3/isaaccjlaugh.mp3" 18 | 19 | 20 | # USAGE/EXAMPLE 21 | # python kcluster_afromb.py INPUT INPUT OUTPUT CLUSTERS MIX 22 | # python kcluster_afromb.py build.mp3 from.mp3 to.mp3 5 0.5 23 | 24 | 25 | 26 | inputFilename = sys.argv[1] 27 | inputFilename2 = sys.argv[2] 28 | 29 | outputFilename = sys.argv[3] 30 | # how many different groups will we cluster our data into? 31 | num_clusters = int(sys.argv[4]) 32 | # how many different groups will we cluster our data into? 33 | mix = float(sys.argv[5]) 34 | 35 | 36 | song = audio.LocalAudioFile(inputFilename) 37 | song2 = audio.LocalAudioFile(inputFilename2) 38 | 39 | 40 | sample_rate = song.sampleRate 41 | num_channels = song.numChannels 42 | out_shape = list(song.data.shape) 43 | out_shape[0] = 2 44 | out = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 45 | 46 | 47 | """ 48 | outs = [None]*2 49 | for n in range(0,num_clusters): 50 | outs[n] = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 51 | """ 52 | 53 | # for each section in song1 54 | for sectionnumber in range(0,len(song.analysis.bars)): 55 | # song1 section 56 | section = song.analysis.bars[sectionnumber] 57 | # song2 section. If too many sections, it loops back to beginning 58 | sectionnumber2 = sectionnumber % len(song2.analysis.sections) 59 | section2 = song2.analysis.sections[sectionnumber2] 60 | 61 | print "SECTION PAIRING: %i AND %i" % (sectionnumber, sectionnumber2) 62 | # default is grab all segments 63 | #sectionsegments = song.analysis.segments 64 | #sectionsegments2 = song2.analysis.segments 65 | 66 | # here we just grab the segments that overlap the section 67 | sectionsegments = song.analysis.segments.that(overlap(section)) 68 | sectionsegments2 = song2.analysis.segments.that(overlap(section2)) 69 | 70 | # this is just too easy 71 | # song.analysis.segments.timbre is a list of all 12-valued timbre vectors. 72 | # must be converted to a numpy.array() so that kmeans(data, n) is happy 73 | data = array(sectionsegments.timbre) 74 | data2 = array(sectionsegments2.timbre) 75 | 76 | # data generation 77 | # rand creates a random 150x2 matrix..or a multidimensional array of 150 (two floated) arrays 78 | # vstack concatenates matrices together 79 | # data = vstack((rand(150,2),rand(150,2))) 80 | 81 | while True: 82 | # computing K-Means with K = 2 (2 clusters) 83 | centroids,_ = kmeans(data,num_clusters) 84 | centroids2,_ = kmeans(data2,num_clusters) 85 | # assign each sample to a cluster 86 | idx,_ = vq(data,centroids) 87 | idx2,_ = vq(data2,centroids2) 88 | #idx lists the cluster that each data point belongs to [2, 0, 0, 1, 2] 89 | 90 | # sometimes kmeans won't return num_clusters 91 | if (len(centroids) == num_clusters) and (len(centroids2) == num_clusters): 92 | break 93 | else: 94 | print "We want %i num_clusters, but instead we got %i and %i" % (num_clusters, len(centroids), len(centroids2)) 95 | 96 | # How to sync up clusters? 97 | # I think a largest-first greedy algorithm will work. 98 | # 1) Find largest cluster A[c] in A 99 | # 2) Find closest cluster in B from A[c] 100 | # 3) Pair them. Remove from data. 101 | # 4) Continue until everything is paired. 102 | 103 | # first create a collection, and then sort it 104 | # not using python's collection, because of python2.6 compatability 105 | collection = [] 106 | for c in range(0, num_clusters): 107 | ccount = 0 108 | for i in idx: 109 | if i==c: 110 | ccount += 1 111 | collection.append([ccount, c]) 112 | collection.sort() 113 | # list of clusterindexes from largest to smallest 114 | centroid_pairs = [] 115 | 116 | 117 | for _,c in collection: 118 | centroid1 = array(centroids[c]) 119 | 120 | min_distance = [999999999999999999999999,0] 121 | for ci in range(0,len(centroids2)): 122 | if ci in [li[1] for li in centroid_pairs]: 123 | continue 124 | centroid2 = array(centroids2[ci]) 125 | euclidian_distance = norm(centroid1-centroid2) 126 | if euclidian_distance < min_distance[0]: 127 | min_distance = [euclidian_distance, ci] 128 | centroid_pairs.append([c,min_distance[1]]) 129 | 130 | 131 | print centroid_pairs 132 | 133 | 134 | # Just so we're clear, we're rebuilding the structure of song1 with segments from song2 135 | 136 | # prepare song2 clusters, 137 | segclusters2 = [[]]*len(centroids2) 138 | for s2 in range(0,len(idx2)): 139 | segment2 = sectionsegments2[s2] 140 | cluster2 = idx2[s2] 141 | segment2.numpytimbre = array(segment2.timbre) 142 | segclusters2[cluster2].append(segment2) 143 | 144 | # for each segment1 in song1, find the timbrely closest segment2 in song2 belonging to the cluster2 with which segment1's cluster1 is paired. 145 | for s in range(0,len(idx)): 146 | segment1 = sectionsegments[s] 147 | cluster1 = idx[s] 148 | cluster2 = [li[1] for li in centroid_pairs if li[0]==cluster1][0] 149 | 150 | 151 | timbre1 = array(segment1.timbre) 152 | min_distance = [9999999999999,0] 153 | for seg in segclusters2[cluster2]: 154 | timbre2 = seg.numpytimbre 155 | euclidian_distance = norm(timbre2-timbre1) 156 | if euclidian_distance < min_distance[0]: 157 | min_distance = [euclidian_distance, seg] 158 | bestmatchsegment2 = min_distance[1] 159 | # we found the segment2 in song2 that best matches segment1 160 | 161 | 162 | # faster, more varied version, picks a random segment from that cluster 163 | # bestmatchsegment2 = choice(segclusters2[cluster2]) 164 | 165 | reference_data = song[segment1] 166 | segment_data = song2[bestmatchsegment2] 167 | 168 | # do we stretch or do we add silence? 169 | # 170 | # SILENCE: 171 | if reference_data.endindex > segment_data.endindex: 172 | # we need to add silence, because segment1 is longer 173 | if num_channels > 1: 174 | silence_shape = (reference_data.endindex,num_channels) 175 | else: 176 | silence_shape = (reference_data.endindex,) 177 | new_segment = audio.AudioData(shape=silence_shape, 178 | sampleRate=out.sampleRate, 179 | numChannels=segment_data.numChannels) 180 | new_segment.append(segment_data) 181 | new_segment.endindex = len(new_segment) 182 | segment_data = new_segment 183 | elif reference_data.endindex < segment_data.endindex: 184 | # we need to cut segment2 shorter, because segment2 is shorter 185 | index = slice(0, int(reference_data.endindex), 1) 186 | segment_data = audio.AudioData(None, segment_data.data[index], sampleRate=segment_data.sampleRate) 187 | 188 | 189 | mixed_data = audio.mix(segment_data,reference_data,mix=mix) 190 | out.append(mixed_data) 191 | 192 | 193 | out.encode(outputFilename) 194 | 195 | """ 196 | RENDER TO FILES: 197 | 198 | #this code makes segclusters, which is a list of each cluster of segments. 199 | segclusters = [[]]*num_clusters 200 | for s in range(0, len(idx)): 201 | segment = song.analysis.segments[s] 202 | cluster_number = idx[s] 203 | outs[cluster_number].append(song[segment]) 204 | 205 | 206 | # render each out to files 207 | inc = 0 208 | for out in outs: 209 | out.encode("clusters/afromb"+str(inc)+".mp3") 210 | inc += 1 211 | 212 | 213 | """ -------------------------------------------------------------------------------- /dadabots_old/remix-scripts/dadarays.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf=8 3 | """ 4 | dadarays.py 5 | 6 | timbrally guided dadaist dissociated array maker 7 | based on dissociated array (adam lindsay) reimagined by Zack Zukowski and CJ Carr 8 | 9 | """ 10 | import random 11 | import echonest.audio as audio 12 | from echonest.sorting import * 13 | from echonest.selection import * 14 | 15 | 16 | import pyechonest.config as config 17 | config.MP3_BITRATE = 192 18 | 19 | 20 | usage = """ 21 | python dadarays.py 22 | 23 | Example: 24 | python dadarays.py of_the_sun.mp3 not_of_the_sun.mp3 25 | """ 26 | 27 | def strong_meter(choices, song, meter, sections, sl, outchunks): 28 | #itterate through every section 29 | for section in sections: 30 | #store all beats and segments in this section 31 | beats = song.analysis.beats.that(are_contained_by(section)) 32 | segments = song.analysis.segments.that(overlap(section)) 33 | # store the number of bars in this section 34 | num_bars = len(section.children()) 35 | #create new arrays for organizing beats and segments 36 | b = [] 37 | segstarts = [] 38 | #itterate from 0 - the number of beats in a measure 39 | for m in range(meter): 40 | #store all beats in this section that fall on the current metrical beat number 41 | b.append(beats.that(fall_on_the(m+1))) 42 | #store all segments overlapping start time of the above beats 43 | segstarts.append(segments.that(overlap_starts_of(b[m]))) 44 | #initiate the current time and stop time 45 | now = b[0][0] 46 | end_range = num_bars * meter 47 | #replace all measures beat by beat 48 | for x in range(0, end_range + 1): 49 | #store the current and next location in the meter 50 | beat = x % meter 51 | next_beat = (x + 1) % meter 52 | #store the last segment of this beat 53 | now_end_segment = segments.that(contain_point(now.end))[0] 54 | #make a list of beats whos starting timbres best match this ending timbre 55 | next_candidates = segstarts[next_beat].ordered_by(timbre_distance_from(now_end_segment)) 56 | 57 | """ 58 | identify the optimum segment variation 59 | unless now is a transition segment 60 | transition segments are the first or last beats in a section 61 | """ 62 | #store how percussive this ending timbre is 63 | perc_num = ((now_end_segment.timbre[10] + now_end_segment.timbre[6] + now_end_segment.timbre[8] + now_end_segment.timbre[11]) / 4) 64 | #store how ambient this ending timbre is 65 | ambi_num = ((now_end_segment.timbre[2] + now_end_segment.timbre[5]) /2) 66 | # is this the second last beat in the section? 67 | if x == end_range - 1: 68 | print "beat number in section" 69 | print x 70 | #this is the end so pick the last beat! 71 | choices = 0 72 | now = beats[len(beats) - 1] 73 | #Ambient or Percussive? 74 | elif ambi_num > perc_num: 75 | #be smooth 76 | choices = 0 77 | x = x + meter 78 | else: 79 | if end_range > meter * 6: 80 | randoo = random.randrange(0, 3, 1) 81 | else: 82 | randoo = random.randrange(0, 1, 1) 83 | choices = choices + randoo 84 | # reduce choices to be within range of next candidates 85 | while choices >= len(next_candidates) and choices > 0: 86 | choices -= 1 87 | #pick the next beat 88 | next_choice = next_candidates[choices] 89 | #store the next beat 90 | is_next = b[next_beat].that(start_during(next_choice))[0] 91 | #add the current beat to the remix 92 | outchunks.append(now) 93 | #remember the next choosen one... 94 | now = is_next 95 | # is this a long or short section (4 bars) 96 | #randomly choose the timbral dissociation ammount in this section !!!!CJ L00k!!!! 97 | if end_range > meter * 4: 98 | rando = random.randrange(2, 6, 1) 99 | else: 100 | rando = random.randrange(0, 1, 1) 101 | choices = rando 102 | return outchunks 103 | 104 | def weak_meter(choices, song, sections, sl, outchunks): 105 | for section in sections: 106 | i = 0 107 | # store all the segments in this section 108 | segments = song.analysis.segments.that(overlap(section)) 109 | # store number of segments 110 | e = len(segments) 111 | #only use 1/4 of the length 112 | e = e / 4 113 | #initiate the curent segment 114 | now_segment = segments[0] 115 | #pick a segment until desired length is rebuilt 116 | while i < e: 117 | #add this segment to the remix 118 | outchunks.append(now_segment) 119 | #do the following a third of the time 120 | if random.randrange(0, 2, 1) == 0: 121 | #pick the next segment 122 | next_segment = (segments.ordered_by(timbre_distance_from(now_segment))[0]) 123 | #add the segment to the remix 124 | outchunks.append(next_segment) 125 | #pick the next next and store it as now 126 | next_next_segment = (segments.ordered_by(timbre_distance_from(next_segment))[0]) 127 | now_segment = next_next_segment 128 | #order by similar durations 129 | time_candidates = song.analysis.segments.ordered_by(duration(now_segment)) 130 | n = 0 131 | #keep just the first 20 most similar durations 132 | for segment in time_candidates: 133 | if n > 20: 134 | del segment 135 | n += 1 136 | #pick similar timbre out of the 20 segments with similar durations 137 | timbre_candidates = time_candidates.ordered_by(timbre_distance_from(now_segment)) 138 | #pick one out of the 4 best 139 | choosen = timbre_candidates[random.randrange(4)] 140 | #store this choice as the next segment 141 | now_segment = choosen 142 | i += 1 143 | return outchunks 144 | 145 | def main(input_filename, output_filename): 146 | choices = 0 147 | song = audio.LocalAudioFile(input_filename) 148 | meter = song.analysis.time_signature.values()[1] 149 | meter_conf = song.analysis.time_signature.values()[0] 150 | tempo_conf = song.analysis.tempo.values()[0] 151 | sections = song.analysis.sections 152 | last_segment = song.analysis.segments[len(song.analysis.segments) - 1] 153 | sl = len(sections) 154 | print "meter confidence" 155 | print meter_conf 156 | print "meter" 157 | print song.analysis.time_signature 158 | print "number of sections" 159 | print sl 160 | outchunks = audio.AudioQuantumList() 161 | if (meter_conf > 0.2): 162 | outchunks = strong_meter(choices, song, meter, sections, sl, outchunks) 163 | else: 164 | outchunks = weak_meter(choices, song, sections, sl, outchunks) 165 | outchunks.append(last_segment) 166 | out = audio.getpieces(song, outchunks) 167 | out.encode(output_filename) 168 | 169 | 170 | if __name__ == '__main__': 171 | import sys 172 | try: 173 | input_filename = sys.argv[1] 174 | output_filename = sys.argv[2] 175 | except: 176 | print usage 177 | sys.exit(-1) 178 | main(input_filename, output_filename) 179 | -------------------------------------------------------------------------------- /kcluster_afromb.py: -------------------------------------------------------------------------------- 1 | """ 2 | kcluster_afromb.py 3 | 4 | 2013 CJ Carr, Zack Zukowski 5 | cortexel.us 6 | cj@imreallyawesome.com 7 | http://github.com/cortexelus/dadabots 8 | 9 | An improved version of Ben Lacker's afromb.py. 10 | 11 | Uses k-means clustering on timbre data. 12 | For each segment in a: 13 | Puts it into one of k groups 14 | Matches that group with a group in b 15 | Picks a new segment from b's group (randomly, the best match, or from a set of best matches) 16 | 17 | In this way, the diversity of timbre is preserved. 18 | (afromb.py takes every segment in a and finds the closest segment in b---but this process doesn't preserve the diversity of b) 19 | 20 | Which makes it possible to take simple beats (kick snare hithat) and layer an enslaught of samples ontop of them while preserving the ebb and flow of the rhythm. 21 | For example, as this song: http://soundcloud.com/cortexelus/23-mindsplosion-algorithmic 22 | 23 | ############################# 24 | 25 | USAGE: 26 | python kcluster_afromb.py INPUT1 INPUT2 OUTPUT MIX NUMCLUSTERS BESTMATCH 27 | 28 | EXAMPLES: 29 | python kcluster_afromb.py song_structure.mp3 sample_library.mp3 remix.mp3 0.8 10 2 30 | 31 | # Setting NUMCLUSTERS to 1 and BESTMATCH to 1 is essentially the same thing as running the original afromb.py 32 | python kcluster_afromb.py a.mp3 b.mp3 out.mp3 0.5 1 1 33 | 34 | # To layer an enslaught of samples on a simple beat, set k to around 3-6 and set bestmatch to 0. Sample enslaught!!!!!!!! 35 | python kcluster_afromb.py drumbreaks.mp3 synthlib.mp3 out.mp3 0.5 4 0 36 | 37 | ############################# 38 | 39 | INPUT1: soundfile, the song's structure 40 | 41 | INPUT2: soundfile, where the samples are coming from 42 | 43 | OUTPUT: output file, sounds like INPUT2 remixed to fit the structure of INPUT1 44 | 45 | MIX The volume mix between remixed INPUT2 and the original INPUT1. 46 | 0 only the original INPUT1 47 | 1.0 only the remixed INPUT2 48 | 0.5 half of each 49 | 50 | NUMCLUSTERS: the k in k-means clustering. 51 | There are usually about 500-1500 segments in a song. 52 | We groups those segments into K groups. 53 | k = 1 is the same as not running k-means clustering at all. 54 | I usually get good results using something between k = 3 (kick, snare, hihat) and k = 20, but you should really just experiment to find out, because it depends on your source files and what effect you want. 55 | 56 | BESTMATCH: Which segment do we pick from b's group? 57 | 0 random 58 | 1 pick the best match 59 | 2 pick randomly from the best 2 matches 60 | n pick randomly from the best n matches 61 | 62 | ############################# 63 | 64 | TODO: 65 | * How do we fit b's segments to a's structure? Right now we add silence. TODO: add option to stretch audio. 66 | * Option to set K as a fraction of total segments. 67 | 68 | <3\m/ 69 | 70 | """ 71 | 72 | from numpy import vstack,array 73 | from numpy.random import rand 74 | from numpy.linalg import norm 75 | from scipy.cluster.vq import kmeans,vq 76 | from random import choice 77 | 78 | import sys 79 | import echonest.audio as audio 80 | from echonest.sorting import * 81 | from echonest.selection import * 82 | import pyechonest.config as config 83 | config.MP3_BITRATE = 192 # take this line out if you want to use default bitrate 84 | 85 | inputFilename = sys.argv[1] 86 | inputFilename2 = sys.argv[2] 87 | outputFilename = sys.argv[3] 88 | 89 | # how many different groups will we cluster our data into? 90 | mix = float(sys.argv[4]) 91 | 92 | # how many different groups will we cluster our data into? 93 | num_clusters = int(sys.argv[5]) 94 | 95 | # best_match = 1 # slower, less varied version. Good for b's which are percussion loops 96 | # best_match = 0 # faster, more varied version, picks a random segment from that cluster. Good for b's which are sample salads. 97 | best_match = int(sys.argv[6]) 98 | 99 | # analyze the songs 100 | song = audio.LocalAudioFile(inputFilename) 101 | song2 = audio.LocalAudioFile(inputFilename2) 102 | 103 | # build a blank output song, to populate later 104 | sample_rate = song.sampleRate 105 | num_channels = song.numChannels 106 | out_shape = list(song.data.shape) 107 | out_shape[0] = 2 108 | out = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 109 | 110 | # grab timbre data 111 | # must be converted to a numpy.array() so that kmeans(data, n) is happy 112 | data = array(song.analysis.segments.timbre) 113 | data2 = array(song2.analysis.segments.timbre) 114 | 115 | # computing K-Means with k = num_clusters 116 | centroids,_ = kmeans(data,num_clusters) 117 | centroids2,_ = kmeans(data2,num_clusters) 118 | # assign each sample to a cluster 119 | idx,_ = vq(data,centroids) 120 | idx2,_ = vq(data2,centroids2) 121 | #idx lists the cluster that each data point belongs to 122 | # ex. (k=2) [2, 0, 0, 1, 0, 2, 0, 0, 1, 2] 123 | 124 | # How to pair up clusters? 125 | # I think a largest-first greedy algorithm will work. 126 | # 1) Find largest cluster A[c] in A 127 | # 2) Find closest cluster in B from A[c] 128 | # 3) Pair them. Remove from data. 129 | # 4) Continue until everything is paired. 130 | 131 | # first create a collection, and then sort it 132 | # not using python's collection, because of python2.6 compatability 133 | collection = [] 134 | for c in range(0, num_clusters): 135 | ccount = 0 136 | for i in idx: 137 | if i==c: 138 | ccount += 1 139 | collection.append([ccount, c]) 140 | collection.sort() 141 | # list of cluster indices from largest to smallest 142 | 143 | centroid_pairs = [] 144 | for _,c in collection: 145 | centroid1 = array(centroids[c]) 146 | min_distance = [9999999999,0] 147 | for ci in range(0,len(centroids2)): 148 | if ci in [li[1] for li in centroid_pairs]: 149 | continue 150 | centroid2 = array(centroids2[ci]) 151 | euclidian_distance = norm(centroid1-centroid2) 152 | if euclidian_distance < min_distance[0]: 153 | min_distance = [euclidian_distance, ci] 154 | centroid_pairs.append([c,min_distance[1]]) 155 | 156 | print centroid_pairs 157 | # now we have a list of paired up cluster indices. Cool. 158 | 159 | # Just so we're clear, we're rebuilding the structure of song1 with segments from song2 160 | 161 | # prepare song2 clusters, 162 | segclusters2 = [audio.AudioQuantumList()]*len(centroids2) 163 | for s2 in range(0,len(idx2)): 164 | segment2 = song2.analysis.segments[s2] 165 | cluster2 = idx2[s2] 166 | segment2.numpytimbre = array(segment2.timbre) 167 | segclusters2[cluster2].append(segment2) 168 | 169 | # for each segment1 in song1, find the timbrely closest segment2 in song2 belonging to the cluster2 with which segment1's cluster1 is paired. 170 | for s in range(0,len(idx)): 171 | segment1 = song.analysis.segments[s] 172 | cluster1 = idx[s] 173 | cluster2 = [li[1] for li in centroid_pairs if li[0]==cluster1][0] 174 | 175 | if(best_match>0): 176 | # slower, less varied version. Good for b's which are percussion loops 177 | 178 | """ 179 | # there's already a function for this, use that instead: timbre_distance_from 180 | timbre1 = array(segment1.timbre) 181 | min_distance = [9999999999999,0] 182 | for seg in segclusters2[cluster2]: 183 | timbre2 = seg.numpytimbre 184 | euclidian_distance = norm(timbre2-timbre1) 185 | if euclidian_distance < min_distance[0]: 186 | min_distance = [euclidian_distance, seg] 187 | bestmatchsegment2 = min_distance[1] 188 | # we found the segment2 in song2 that best matches segment1 189 | """ 190 | 191 | bestmatches = segclusters2[cluster2].ordered_by(timbre_distance_from(segment1)) 192 | 193 | if(best_match > 1): 194 | # if best_match > 1, it randomly grabs from the top best_matches. 195 | maxmatches = max(best_match, len(bestmatches)) 196 | bestmatchsegment2 = choice(bestmatches[0:maxmatches]) 197 | else: 198 | # if best_match == 1, it grabs the exact best match 199 | bestmatchsegment2 = bestmatches[0] 200 | else: 201 | # faster, more varied version, picks a random segment from that cluster. Good for sample salads. 202 | bestmatchsegment2 = choice(segclusters2[cluster2]) 203 | 204 | reference_data = song[segment1] 205 | segment_data = song2[bestmatchsegment2] 206 | 207 | # what to do when segments lengths aren't equal? (almost always) 208 | # do we add silence? or do we stretch the samples? 209 | add_silence = True 210 | 211 | # This is the add silence solution: 212 | if add_silence: 213 | if reference_data.endindex > segment_data.endindex: 214 | # we need to add silence, because segment1 is longer 215 | if num_channels > 1: 216 | silence_shape = (reference_data.endindex,num_channels) 217 | else: 218 | silence_shape = (reference_data.endindex,) 219 | new_segment = audio.AudioData(shape=silence_shape, 220 | sampleRate=out.sampleRate, 221 | numChannels=segment_data.numChannels) 222 | new_segment.append(segment_data) 223 | new_segment.endindex = len(new_segment) 224 | segment_data = new_segment 225 | elif reference_data.endindex < segment_data.endindex: 226 | # we need to cut segment2 shorter, because segment2 is shorter 227 | index = slice(0, int(reference_data.endindex), 1) 228 | segment_data = audio.AudioData(None, segment_data.data[index], sampleRate=segment_data.sampleRate) 229 | else: 230 | # TODO: stretch samples to fit. 231 | # haven't written this part yet. 232 | segment_data = segment_data 233 | 234 | # mix the original and the remix 235 | mixed_data = audio.mix(segment_data,reference_data,mix=mix) 236 | out.append(mixed_data) 237 | 238 | # redner output 239 | out.encode(outputFilename) 240 | -------------------------------------------------------------------------------- /dadabots_old/alltheclusters.py: -------------------------------------------------------------------------------- 1 | """ 2 | kcluster_afromb.py 3 | 4 | 2013 CJ Carr, Zack Zukowski 5 | cortexel.us 6 | cj@imreallyawesome.com 7 | http://github.com/cortexelus/dadabots 8 | 9 | An improved version of echonest's afromb.py. 10 | 11 | Uses k-means clustering on timbre data. 12 | For each segment in a: 13 | Puts it into one of k groups 14 | Matches that group with a group in b 15 | Picks a new segment from b's group (randomly, the best match, or from a set of best matches) 16 | 17 | In this way, the diversity of timbre is preserved. 18 | (unlike the previous ruler of the lands afromb.py, which merely took every segment in a found the closest segment in b----its process didn't preserve the diversity of b) 19 | 20 | Which makes it possible to take simple beats (kick snare hithat) and layer an enslaught of samples ontop of them while preserving the ebb and flow of the rhythm. 21 | 22 | Which could be the basis of like a whole genre of electronic music. 23 | 24 | ############################# 25 | 26 | USAGE: 27 | python kcluster_afromb.py INPUT1 INPUT2 OUTPUT MIX NUMCLUSTERS BESTMATCH 28 | 29 | EXAMPLES: 30 | python kcluster_afromb.py song_structure.mp3 sample_library.mp3 remix.mp3 0.8 10 2 31 | 32 | # Setting NUMCLUSTERS to 1 and BESTMATCH to 1 is essentially the same thing as running the original afromb.py 33 | python kcluster_afromb.py a.mp3 b.mp3 out.mp3 0.5 1 1 34 | 35 | # To layer an enslaught of samples on a simple beat, set k to around 3-6 and set bestmatch to 0. Sample enslaught!!!!!!!! 36 | python kcluster_afromb.py drumbreaks.mp3 synthlib.mp3 out.mp3 0.5 4 0 37 | 38 | ############################# 39 | 40 | INPUT1: soundfile, the song's structure 41 | 42 | INPUT2: soundfile, where the samples are coming from 43 | 44 | OUTPUT: output file, sounds like INPUT2 remixed to fit the structure of INPUT1 45 | 46 | MIX The volume mix between remixed INPUT2 and the original INPUT1. 47 | 0 only the original INPUT1 48 | 1.0 only the remixed INPUT2 49 | 0.5 half of each 50 | 51 | NUMCLUSTERS: the k in k-means clustering. 52 | There are usually about 500-1500 segments in a song. 53 | We groups those segments into K groups. 54 | k = 1 is the same as not running k-means clustering at all. 55 | I usually get good results using something between k = 3 (kick, snare, hihat) and k = 20, but you should really just experiment to find out, because it depends on your source files and what effect you want. 56 | 57 | BESTMATCH: Which segment do we pick from b's group? 58 | 0 random 59 | 1 pick the best match 60 | 2 pick randomly from the best 2 matches 61 | n pick randomly from the best n matches 62 | 63 | ############################# 64 | 65 | TODO: 66 | * How do we fit b's segments to a's structure? Right now we add silence. TODO: add option to stretch audio. 67 | * Option to set K as a fraction of total segments. 68 | 69 | <3\m/ 70 | 71 | """ 72 | 73 | from numpy import vstack,array 74 | from numpy.random import rand 75 | from numpy.linalg import norm 76 | from scipy.cluster.vq import kmeans,vq 77 | from random import choice 78 | 79 | import sys 80 | import echonest.audio as audio 81 | from echonest.sorting import * 82 | from echonest.selection import * 83 | import pyechonest.config as config 84 | config.MP3_BITRATE = 192 # take this line out if you want to use default bitrate 85 | 86 | inputFilename = sys.argv[1] 87 | outputFilename = sys.argv[2] 88 | 89 | # how many different groups will we cluster our data into? 90 | num_clusters = int(sys.argv[3]) 91 | 92 | # best_match = 1 # slower, less varied version. Good for b's which are percussion loops 93 | # best_match = 0 # faster, more varied version, picks a random segment from that cluster. Good for b's which are sample salads. 94 | best_match = int(sys.argv[4]) 95 | 96 | # analyze the songs 97 | song = audio.LocalAudioFile(inputFilename) 98 | #song2 = audio.LocalAudioFile(inputFilename2) 99 | 100 | # build a blank output song, to populate later 101 | sample_rate = song.sampleRate 102 | num_channels = song.numChannels 103 | out_shape = list(song.data.shape) 104 | out_shape[0] = 2 105 | out = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 106 | 107 | # grab timbre data 108 | # must be converted to a numpy.array() so that kmeans(data, n) is happy 109 | data = array(song.analysis.segments.timbre) 110 | #data2 = array(song2.analysis.segments.timbre) 111 | 112 | # computing K-Means with k = num_clusters 113 | centroids,_ = kmeans(data,num_clusters) 114 | #centroids2,_ = kmeans(data2,num_clusters) 115 | # assign each sample to a cluster 116 | idx,_ = vq(data,centroids) 117 | #idx2,_ = vq(data2,centroids2) 118 | #idx lists the cluster that each data point belongs to 119 | # ex. (k=2) [2, 0, 0, 1, 0, 2, 0, 0, 1, 2] 120 | 121 | # How to pair up clusters? 122 | # I think a largest-first greedy algorithm will work. 123 | # 1) Find largest cluster A[c] in A 124 | # 2) Find closest cluster in B from A[c] 125 | # 3) Pair them. Remove from data. 126 | # 4) Continue until everything is paired. 127 | 128 | # first create a collection, and then sort it 129 | # not using python's collection, because of python2.6 compatability 130 | collection = [] 131 | for c in range(0, num_clusters): 132 | ccount = 0 133 | for i in idx: 134 | if i==c: 135 | ccount += 1 136 | collection.append([ccount, c]) 137 | collection.sort() 138 | # list of cluster indices from largest to smallest 139 | 140 | """ 141 | centroid_pairs = [] 142 | for _,c in collection: 143 | centroid1 = array(centroids[c]) 144 | min_distance = [9999999999,0] 145 | for ci in range(0,len(centroids2)): 146 | if ci in [li[1] for li in centroid_pairs]: 147 | continue 148 | centroid2 = array(centroids2[ci]) 149 | euclidian_distance = norm(centroid1-centroid2) 150 | if euclidian_distance < min_distance[0]: 151 | min_distance = [euclidian_distance, ci] 152 | centroid_pairs.append([c,min_distance[1]]) 153 | 154 | print centroid_pairs 155 | # now we have a list of paired up cluster indices. Cool. 156 | """ 157 | 158 | # Just so we're clear, we're rebuilding the structure of song1 with segments from song2 159 | 160 | 161 | # prepare song clusters, 162 | segclusters = [audio.AudioQuantumList()]*len(centroids) 163 | for s in range(0,len(idx)): 164 | segment = song.analysis.segments[s] 165 | cluster = idx[s] 166 | segment.numpytimbre = array(segment.timbre) 167 | segclusters[cluster].append(segment) 168 | 169 | 170 | 171 | # for each segment1 in song1, find the timbrely closest segment2 in song2 belonging to the cluster2 with which segment1's cluster1 is paired. 172 | for s in range(0,len(idx)): 173 | segment1 = song.analysis.segments[s] 174 | reference_data = song[segment1] 175 | cluster1 = idx[s] 176 | 177 | segment_data_list = [] 178 | 179 | for cluster in range(0,num_clusters): 180 | if(cluster==cluster1): 181 | continue # skip the reference cluster 182 | if(best_match>0): 183 | # slower, less varied version. Good for b's which are percussion loops 184 | 185 | """ 186 | # there's already a function for this, use that instead: timbre_distance_from 187 | timbre1 = array(segment1.timbre) 188 | min_distance = [9999999999999,0] 189 | for seg in segclusters2[cluster2]: 190 | timbre2 = seg.numpytimbre 191 | euclidian_distance = norm(timbre2-timbre1) 192 | if euclidian_distance < min_distance[0]: 193 | min_distance = [euclidian_distance, seg] 194 | bestmatchsegment2 = min_distance[1] 195 | # we found the segment2 in song2 that best matches segment1 196 | """ 197 | 198 | bestmatches = segclusters[cluster].ordered_by(timbre_distance_from(segment1)) 199 | 200 | if(best_match > 1): 201 | # if best_match > 1, it randomly grabs from the top best_matches. 202 | maxmatches = max(best_match, len(bestmatches)) 203 | bestmatchsegment = choice(bestmatches[0:maxmatches]) 204 | else: 205 | # if best_match == 1, it grabs the exact best match 206 | bestmatchsegment = bestmatches[0] 207 | else: 208 | # faster, more varied version, picks a random segment from that cluster. Good for sample salads. 209 | bestmatchsegment = choice(segclusters[cluster]) 210 | 211 | segment_data = song[bestmatchsegment] 212 | 213 | 214 | # what to do when segments lengths aren't equal? (almost always) 215 | # do we add silence? or do we stretch the samples? 216 | add_silence = True 217 | 218 | # This is the add silence solution: 219 | if add_silence: 220 | if reference_data.endindex > segment_data.endindex: 221 | # we need to add silence, because segment1 is longer 222 | if num_channels > 1: 223 | silence_shape = (reference_data.endindex,num_channels) 224 | else: 225 | silence_shape = (reference_data.endindex,) 226 | new_segment = audio.AudioData(shape=silence_shape, 227 | sampleRate=out.sampleRate, 228 | numChannels=segment_data.numChannels) 229 | new_segment.append(segment_data) 230 | new_segment.endindex = len(new_segment) 231 | segment_data = new_segment 232 | elif reference_data.endindex < segment_data.endindex: 233 | # we need to cut segment2 shorter, because segment2 is shorter 234 | index = slice(0, int(reference_data.endindex), 1) 235 | segment_data = audio.AudioData(None, segment_data.data[index], sampleRate=segment_data.sampleRate) 236 | else: 237 | # TODO: stretch samples to fit. 238 | # haven't written this part yet. 239 | segment_data = segment_data 240 | 241 | 242 | segment_data_list.append(segment_data) 243 | 244 | # mix the original and the remix 245 | #mixed_data = audio.mix(segment_data,reference_data,mix=mix) 246 | mixed_data = audio.megamix(segment_data_list) 247 | out.append(mixed_data) 248 | 249 | # redner output 250 | out.encode(outputFilename) 251 | -------------------------------------------------------------------------------- /dadabots_old/remix-scripts/qup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf=8 3 | 4 | """ 5 | qup.py 6 | 7 | Turns any song into drum'n'bass. 8 | Why qup? Because we're turning music production on its head. 9 | 10 | CJ Carr (Cortexelus James) 11 | Hack2LAUNCH 4/12/2013 12 | """ 13 | import copy 14 | import random 15 | import math 16 | import echonest.audio as audio 17 | import echonest.modify as modify 18 | st = modify.Modify() 19 | from echonest.sorting import * 20 | from echonest.selection import * 21 | import pyechonest.config as config 22 | config.MP3_BITRATE = 192 23 | 24 | import sys 25 | from numpy import vstack,array 26 | from numpy.random import rand 27 | from numpy.linalg import norm 28 | from scipy.cluster.vq import kmeans,vq 29 | from random import choice 30 | 31 | # take an input song 32 | input_filename = "mp3/vaetxh-unfolding.mp3"; 33 | output_filename = "mp3/qup-creation.mp3"; 34 | 35 | input_filename = sys.argv[1] 36 | output_filename = sys.argv[2] 37 | 38 | song = audio.LocalAudioFile(input_filename) 39 | 40 | # set 41 | sample_rate = song.sampleRate 42 | num_channels = song.numChannels 43 | out_shape = list(song.data.shape) 44 | out_shape[0] = 2 45 | out = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 46 | 47 | secs = song.analysis.sections 48 | num_sections = len(secs) 49 | ### ZEPTO -> DNB -> ZEPTO -> DNB ?? 50 | 51 | 52 | def loudness(section): 53 | segs = song.analysis.segments.that(overlap(section)) 54 | num_segs = len(segs) 55 | loudness_total = 0 56 | for seg in segs: 57 | loudness_total += seg.loudness_max 58 | avg_loudness = loudness_total / num_segs 59 | return avg_loudness 60 | 61 | 62 | def tempo_warp(section, bpm): 63 | print "tempo_warp" 64 | new_beat_duration = 60.0/bpm 65 | beats = song.analysis.beats.that(are_contained_by(section)) 66 | 67 | new_beats = [] 68 | for beat in beats: 69 | ratio = beat.duration / new_beat_duration 70 | new_beat = st.shiftTempo(song[beat], ratio) 71 | new_beats.append(new_beat) 72 | out = audio.assemble(new_beats) 73 | return out 74 | 75 | 76 | #dnbify(song.analysis.sections[0]) 77 | 78 | 79 | 80 | def beatrepeat(section): 81 | print "original with beat repeat" 82 | 83 | beats = song.analysis.beats.that(are_contained_by(section)) 84 | tatums = song.analysis.beats.that(are_contained_by(section)) 85 | br = audio.AudioQuantumList() 86 | 87 | for _ in range(2): 88 | br.append(song[beats[0]]) 89 | br.append(song[beats[1]]) 90 | br.append(song[beats[2]]) 91 | br.append(song[beats[3]]) 92 | for _ in range(2): 93 | br.append(song[beats[0]]) 94 | br.append(song[beats[1]]) 95 | for _ in range(2): 96 | br.append(song[beats[0]]) 97 | for _ in range(2): 98 | br.append(song[tatums[0]]) 99 | 100 | return br 101 | 102 | 103 | def beatrepeat_and_tempo_warp(section, bpm): 104 | print "beatrepeat_and_tempo_warp" 105 | beats = song.analysis.beats.that(are_contained_by(section)) 106 | tatums = song.analysis.beats.that(are_contained_by(section)) 107 | br = audio.AudioQuantumList() 108 | 109 | new_beat_duration = 60.0/bpm 110 | beats = song.analysis.beats.that(are_contained_by(section)) 111 | 112 | new_beats = [] 113 | for beat in beats: 114 | ratio = beat.duration / new_beat_duration 115 | new_beat = st.shiftTempo(song[beat], ratio) 116 | new_beats.append(new_beat) 117 | out = audio.assemble(new_beats) 118 | return out 119 | 120 | 121 | for _ in range(2): 122 | br.append(song[beats[-4]]) 123 | br.append(song[beats[-3]]) 124 | br.append(song[beats[-2]]) 125 | br.append(song[beats[-1]]) 126 | 127 | 128 | 129 | 130 | """ 131 | shorter_beat = st.shiftTempo(song[beats[0]], 2) 132 | for _ in range(8): 133 | more_beat_repeat.append(shorter_beat) 134 | shorter_beat = st.shiftTempo(song[beats[0]], 4) 135 | for _ in range(8): 136 | more_beat_repeat.append(shorter_beat) 137 | shorter_beat = st.shiftTempo(song[beats[0]], 8) 138 | for _ in range(16): 139 | more_beat_repeat.append(shorter_beat) 140 | assembled_beat_repeat = audio.assemble(more_beat_repeat) 141 | """ 142 | 143 | 144 | #return br 145 | 146 | import shutil 147 | 148 | # dnbify 149 | def dnbify(randombeat): 150 | print "dnbify" 151 | 152 | dnbfile = "mp3/breaks/RC4_Breakbeat_175 (%i).mp3" % randombeat 153 | dnbloop = audio.LocalAudioFile(dnbfile) 154 | 155 | # how many different groups will we cluster our data into? 156 | num_clusters = 5 157 | 158 | mix = 1.0 159 | 160 | dnbouts = [] 161 | for layer in range(0, 2): 162 | # best_match = 1 # slower, less varied version. Good for b's which are percussion loops 163 | # best_match = 0 # faster, more varied version, picks a random segment from that cluster. Good for b's which are sample salads. 164 | best_match = layer 165 | print "layer" 166 | print layer 167 | 168 | song1 = dnbloop 169 | song2 = song 170 | 171 | dnbout = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 172 | 173 | # here we just grab the segments that overlap the section 174 | sectionsegments = song1.analysis.segments 175 | #for _ in range(3): 176 | # sectionsegments.extend(song1.analysis.segments) 177 | sectionsegments2 = song2.analysis.segments #.that(overlap(section)); 178 | 179 | 180 | # this is just too easy 181 | # song.analysis.segments.timbre is a list of all 12-valued timbre vectors. 182 | # must be converted to a numpy.array() so that kmeans(data, n) is happy 183 | data = array(sectionsegments.timbre) 184 | data2 = array(sectionsegments2.timbre) 185 | 186 | """ 187 | # grab timbre data 188 | # must be converted to a numpy.array() so that kmeans(data, n) is happy 189 | data = array(song1.analysis.segments.timbre) 190 | data2 = array(song2.analysis.segments.timbre) 191 | """ 192 | 193 | 194 | # computing K-Means with k = num_clusters 195 | centroids,_ = kmeans(data,num_clusters) 196 | centroids2,_ = kmeans(data2,num_clusters) 197 | # assign each sample to a cluster 198 | idx,_ = vq(data,centroids) 199 | idx2,_ = vq(data2,centroids2) 200 | 201 | collection = [] 202 | for c in range(0, num_clusters): 203 | ccount = 0 204 | for i in idx: 205 | if i==c: 206 | ccount += 1 207 | collection.append([ccount, c]) 208 | collection.sort() 209 | # list of cluster indices from largest to smallest 210 | 211 | centroid_pairs = [] 212 | for _,c in collection: 213 | centroid1 = array(centroids[c]) 214 | min_distance = [9999999999,0] 215 | for ci in range(0,len(centroids2)): 216 | if ci in [li[1] for li in centroid_pairs]: 217 | continue 218 | centroid2 = array(centroids2[ci]) 219 | euclidian_distance = norm(centroid1-centroid2) 220 | if euclidian_distance < min_distance[0]: 221 | min_distance = [euclidian_distance, ci] 222 | centroid_pairs.append([c,min_distance[1]]) 223 | 224 | print centroid_pairs 225 | # now we have a list of paired up cluster indices. Cool. 226 | 227 | # Just so we're clear, we're rebuilding the structure of song1 with segments from song2 228 | 229 | # prepare song2 clusters, 230 | segclusters2 = [audio.AudioQuantumList()]*len(centroids2) 231 | for s2 in range(0,len(idx2)): 232 | segment2 = song2.analysis.segments[s2] 233 | cluster2 = idx2[s2] 234 | segment2.numpytimbre = array(segment2.timbre) 235 | segclusters2[cluster2].append(segment2) 236 | 237 | 238 | # for each segment1 in song1, find the timbrely closest segment2 in song2 belonging to the cluster2 with which segment1's cluster1 is paired. 239 | for s in range(0,len(idx)): 240 | segment1 = song1.analysis.segments[s] 241 | cluster1 = idx[s] 242 | cluster2 = [li[1] for li in centroid_pairs if li[0]==cluster1][0] 243 | 244 | if(best_match>0): 245 | # slower, less varied version. Good for b's which are percussion loops 246 | 247 | """ 248 | # there's already a function for this, use that instead: timbre_distance_from 249 | timbre1 = array(segment1.timbre) 250 | min_distance = [9999999999999,0] 251 | for seg in segclusters2[cluster2]: 252 | timbre2 = seg.numpytimbre 253 | euclidian_distance = norm(timbre2-timbre1) 254 | if euclidian_distance < min_distance[0]: 255 | min_distance = [euclidian_distance, seg] 256 | bestmatchsegment2 = min_distance[1] 257 | # we found the segment2 in song2 that best matches segment1 258 | """ 259 | 260 | bestmatches = segclusters2[cluster2].ordered_by(timbre_distance_from(segment1)) 261 | 262 | if(best_match > 1): 263 | # if best_match > 1, it randomly grabs from the top best_matches. 264 | maxmatches = max(best_match, len(bestmatches)) 265 | bestmatchsegment2 = choice(bestmatches[0:maxmatches]) 266 | else: 267 | # if best_match == 1, it grabs the exact best match 268 | bestmatchsegment2 = bestmatches[0] 269 | else: 270 | # faster, more varied version, picks a random segment from that cluster. Good for sample salads. 271 | bestmatchsegment2 = choice(segclusters2[cluster2]) 272 | 273 | reference_data = song1[segment1] 274 | segment_data = song2[bestmatchsegment2] 275 | 276 | # what to do when segments lengths aren't equal? (almost always) 277 | # do we add silence? or do we stretch the samples? 278 | add_silence = True 279 | 280 | # This is the add silence solution: 281 | if add_silence: 282 | if reference_data.endindex > segment_data.endindex: 283 | # we need to add silence, because segment1 is longer 284 | if num_channels > 1: 285 | silence_shape = (reference_data.endindex,num_channels) 286 | else: 287 | silence_shape = (reference_data.endindex,) 288 | new_segment = audio.AudioData(shape=silence_shape, 289 | sampleRate=out.sampleRate, 290 | numChannels=segment_data.numChannels) 291 | new_segment.append(segment_data) 292 | new_segment.endindex = len(new_segment) 293 | segment_data = new_segment 294 | elif reference_data.endindex < segment_data.endindex: 295 | # we need to cut segment2 shorter, because segment2 is shorter 296 | index = slice(0, int(reference_data.endindex), 1) 297 | segment_data = audio.AudioData(None, segment_data.data[index], sampleRate=segment_data.sampleRate) 298 | else: 299 | # TODO: stretch samples to fit. 300 | # haven't written this part yet. 301 | segment_data = segment_data 302 | 303 | # mix the original and the remix 304 | mixed_data = audio.mix(segment_data,reference_data,mix=mix) 305 | dnbout.append(mixed_data) 306 | 307 | dnbouts.append(dnbout) 308 | 309 | print "YEA" 310 | mixed_dnbouts = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 311 | print len(dnbouts[0]) 312 | print len(dnbouts[1]) 313 | #for s in range(0,len(dnbouts[0])): 314 | # print s 315 | # print dnbouts[0] 316 | # print dnbouts[1] 317 | mixed_data = audio.mix(dnbouts[0], dnbouts[1], 0.5) 318 | mixed_dnbouts.append(mixed_data) 319 | print "woah" 320 | 321 | dnbrepeatout = audio.AudioData(shape=out_shape, sampleRate=sample_rate,numChannels=num_channels) 322 | for _ in range(4): 323 | dnbrepeatout.append(mixed_dnbouts) 324 | print "oh okay" 325 | return dnbrepeatout 326 | 327 | 328 | # zeptoify 329 | # creates a buildup 330 | # basically orders segments with high timbre[6] by length 331 | def zepto(length_seconds): 332 | print "zeptoify" 333 | 334 | section = False 335 | if section==False: 336 | total_duration = song.analysis.duration 337 | segments = song.analysis.segments 338 | else: 339 | total_duration = section.duration 340 | #order by length) 341 | segments = song.analysis.segments.that(are_contained_by(section)) 342 | 343 | length_order = segments.ordered_by(duration) 344 | # grab the one with the highest timbre[6] value from every 4 segment 345 | i = 0 346 | 347 | length = len(segments) 348 | unused_segs = audio.AudioQuantumList() 349 | while total_duration > length_seconds: 350 | print_seg_durations(length_order) 351 | 352 | sorted_segs = audio.AudioQuantumList() 353 | 354 | while i < length: 355 | j = 0 356 | four_segs = audio.AudioQuantumList() 357 | # append the next four segments 358 | while j < 4: 359 | if(j+i < length): 360 | four_segs.append(length_order[j + i]) 361 | j += 1 362 | else: 363 | break 364 | # order the four segments by timbre value 6 365 | timbre_segs = four_segs.ordered_by(timbre_value(6)) 366 | # Remove the worst candidate while the total time is less than 30secs 367 | for k in range(0, j-1): 368 | sorted_segs.append(timbre_segs[k]) 369 | unused_segs.append(timbre_segs[j-1]) 370 | 371 | deduction = timbre_segs[j-1].duration 372 | total_duration = total_duration - deduction 373 | if total_duration < length_seconds: 374 | sorted_segs.extend(length_order[i:]) 375 | break 376 | i = i + 4 377 | length_order = copy.copy(sorted_segs) 378 | length = len(length_order) 379 | print "I think the total duration is " + str(total_duration) 380 | print "However the toal duration is actually " + str(get_total_duration(length_order)) 381 | i = 0 382 | fixed_order = length_order.ordered_by(duration) 383 | fixed_order.reverse() 384 | 385 | #print_seg_durations(fixed_order) 386 | print "total duration: " + str(total_duration) 387 | #return [fixed_order, unused_segs] 388 | return fixed_order.render() 389 | 390 | def get_total_duration(segment_list): 391 | total_dur = 0 392 | for seg in segment_list: 393 | total_dur += seg.duration 394 | return total_dur 395 | 396 | def print_seg_durations(segments): 397 | string0 = "" 398 | for s in segments: 399 | string0 += str(s.duration) + ", " 400 | print string0 401 | 402 | 403 | 404 | 405 | def longestsample(): 406 | length_order = song.analysis.segments.ordered_by(duration) 407 | return length_order[-1].render() 408 | 409 | def original(section): 410 | print "original" 411 | 412 | # combine 413 | 414 | #itsalive = zepto(30) 415 | 416 | for n in range(0,10): 417 | 418 | randombeat = random.randrange(17,86) 419 | itsalive = dnbify(randombeat) 420 | itsalive.encode(output_filename + "." + str(n) + "." + str(randombeat) + ".mp3") 421 | 422 | #ITSALIVE = zepto(song.analysis, 40) 423 | #ITSALIVE.encode(output_filename) 424 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Dadabot_Autochiptune.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "", 4 | "signature": "sha256:459bc68da517eaff8fe1cfacc53d6a10da4d1486f86ea49f442f2c2377db0a9d" 5 | }, 6 | "nbformat": 3, 7 | "nbformat_minor": 0, 8 | "worksheets": [ 9 | { 10 | "cells": [ 11 | { 12 | "cell_type": "code", 13 | "collapsed": false, 14 | "input": [], 15 | "language": "python", 16 | "metadata": {}, 17 | "outputs": [], 18 | "prompt_number": 0 19 | }, 20 | { 21 | "cell_type": "code", 22 | "collapsed": false, 23 | "input": [ 24 | "#!/usr/bin/env python\n", 25 | "# -*- encoding: utf-8 -*-\n", 26 | "\n", 27 | "# ### Algorithm:\n", 28 | "# 1. HPSS => Harmonics, Percussives\n", 29 | "# 1. Percussives => peak pick => noise generator\n", 30 | "# 1. Harmonics => CQT\n", 31 | "# 1. CQT => Bass range => peak pick => triangle generator\n", 32 | "# 1. CQT => Treble range => peak pick => harmony => pulse generator\n", 33 | "\n", 34 | "import argparse\n", 35 | "import sys\n", 36 | "import os\n", 37 | "import time\n", 38 | "\n", 39 | "import librosa\n", 40 | "import numpy as np\n", 41 | "import scipy.signal\n", 42 | "import scipy.ndimage\n", 43 | "import functools\n", 44 | "\n", 45 | "import warnings\n", 46 | "warnings.filterwarnings(\"ignore\")\n", 47 | "\n", 48 | "# MAGIC NUMBERS\n", 49 | "sr = 22050\n", 50 | "MIDI_MIN = 18\n", 51 | "MIDI_MAX = 96\n", 52 | "fmin = librosa.midi_to_hz(MIDI_MIN)\n", 53 | "n_fft = 2048\n", 54 | "hop_length = 512\n", 55 | "\n", 56 | "TREBLE_MIN = 54 - MIDI_MIN\n", 57 | "TREBLE_MAX = MIDI_MAX - MIDI_MIN\n", 58 | "BASS_MIN = 24 - MIDI_MIN\n", 59 | "BASS_MAX = TREBLE_MIN + 24\n", 60 | "\n", 61 | "\n", 62 | "def triangle(*args, **kwargs):\n", 63 | " '''Synthesize a triangle wave'''\n", 64 | " v = scipy.signal.sawtooth(*args, **kwargs)\n", 65 | "\n", 66 | " return 2 * np.abs(v) - 1.\n", 67 | "\n", 68 | "\n", 69 | "def nes_triangle(*args, **kwargs):\n", 70 | " '''Synthesize a quantized NES triangle'''\n", 71 | "\n", 72 | " # http://wiki.nesdev.com/w/index.php/APU_Triangle\n", 73 | " # NES triangle is quantized to 16 values\n", 74 | " w = triangle(*args, **kwargs)\n", 75 | "\n", 76 | " qw = w - np.mod(w, 2./15)\n", 77 | "\n", 78 | " return qw\n", 79 | "\n", 80 | "\n", 81 | "def noise(seq):\n", 82 | " '''Synthesize binary noise'''\n", 83 | " v = np.random.randint(0, 2, size=(len(seq),))\n", 84 | "\n", 85 | " return 2 * v - 1.\n", 86 | "\n", 87 | "\n", 88 | "def quantize_values(X, v=15):\n", 89 | " '''Quantize values to at most v discrete values'''\n", 90 | "\n", 91 | " X = X - X.min()\n", 92 | " X = X / X.max()\n", 93 | " X = X - np.mod(X, 1./v)\n", 94 | " return X\n", 95 | "\n", 96 | "\n", 97 | "def synthesize(beats, piano_roll, fmin=0, bins_per_octave=12,\n", 98 | " tuning=0.0, wave=None, n=None):\n", 99 | " '''Synthesize a weighted piano roll'''\n", 100 | "\n", 101 | " # Quantize the piano roll\n", 102 | " sr = 22050\n", 103 | "\n", 104 | " piano_roll = quantize_values(piano_roll)\n", 105 | "\n", 106 | " if wave is None:\n", 107 | " wave = functools.partial(scipy.signal.square, duty=0.5)\n", 108 | "\n", 109 | " bins_per_semi = bins_per_octave/12\n", 110 | " first_bin = bins_per_semi/2\n", 111 | "\n", 112 | " frequencies = librosa.cqt_frequencies(n_bins=piano_roll.shape[0],\n", 113 | " fmin=fmin,\n", 114 | " bins_per_octave=bins_per_octave,\n", 115 | " tuning=tuning)\n", 116 | "\n", 117 | " beats -= beats[0]\n", 118 | "\n", 119 | " if n is None:\n", 120 | " n = beats[-1] + 0.5 * sr\n", 121 | "\n", 122 | " beats = librosa.util.fix_frames(beats, x_min=0, x_max=n)\n", 123 | " beat_intervals = librosa.util.frame(beats, frame_length=2, hop_length=1).T\n", 124 | "\n", 125 | " output = np.zeros(n)\n", 126 | "\n", 127 | " correction = 2.0 ** (tuning / bins_per_octave)\n", 128 | " stream = correction * 2.0 * np.pi * np.arange(len(output)) / sr\n", 129 | "\n", 130 | " active_bins = piano_roll.sum(axis=1) > 0\n", 131 | "\n", 132 | " for n, freq in enumerate(frequencies):\n", 133 | " if not active_bins[n * bins_per_semi + first_bin]:\n", 134 | " continue\n", 135 | "\n", 136 | " my_f = freq * stream\n", 137 | "\n", 138 | " sine = wave(my_f)\n", 139 | "\n", 140 | " # Align beat timings to zero crossings of sine\n", 141 | " zc_mask = librosa.zero_crossings(sine)\n", 142 | "\n", 143 | " beat_f = match_zc(beat_intervals, zc_mask, freq * correction, sr)\n", 144 | "\n", 145 | " # Mask out this frequency wherever it's inactive\n", 146 | " for m, (start, end) in enumerate(beat_f):\n", 147 | " sine[start:end] *= piano_roll[n*bins_per_semi + first_bin, m]\n", 148 | "\n", 149 | " output += sine\n", 150 | "\n", 151 | " output = librosa.util.normalize(output)\n", 152 | " return output, sr\n", 153 | "\n", 154 | "\n", 155 | "def match_zc(queries, zc_mask, my_f, sr):\n", 156 | "\n", 157 | " # For each query, bound define a search range\n", 158 | " window = int(np.ceil(sr / my_f))\n", 159 | "\n", 160 | " output = np.empty(queries.size, dtype=int)\n", 161 | "\n", 162 | " for i, q in enumerate(queries.ravel()):\n", 163 | " s = np.maximum(0, q - window)\n", 164 | " t = np.minimum(len(zc_mask), q + window)\n", 165 | "\n", 166 | " vals = s + np.flatnonzero(zc_mask[s:t])\n", 167 | " output[i] = vals[np.argmin(np.abs(q - vals))]\n", 168 | "\n", 169 | " return output.reshape(queries.shape)\n", 170 | "\n", 171 | "\n", 172 | "def peakgram(C, max_peaks=1, note_search=8):\n", 173 | " '''Compute spectrogram column-wise peaks subject to constraints'''\n", 174 | "\n", 175 | " mask = np.zeros_like(C)\n", 176 | "\n", 177 | " for t in range(C.shape[1]):\n", 178 | " if t == 0 or not np.any(mask[:, t-1]):\n", 179 | " col = C[:, t]\n", 180 | " else:\n", 181 | " col = np.min(C[:, t]) * np.ones(C.shape[0])\n", 182 | "\n", 183 | " # Find peaks in the previous column\n", 184 | " # zero out anything outside of +- note_search from a peak\n", 185 | " for v in np.argwhere(mask[:, t-1]):\n", 186 | " r_min = max(0, v-note_search)\n", 187 | " r_max = min(col.shape[0], v+note_search+1)\n", 188 | " col[r_min:r_max] = C[r_min:r_max, t]\n", 189 | "\n", 190 | " # Local normalization\n", 191 | " z = col.max()\n", 192 | " if z > 0:\n", 193 | " col = col / z\n", 194 | "\n", 195 | " # Don't look for 2nds or 11ths\n", 196 | " # Compute max over an octave range, +- 3 semitones\n", 197 | " peaks = librosa.util.peak_pick(col, 3, 3, 6, 6, 1e-2, 3)\n", 198 | "\n", 199 | " if len(peaks) == 0:\n", 200 | " continue\n", 201 | "\n", 202 | " # Order the peaks by loudness\n", 203 | " idx = np.argsort(col[peaks])[::-1]\n", 204 | " peaks = peaks[idx]\n", 205 | "\n", 206 | " # Clip to max_peaks\n", 207 | " peaks = peaks[:min(len(peaks), max_peaks)]\n", 208 | "\n", 209 | " # If there are any peaks, pick them out\n", 210 | " mask[peaks, t] = 1\n", 211 | "\n", 212 | " return mask\n", 213 | "\n", 214 | "\n", 215 | "def dft_normalize(c):\n", 216 | "\n", 217 | " D = np.fft.rfft(c, axis=0)\n", 218 | " D = D / (1e-8 + np.mean(np.abs(D)**2, axis=1, keepdims=True)**0.5)\n", 219 | " cinv = np.fft.irfft(D, axis=0)\n", 220 | " return np.clip(cinv, 0, None)\n", 221 | "\n", 222 | "\n", 223 | "def process_audio(y):\n", 224 | " '''load the audio, do feature extraction'''\n", 225 | "\n", 226 | "\n", 227 | " # Get the harmonic and percussive components\n", 228 | " y_harm, y_perc = librosa.effects.hpss(y)\n", 229 | "\n", 230 | " # compute CQT\n", 231 | " cq = librosa.cqt(y_harm, sr, fmin=fmin, n_bins=MIDI_MAX-MIDI_MIN, hop_length=hop_length)\n", 232 | "\n", 233 | " cq = dft_normalize(cq)\n", 234 | "\n", 235 | " \"\"\"\n", 236 | " # Trim to match cq and P shape\n", 237 | " P = (librosa.feature.rmse(y=y_perc, hop_length=hop_length)\n", 238 | " / librosa.feature.rmse(y=y, hop_length=hop_length))\n", 239 | "\n", 240 | " P[~np.isfinite(P)] = 0.0\n", 241 | " \"\"\"\n", 242 | " duration = cq.shape[-1]\n", 243 | " # P = librosa.util.fix_length(P, duration, axis=-1)\n", 244 | " cq = librosa.util.fix_length(cq, duration, axis=-1)\n", 245 | "\n", 246 | " return y, cq, y_perc\n", 247 | "\n", 248 | "\n", 249 | "def get_wav(cq, nmin=60, nmax=120, width=5, max_peaks=1, wave=None, n=None):\n", 250 | "\n", 251 | " # Slice down to the bass range\n", 252 | " cq = cq[nmin:nmax]\n", 253 | "\n", 254 | " # Pick peaks at each time\n", 255 | " mask = peakgram(librosa.logamplitude(cq**2, top_db=60, ref_power=np.max),\n", 256 | " max_peaks=max_peaks)\n", 257 | "\n", 258 | " # Smooth in time\n", 259 | " mask = scipy.ndimage.median_filter(mask,\n", 260 | " size=(1, width),\n", 261 | " mode='mirror')\n", 262 | "\n", 263 | " # resynthesize with some magnitude compression\n", 264 | " wav = synthesize(librosa.frames_to_samples(np.arange(cq.shape[-1]),\n", 265 | " hop_length=hop_length),\n", 266 | " mask * cq**(1./3),\n", 267 | " fmin=librosa.midi_to_hz(nmin + MIDI_MIN),\n", 268 | " bins_per_octave=12,\n", 269 | " wave=wave,\n", 270 | " n=n)[0]\n", 271 | "\n", 272 | " return wav\n", 273 | "\n", 274 | "\n", 275 | "def get_drum_wav(percussion, width=5, n=None):\n", 276 | "\n", 277 | " # Compute volume shaper\n", 278 | " percussion = librosa.util.normalize(percussion.ravel())\n", 279 | "\n", 280 | " v = scipy.ndimage.median_filter(percussion,\n", 281 | " width,\n", 282 | " mode='mirror')\n", 283 | " v = np.atleast_2d(v)\n", 284 | "\n", 285 | " wav = synthesize(librosa.frames_to_samples(np.arange(v.shape[-1]),\n", 286 | " hop_length=hop_length),\n", 287 | " v,\n", 288 | " fmin=librosa.midi_to_hz(0),\n", 289 | " bins_per_octave=12,\n", 290 | " wave=noise,\n", 291 | " n=n)[0]\n", 292 | "\n", 293 | " return wav\n", 294 | "\n", 295 | "\n", 296 | "def process_arguments(args):\n", 297 | "\n", 298 | " parser = argparse.ArgumentParser(description='Auto Chip Tune')\n", 299 | "\n", 300 | " parser.add_argument('input_file',\n", 301 | " action='store',\n", 302 | " help='Path to the input audio file')\n", 303 | "\n", 304 | " parser.add_argument('output_file',\n", 305 | " action='store',\n", 306 | " help='Path to store the generated chiptune')\n", 307 | "\n", 308 | " parser.add_argument('-s', '--stereo',\n", 309 | " action='store_true',\n", 310 | " default=False,\n", 311 | " help='Mix original and synthesized tracks in stereo')\n", 312 | "\n", 313 | " return vars(parser.parse_args(args))" 314 | ], 315 | "language": "python", 316 | "metadata": {}, 317 | "outputs": [], 318 | "prompt_number": 1 319 | }, 320 | { 321 | "cell_type": "code", 322 | "collapsed": false, 323 | "input": [ 324 | "'''Robust PCA in python.'''\n", 325 | "# CREATED:2013-04-29 08:50:44 by Brian McFee \n", 326 | "# \n", 327 | "import numpy as np\n", 328 | "import scipy\n", 329 | "import scipy.linalg\n", 330 | "import scipy.weave\n", 331 | "\n", 332 | "def nuclear_prox(A, r=1.0):\n", 333 | " '''Proximal operator for scaled nuclear norm:\n", 334 | " Y* <- argmin_Y r * ||Y||_* + 1/2 * ||Y - A||_F^2\n", 335 | " Arguments:\n", 336 | " A -- (ndarray) input matrix\n", 337 | " r -- (float>0) scaling factor\n", 338 | " Returns:\n", 339 | " Y -- (ndarray) if A = USV', then Y = UTV'\n", 340 | " where T = max(S - r, 0)\n", 341 | " '''\n", 342 | " \n", 343 | " U, S, V = scipy.linalg.svd(A, full_matrices=False)\n", 344 | " T = np.maximum(S - r, 0.0)\n", 345 | " Y = (U * T).dot(V)\n", 346 | " return Y\n", 347 | "\n", 348 | "def l1_prox(A, r=1.0, nonneg=False):\n", 349 | " '''Proximal operator for entry-wise matrix l1 norm:\n", 350 | " Y* <- argmin_Y r * ||Y||_1 + 1/2 * ||Y - A||_F^2\n", 351 | " Arguments:\n", 352 | " Arguments:\n", 353 | " A -- (ndarray) input matrix\n", 354 | " r -- (float>0) scaling factor\n", 355 | " nonneg -- (bool) retain only the non-negative portion\n", 356 | " Returns:\n", 357 | " Y -- (ndarray) Y = A after shrinkage\n", 358 | " '''\n", 359 | " \n", 360 | " Y = np.zeros_like(A)\n", 361 | " \n", 362 | " numel = A.size\n", 363 | " \n", 364 | " shrinkage = r\"\"\"\n", 365 | " int NN = (int)nonneg;\n", 366 | " for (int i = 0; i < numel; i++) {\n", 367 | " Y[i] = 0;\n", 368 | " if (A[i] - r > 0) {\n", 369 | " Y[i] = A[i] - r;\n", 370 | " } else if (!NN && (A[i] + r <= 0)) {\n", 371 | " Y[i] = A[i] + r;\n", 372 | " }\n", 373 | " }\n", 374 | " \"\"\"\n", 375 | " \n", 376 | " scipy.weave.inline(shrinkage, ['numel', 'A', 'r', 'Y', 'nonneg'])\n", 377 | " return Y\n", 378 | "\n", 379 | "def robust_pca_cost(Y, Z, alpha):\n", 380 | " '''Get the cost of an RPCA solution.\n", 381 | " Arguments:\n", 382 | " Y -- (ndarray) the low-rank component\n", 383 | " Z -- (ndarray) the sparse component\n", 384 | " alpha -- (float>0) the balancing factor\n", 385 | " Returns:\n", 386 | " total, nuclear_norm, l1_norm -- (list of floats)\n", 387 | " '''\n", 388 | " nuclear_norm = scipy.linalg.svd(Y, full_matrices=False, compute_uv=False).sum()\n", 389 | " \n", 390 | " l1_norm = np.abs(Z).sum()\n", 391 | " \n", 392 | " return nuclear_norm + alpha * l1_norm, nuclear_norm, l1_norm\n", 393 | "\n", 394 | "\n", 395 | "def robust_pca(X, alpha=None, max_iter=100, verbose=False, nonneg=False):\n", 396 | " '''ADMM solver for robust PCA.\n", 397 | " min_Y ||Y||_* + alpha * ||X-Y||_1\n", 398 | " Arguments:\n", 399 | " X -- (ndarray) input data (d-by-n)\n", 400 | " alpha -- (float>0) weight of the l1 penalty\n", 401 | " if unspecified, defaults to 1.0 / sqrt(max(d, n))\n", 402 | " nonneg -- (bool) constrain to non-negative noise\n", 403 | " Returns:\n", 404 | " Y -- (ndarray) low-rank component of X\n", 405 | " Z -- (ndarray) sparse component of X\n", 406 | " diags -- (dict) diagnostic output\n", 407 | " '''\n", 408 | " \n", 409 | " RHO_MIN = 1e-1\n", 410 | " RHO_MAX = 1e6\n", 411 | " MAX_RATIO = 1e1\n", 412 | " SCALE_FACTOR = 3.0e0\n", 413 | " ABS_TOL = 1e-4\n", 414 | " REL_TOL = 1e-3\n", 415 | " \n", 416 | " # update rules:\n", 417 | " # Y+ <- nuclear_prox(X - Z - W, 1/rho)\n", 418 | " # Z+ <- l1_prox(X - Y - W, alpha/rho)\n", 419 | " # W+ <- W + Y + Z - X\n", 420 | " \n", 421 | " # Initialize\n", 422 | " rho = RHO_MIN\n", 423 | " \n", 424 | " Y = X.copy()\n", 425 | " Z = np.zeros_like(X)\n", 426 | " W = np.zeros_like(X)\n", 427 | " \n", 428 | " norm_X = scipy.linalg.norm(X)\n", 429 | " \n", 430 | " if alpha is None:\n", 431 | " alpha = max(X.shape)**(-0.5)\n", 432 | "\n", 433 | " m = X.size\n", 434 | "\n", 435 | " _DIAG = {\n", 436 | " 'err_primal': [],\n", 437 | " 'err_dual': [],\n", 438 | " 'eps_primal': [],\n", 439 | " 'eps_dual': [],\n", 440 | " 'rho': []\n", 441 | " }\n", 442 | " \n", 443 | " for t in range(max_iter):\n", 444 | " Y = nuclear_prox(X - Z - W, 1.0/ rho)\n", 445 | " Z_old = Z.copy()\n", 446 | " Z = l1_prox(X - Y - W, alpha / rho, nonneg)\n", 447 | " \n", 448 | " if nonneg:\n", 449 | " Z = np.maximum(Z, X)\n", 450 | "\n", 451 | " residual_pri = Y + Z - X\n", 452 | " residual_dual = Z - Z_old\n", 453 | " \n", 454 | " res_norm_pri = scipy.linalg.norm(residual_pri)\n", 455 | " res_norm_dual = rho * scipy.linalg.norm(residual_dual)\n", 456 | " \n", 457 | " W = W + residual_pri\n", 458 | " \n", 459 | " eps_pri = np.sqrt(m) * ABS_TOL + REL_TOL * max(scipy.linalg.norm(Y), scipy.linalg.norm(Z), norm_X)\n", 460 | " eps_dual = np.sqrt(m) * ABS_TOL + REL_TOL * scipy.linalg.norm(W)\n", 461 | " \n", 462 | " _DIAG['eps_primal'].append(eps_pri)\n", 463 | " _DIAG['eps_dual' ].append(eps_dual)\n", 464 | " _DIAG['err_primal'].append(res_norm_pri)\n", 465 | " _DIAG['err_dual' ].append(res_norm_dual)\n", 466 | " _DIAG['rho' ].append(rho)\n", 467 | " \n", 468 | " if res_norm_pri <= eps_pri and res_norm_dual <= eps_dual:\n", 469 | " break\n", 470 | " \n", 471 | " if res_norm_pri > MAX_RATIO * res_norm_dual and rho * SCALE_FACTOR <= RHO_MAX:\n", 472 | " rho = rho * SCALE_FACTOR\n", 473 | " W = W / SCALE_FACTOR\n", 474 | " \n", 475 | " \n", 476 | " elif res_norm_dual > MAX_RATIO * res_norm_pri and rho / SCALE_FACTOR >= RHO_MIN:\n", 477 | " rho = rho / SCALE_FACTOR\n", 478 | " W = W * SCALE_FACTOR\n", 479 | " \n", 480 | " if verbose:\n", 481 | " if t < max_iter - 1:\n", 482 | " print 'Converged in %d steps' % t\n", 483 | " else:\n", 484 | " print 'Reached maximum iterations'\n", 485 | " \n", 486 | " Y = X - Z\n", 487 | " _DIAG['cost'] = robust_pca_cost(Y, Z, alpha)\n", 488 | " \n", 489 | " return (Y, Z, _DIAG)" 490 | ], 491 | "language": "python", 492 | "metadata": {}, 493 | "outputs": [], 494 | "prompt_number": 2 495 | }, 496 | { 497 | "cell_type": "code", 498 | "collapsed": false, 499 | "input": [ 500 | "\n", 501 | "\n", 502 | "# From https://github.com/bmcfee/musichacks/blob/master/2013yyz/frankenmash/mangler.py\n", 503 | "# Robust PCA method of vocal removal\n", 504 | "\n", 505 | "def rpca_correct(X, L, S, p=0):\n", 506 | " \n", 507 | " # Recombobulate into an energy partition\n", 508 | " L = np.maximum(0.0, L)\n", 509 | " L = np.minimum(X, L)\n", 510 | " S = X - L\n", 511 | " \n", 512 | " # Wiener-filter to smooth out the edges\n", 513 | " if p > 0:\n", 514 | " zS = S == 0\n", 515 | " S = S ** p\n", 516 | " S[zS] = 0.0\n", 517 | " \n", 518 | " zL = L == 0\n", 519 | " L = L ** p\n", 520 | " L[zL] = 0.0\n", 521 | " \n", 522 | " L[zL & zS] = 0.5\n", 523 | " S[zL & zS] = 0.5\n", 524 | " \n", 525 | " Ml = L / (L + S)\n", 526 | " Ms = S / (L + S)\n", 527 | " \n", 528 | " return (X * Ml, X * Ms)\n", 529 | " else:\n", 530 | " return (L, S)\n", 531 | "\n", 532 | " \n", 533 | "def remove_vocals(y):\n", 534 | " \n", 535 | " # Step 1: compute STFT\n", 536 | " D = librosa.stft(y, n_fft=n_fft, hop_length=hop_length).astype(np.complex64)\n", 537 | " \n", 538 | " # Step 2: separate magnitude and phase\n", 539 | " S, P = librosa.magphase(D)\n", 540 | " S = S / S.max()\n", 541 | " \n", 542 | " tau = (D.shape[0] * 3) / 4\n", 543 | "\n", 544 | " \n", 545 | " # Step 3: RPCA to separate voice and background\n", 546 | " S1, S2, _ = robust_pca(S[:tau,:], max_iter=25)\n", 547 | " S1, S2 = rpca_correct(S[:tau,:], S1, S2)\n", 548 | "\n", 549 | " S1 = np.vstack((S1, S[tau:,:]))\n", 550 | " \n", 551 | " del D\n", 552 | " del S\n", 553 | " del S2\n", 554 | " # Step 4: recombine with phase, return vocals\n", 555 | " return S1 * P\n" 556 | ], 557 | "language": "python", 558 | "metadata": {}, 559 | "outputs": [], 560 | "prompt_number": 3 561 | }, 562 | { 563 | "cell_type": "code", 564 | "collapsed": false, 565 | "input": [ 566 | "def autochip(input_file=None, output_file=None, stereo=False):\n", 567 | " #global y_treb, y_bass, y_perc, percussion\n", 568 | " \n", 569 | " print 'Processing {:s}'.format(os.path.basename(input_file))\n", 570 | " \n", 571 | " y, sr = librosa.load(input_file)\n", 572 | " \"\"\" TODO: remove vocals in percussion layer \n", 573 | " print \"remove vox\"\n", 574 | " y_novox = remove_vocals(y)\n", 575 | " print \"leny\"\n", 576 | " leny = len(y)\n", 577 | " print \"process audio\"\n", 578 | " y, cq, _ = process_audio(y) # include vocals in harmony\n", 579 | " _, _, y_perc = process_audio(y_novox) # build the percussion from the version without vocals\n", 580 | " del y\n", 581 | " \"\"\"\n", 582 | " leny = len(y)\n", 583 | " y, cq, y_perc = process_audio(y)\n", 584 | " del y\n", 585 | " \n", 586 | " print 'Synthesizing squares...'\n", 587 | " y_treb = get_wav(cq,\n", 588 | " nmin=MIDI_MIN,\n", 589 | " nmax=MIDI_MAX,\n", 590 | " max_peaks=20,\n", 591 | " n=leny)\n", 592 | "\n", 593 | " print 'Synthesizing triangles...'\n", 594 | " y_bass = get_wav(cq,\n", 595 | " nmin=MIDI_MIN,\n", 596 | " nmax=BASS_MAX,\n", 597 | " wave=nes_triangle,\n", 598 | " max_peaks=4,\n", 599 | " n=leny)\n", 600 | "\n", 601 | " del cq\n", 602 | " \n", 603 | " print 'Synthesizing drums...'\n", 604 | " #1 11325 5798016\n", 605 | " \n", 606 | " #y_drum = get_drum_wav(percussion, n=len(y))\n", 607 | " #y_drum = librosa.istft(percussion, hop_length, n_fft)\n", 608 | " #print len(y_bass), len(y_perc), y_perc.size\n", 609 | " \n", 610 | " \n", 611 | " \n", 612 | " bits = pow(2,2)\n", 613 | " bitcrush_ = np.vectorize(lambda x: round(x*bits)/bits) \n", 614 | " y_perc = bitcrush_(y_perc)\n", 615 | " \n", 616 | "\n", 617 | " print 'Mixing... '\n", 618 | " y_chip = librosa.util.normalize(0.5 * y_treb +\n", 619 | " 0.7 * y_bass +\n", 620 | " 0.8 * y_perc) # took the drum out\n", 621 | "\n", 622 | " del y_treb\n", 623 | " del y_bass\n", 624 | " del y_perc\n", 625 | " \n", 626 | " \"\"\"\n", 627 | " bitcrush = np.vectorize(lambda x, bits: floor(x*bits)/bits) \n", 628 | " \n", 629 | " y_chip = y_treb + y_bass\n", 630 | " del y_treb\n", 631 | " del y_bass\n", 632 | " y_chip = bitcrush(y_chip, pow(2,16))\n", 633 | " y_perc = bitcrush(y_perc,1.2)\n", 634 | " y_chip = (y_chip) + (0.3 * y_perc)\n", 635 | " \n", 636 | " del y_perc\n", 637 | " y_chip = librosa.util.normalize(y_chip)\n", 638 | " #y_chip = bitcrush(y_chip, pow(2,8))\n", 639 | " \n", 640 | " \"\"\"\n", 641 | " \n", 642 | " if stereo:\n", 643 | " y_out = np.vstack([librosa.util.normalize(y), y_chip])\n", 644 | " else:\n", 645 | " y_out = y_chip\n", 646 | "\n", 647 | " del y_chip \n", 648 | " \n", 649 | " librosa.output.write_wav(output_file, y_out, sr)\n", 650 | " del y_out\n", 651 | " print 'Done.'" 652 | ], 653 | "language": "python", 654 | "metadata": {}, 655 | "outputs": [], 656 | "prompt_number": 4 657 | }, 658 | { 659 | "cell_type": "code", 660 | "collapsed": false, 661 | "input": [ 662 | "#!/usr/bin/env python\n", 663 | "# encoding: utf=8\n", 664 | "\"\"\"\n", 665 | "offliberty gnabber\n", 666 | "downloads tracks from soundcloud, always 128k mp3\n", 667 | "\n", 668 | "cortexel.us 2012\n", 669 | "\"\"\"\n", 670 | "import urllib2, urllib, re, json\n", 671 | "\n", 672 | "usage = \"Offliberty Gnabber. Downloads tracks from soundcloud, youtube, etc.\\n\\\n", 673 | "Usage: offliberty.py url\\\n", 674 | "Example: offliberty.py http://soundcloud.com/chopshopshockshack/mt-analogue-you-know-what-time\"\n", 675 | "\n", 676 | "def gnab_download(url, file_name):\n", 677 | " print \"gnab download..\"\n", 678 | " url = url.replace(\"https\",\"http\")\n", 679 | " #print \"url: %s / filename: %s\" % (url, file_name)\n", 680 | " print \"opening url\", url\n", 681 | " u = urllib2.urlopen(url)\n", 682 | " #print u\n", 683 | " #print \"opening filename\", file_name\n", 684 | " f = open(file_name, 'wb')\n", 685 | " #print f\n", 686 | " meta = u.info()\n", 687 | " #print meta\n", 688 | " file_size = False\n", 689 | " if(meta.getheaders(\"Content-Length\")):\n", 690 | " file_size = int(meta.getheaders(\"Content-Length\")[0])\n", 691 | " #print file_size\n", 692 | " #print \"Downloading: %s \\nBytes: %s\" % (file_name, file_size)\n", 693 | "\n", 694 | " #if(file_size >= self.MAX_FILE_SIZE):\n", 695 | " # raise Exception(\"File size too big!! %i > %i \" % [file_size, self.MAX_FILE_SIZE])\n", 696 | " \n", 697 | " file_size_dl = 0\n", 698 | " block_sz = 8192\n", 699 | " while True:\n", 700 | " buffer = u.read(block_sz)\n", 701 | " if not buffer:\n", 702 | " break\n", 703 | "\n", 704 | " file_size_dl += len(buffer)\n", 705 | " f.write(buffer)\n", 706 | " if(file_size):\n", 707 | " status = r\"%10d [%3.2f%%]\" % (file_size_dl, file_size_dl * 100. / file_size)\n", 708 | " else:\n", 709 | " status = r\"%10d\" % (file_size_dl)\n", 710 | " status = status + chr(8)*(len(status)+1)\n", 711 | " #print status,\n", 712 | "\n", 713 | " print \"\\n\"\n", 714 | " f.close()\n", 715 | " \n", 716 | "#gnab_download('https://i1.sndcdn.com/avatars-000008456211-qo1al2-large.jpg', './dadabots/art/\u1d04\u042f\u0367tx\u013dz\\n.avatar.jpg')\n", 717 | "\n", 718 | "def gnabsong(url, filename):\n", 719 | " gnab_download(geturl(url), filename)\n", 720 | " \n", 721 | "# given url, grabs mp3 using offliberty\n", 722 | "def geturl(song_url):\n", 723 | " if \"soundcloud.com\" in song_url:\n", 724 | " return get_soundcloud_song(song_url)\n", 725 | " off_url = \"http://offliberty.com/off02.php\"\n", 726 | " req = urllib2.Request(off_url) \n", 727 | " #res = urllib2.urlopen(req)\n", 728 | " print sc_url \n", 729 | " req.add_header(\"User-agent\", \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36\")\n", 730 | " req.add_header(\"Referer\",\"http://offliberty.com/\")\n", 731 | "\n", 732 | " data = { 'track' : sc_url, 'refext' : \"\"} \n", 733 | " req.add_data(urllib.urlencode(data))\n", 734 | " res = urllib2.urlopen(req)\n", 735 | " \n", 736 | " offpage = res.read(4000)\n", 737 | " \n", 738 | " if(\"You can't use Offliberty so often\" in offpage):\n", 739 | " print \"Offliberty limit reached. . sleeping for one hour\"\n", 740 | " sys.stdout.flush()\n", 741 | " time.sleep(60*60) \n", 742 | " url_list = re.findall('(?:https?://|www.)[^\"\\' ]+', offpage)\n", 743 | " return url_list[0]\n", 744 | "\n", 745 | "def get_soundcloud_song(song_url):\n", 746 | " # given url, grabs mp3 using offliberty\n", 747 | " api_url = \"https://api.soundcloud.com/resolve.json?\" + urllib.urlencode([(\"url\",song_url), (\"client_id\",client_id)])\n", 748 | " req = urllib2.Request(api_url) \n", 749 | " #res = urllib2.urlopen(req)\n", 750 | " print song_url, api_url\n", 751 | " #req.add_header(\"User-agent\", \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36\")\n", 752 | " #req.add_header(\"Referer\",\"http://offliberty.com/\")\n", 753 | "\n", 754 | " result = json.loads(urllib2.urlopen(req).read())\n", 755 | " mp3_url = result[\"stream_url\"] + \"?client_id=\" + client_id\n", 756 | " return mp3_url\n" 757 | ], 758 | "language": "python", 759 | "metadata": {}, 760 | "outputs": [], 761 | "prompt_number": 5 762 | }, 763 | { 764 | "cell_type": "code", 765 | "collapsed": false, 766 | "input": [], 767 | "language": "python", 768 | "metadata": {}, 769 | "outputs": [], 770 | "prompt_number": 5 771 | }, 772 | { 773 | "cell_type": "code", 774 | "collapsed": false, 775 | "input": [ 776 | "from PIL import Image\n", 777 | "import PIL.ImageOps\n", 778 | "import PIL.ImageFilter as ImageFilter\n", 779 | "import ImageChops\n", 780 | "\n", 781 | "\n", 782 | "# resizes image so its all blurred\n", 783 | "def autochip_art(bot,track_art):\n", 784 | " image = Image.open(track_art)\n", 785 | " image = image.resize((16,16),Image.NEAREST).resize((800,800),Image.NEAREST)\n", 786 | " new_track_art = track_art[:-3] + \"rmx.autochip.\" + track_art[-3:]\n", 787 | " image.save(new_track_art) \n", 788 | " return new_track_art\n", 789 | "\n", 790 | "# takes art, finds edges, creates horz and vert symmetry\n", 791 | "def art_florp(bot,track_art):\n", 792 | " image = Image.open(track_art)\n", 793 | " image = image.filter(ImageFilter.FIND_EDGES)\n", 794 | " image = Image.blend(Image.blend(image, image.rotate(90), 0.5), Image.blend(image.rotate(180), image.rotate(270), 0.5), 0.5)\n", 795 | " new_track_art = track_art[:-3] + \"rmx.florp.\" + track_art[-3:]\n", 796 | " image.save(new_track_art) \n", 797 | " return new_track_art\n", 798 | "\n", 799 | "# simple horz flip, kinda dumb\n", 800 | "def horzflip(bot,art):\n", 801 | " image = Image.open(art)\n", 802 | " image = Image.blend(image, image.rotate(180), 0.5)\n", 803 | " new_art = art[:-3] + \"rmx.horzflip.\" + art[-3:]\n", 804 | " image.save(new_art)\n", 805 | " return new_art\n", 806 | " \n", 807 | "#octogon flip\n", 808 | "def octoflip(bot,art):\n", 809 | " image = Image.open(art)\n", 810 | " image = Image.blend(Image.blend(image, image.rotate(90), 0.5), Image.blend(image.rotate(180), image.rotate(270), 0.5), 0.5)\n", 811 | " image = Image.blend(image, image.rotate(45), 0.5)\n", 812 | " image = image.filter(ImageFilter.SHARPEN)\n", 813 | " image = image.filter(ImageFilter.SHARPEN)\n", 814 | " new_art = art[:-3] + \"rmx.octo.\" + art[-3:]\n", 815 | " image.save(new_art)\n", 816 | " return new_art" 817 | ], 818 | "language": "python", 819 | "metadata": {}, 820 | "outputs": [], 821 | "prompt_number": 6 822 | }, 823 | { 824 | "cell_type": "code", 825 | "collapsed": false, 826 | "input": [], 827 | "language": "python", 828 | "metadata": {}, 829 | "outputs": [], 830 | "prompt_number": 6 831 | }, 832 | { 833 | "cell_type": "code", 834 | "collapsed": false, 835 | "input": [], 836 | "language": "python", 837 | "metadata": {}, 838 | "outputs": [], 839 | "prompt_number": 6 840 | }, 841 | { 842 | "cell_type": "code", 843 | "collapsed": false, 844 | "input": [ 845 | "#!/usr/bin/env python\n", 846 | "# encoding: utf-8\n", 847 | "\n", 848 | "\"\"\"\n", 849 | "DadaBot.py\n", 850 | "\n", 851 | "Class for soundcloud bots. \n", 852 | "\n", 853 | "By CJ Carr [cortexel.us]\n", 854 | "Zack Zukowski\n", 855 | "\"\"\"\n", 856 | "import soundcloud\n", 857 | "import time\n", 858 | "import sys\n", 859 | "import os.path\n", 860 | "import urllib2\n", 861 | "from random import choice\n", 862 | "import random\n", 863 | "from random import randint\n", 864 | "from requests.exceptions import HTTPError \n", 865 | "import pickle\n", 866 | "import copy\n", 867 | "import subprocess\n", 868 | "from random import shuffle\n", 869 | "usage = \"Use it correctly, not incorrectly\"\n", 870 | "\n", 871 | "class DadaBot:\n", 872 | " \n", 873 | " def __init__(bot): \n", 874 | " bot.client = None # need to call connectSC()\n", 875 | " bot.bot_user = None # need to call connectSC()\n", 876 | " bot.followers = None # list of all followers\n", 877 | " bot.follower = None # follower sc object whose music is remixed\n", 878 | "\n", 879 | " bot.track = None # track sc object to be remixed\n", 880 | " bot.track_mp3 = \"\" # file name of downloaded song to be remixed\n", 881 | " bot.track_art = \"\" # filename of track art downloaded\n", 882 | " bot.user_art = \"\" # filename of user art downloaded\n", 883 | " \n", 884 | " bot.always_find_new_tracks = True \n", 885 | " # If True, will not remix a track which has been favorited by the bot\n", 886 | " # If False, all tracks are fair game.\n", 887 | " \n", 888 | " bot.creative_commons_only = True\n", 889 | " # ignores tracks which aren't creative commons\n", 890 | "\n", 891 | " bot.followerid = 0\n", 892 | " bot.trackid = 0\n", 893 | " bot.remix_trackid = 0\n", 894 | " bot.bot_userid = 0\n", 895 | " \n", 896 | " bot.remix_track = None # track sc of new remix track\n", 897 | " bot.remix_title = \"\" # title of new remix track\n", 898 | " bot.remix_mp3 = \"\" # filename of new remix \n", 899 | " bot.remix_artwork = \"\" # filename of remixed artwork\n", 900 | " bot.remix_completed = False\n", 901 | " bot.remix_process_call = \"\"\n", 902 | " \n", 903 | " # DEFAULT info\n", 904 | " bot.username = \"****\"\n", 905 | " bot.password = \"******\"\n", 906 | " bot.genre = \"chiptune\"\n", 907 | " bot.tag = \"autochiptune\" # for file names example: \"song.rmx.weev.mp3\"\n", 908 | " \n", 909 | " # unicode(\"z \", errors='ignore')# unicode(\" \", errors='ignore') # unicode(\"\\u0290 \", errors='replace') #\" \" #.decode(\"utf-8\", \"replace\")\n", 910 | "\n", 911 | " bot.MAX_TRACK_DURATION = 1000 * 60 * 8 # no tracks longer than 8 minutes\n", 912 | " bot.MIN_TRACK_DURATION = 10 * 1000 # minimum 10 seconds\n", 913 | " bot.MAX_FILE_SIZE = 10000000\n", 914 | " bot.comments = [\n", 915 | " 'autochiptune_remix: %s',\n", 916 | " ] \n", 917 | " \n", 918 | " def connect(bot, *args):\n", 919 | " global client_id, client_secret \n", 920 | " if len(args)==2:\n", 921 | " username = args[0]\n", 922 | " password = args[1]\n", 923 | " else:\n", 924 | " username = bot.username\n", 925 | " password = bot.password\n", 926 | " \n", 927 | " # intiialize\n", 928 | " print \"Initializing soundcloud.Client . . . \"\n", 929 | " bot.client = soundcloud.Client(\n", 930 | " client_id=client_id, \n", 931 | " client_secret=client_secret,\n", 932 | " username=username, \n", 933 | " password=password)\n", 934 | " bot.bot_user = bot.client.get('/me')\n", 935 | " bot.bot_userid = bot.bot_user.id\n", 936 | " \n", 937 | " # Get a list of all the given user's followers. stop at \n", 938 | " def get_followers(bot, user_id, max_limit):\n", 939 | " followers = []\n", 940 | " url = ('/users/%s/followers') % user_id\n", 941 | " # soundcloud api only gives you 200 at a time, so we need to loop through with next_href\n", 942 | " # see: https://developers.soundcloud.com/docs#pagination\n", 943 | " while len(followers)= bot.MIN_TRACK_DURATION), tracks)\n", 1106 | " shuffle(tracks)\n", 1107 | " \n", 1108 | " tracktitles = []\n", 1109 | " for t in tracks:\n", 1110 | " tracktitles.append(t.title)\n", 1111 | " print \"Filtered titles: \", tracktitles\n", 1112 | " \n", 1113 | " for track in tracks:\n", 1114 | " print \"Hmm.. \", track.title\n", 1115 | " bot.follower = follower\n", 1116 | " bot.track = track\n", 1117 | " if bot.download_mp3_and_art(): \n", 1118 | " track_found = True\n", 1119 | " break\n", 1120 | " \"\"\"else:\n", 1121 | " sys.stdout.write(\"Keep searching through \" + follower.username + \"'s tracks?\")\n", 1122 | " choice = raw_input().lower()\n", 1123 | " if choice==\"y\" or choice==\"yes\":\n", 1124 | " continue\n", 1125 | " else:\n", 1126 | " break\n", 1127 | " \"\"\"\n", 1128 | " \n", 1129 | " if track_found:\n", 1130 | " break\n", 1131 | " \n", 1132 | " if not track_found:\n", 1133 | " raise Exception( \"NO TRACKS!!!!!!!!!!\" )\n", 1134 | " \n", 1135 | " print \"\\n\"\n", 1136 | " bot.trackid = bot.track.id\n", 1137 | " bot.followerid = bot.follower['id']\n", 1138 | " \n", 1139 | " return True\n", 1140 | " \n", 1141 | "\n", 1142 | " def dump_intention(bot):\n", 1143 | " intention_filename = \"./dadabots/intn/\" + bot.track_mp3[6:-4] + \".\" + bot.tag + \".intention\"\n", 1144 | " \n", 1145 | " # an intention is a copy of the bot object\n", 1146 | " # except it does not contain the soundcloud objects (because this causes a stack overflow)\n", 1147 | " intention = copy.copy(bot)\n", 1148 | " intention.follower = None\n", 1149 | " intention.followers = None\n", 1150 | " intention.track = None\n", 1151 | " intention.remix_track = None\n", 1152 | " intention.client = None\n", 1153 | " intention.bot_user = None \n", 1154 | " \n", 1155 | " file = open(intention_filename, \"wb\" )\n", 1156 | " pickle.dump(intention, file)\n", 1157 | " file.close()\n", 1158 | " print intention_filename\n", 1159 | " return intention_filename\n", 1160 | " \n", 1161 | " @staticmethod\n", 1162 | " def load(intention_filename):\n", 1163 | " file = open( intention_filename, \"rb\" )\n", 1164 | " sys.setrecursionlimit(10000)\n", 1165 | " bot = pickle.load(file)\n", 1166 | " file.close()\n", 1167 | " bot.connect(bot.username, bot.password)\n", 1168 | " bot.track = bot.client.get('/tracks/'+str(bot.trackid))\n", 1169 | " bot.follower = bot.client.get('/users/'+str(bot.track.user_id))\n", 1170 | " \n", 1171 | " return bot\n", 1172 | " \n", 1173 | " def post_remix(bot):\n", 1174 | " print \"Uploading remix . . . \"\n", 1175 | " print \"Remix track art\", bot.remix_track_art\n", 1176 | " if(bot.remix_track_art):\n", 1177 | " art_bytes = open(bot.remix_track_art, 'rb')\n", 1178 | " elif(bot.remix_user_art):\n", 1179 | " art_bytes = open(bot.remix_user_art, 'rb')\n", 1180 | " else:\n", 1181 | " art_bytes = \"\"\n", 1182 | " if not bot.remix_description:\n", 1183 | " bot.remix_description = '%s remix of %s' % (bot.tag, bot.track.permalink_url)\n", 1184 | " try: \n", 1185 | " bot.remix_track = bot.client.post('/tracks', track={\n", 1186 | " 'title': bot.remix_title,\n", 1187 | " 'asset_data': open(bot.remix_mp3, 'rb'),\n", 1188 | " 'sharing': 'public',\n", 1189 | " 'description' : bot.remix_description,\n", 1190 | " 'genre' : bot.genre,\n", 1191 | " 'artwork_data' : art_bytes\n", 1192 | " })\n", 1193 | " except HTTPError as err:\n", 1194 | " print \"Err\", err\n", 1195 | " if \"422\" in err:\n", 1196 | " raise Exception(\"Error uploading track to SoundCloud. Account has probably reached upload limit. Limit=3 hours for standard SoundCloud accounts\")\n", 1197 | " else:\n", 1198 | " raise\n", 1199 | " except:\n", 1200 | " print \"Exception:\", sys.exc_info()[0]\n", 1201 | " raise\n", 1202 | " # print track link\n", 1203 | " print bot.remix_track.permalink_url\n", 1204 | " return bot.remix_track\n", 1205 | "\n", 1206 | " def update_avatar(bot,image):\n", 1207 | " print \"Updating avatar...\" + image\n", 1208 | " user = bot.client.put('/me', user={\n", 1209 | " 'avatar_data' :open(image, 'rb')\n", 1210 | " })\n", 1211 | " return user\n", 1212 | " \n", 1213 | " # returns a comment\n", 1214 | " def comment(bot, url):\n", 1215 | " comment = choice(bot.comments) % url\n", 1216 | " return comment\n", 1217 | " \n", 1218 | " def main(bot):\n", 1219 | " \n", 1220 | " print \"hi\"\n", 1221 | " \n", 1222 | " bot.creative_commons_only = False\n", 1223 | " \n", 1224 | " #connect to soundcloud API\n", 1225 | " bot.connect(bot.username, bot.password)\n", 1226 | " \n", 1227 | " # grab track from this follower\n", 1228 | " # downloads mp3, track art, and user art, and returns filenames\n", 1229 | " bot.find_track()\n", 1230 | " # bot.grab_track(\"https://soundcloud.com/leeloo0905/in-the-eye\")\n", 1231 | " \n", 1232 | " # update bot user art\n", 1233 | " if(bot.user_art):\n", 1234 | " bot.remix_user_art = autochip_art(bot, bot.user_art)\n", 1235 | " bot.update_avatar(bot.remix_user_art)\n", 1236 | " \n", 1237 | " # remix track art\n", 1238 | " if(bot.track_art):\n", 1239 | " print \"Remixing track art\", bot.track_art\n", 1240 | " bot.remix_track_art = autochip_art(bot, bot.track_art)\n", 1241 | " else:\n", 1242 | " print \"No track art to remix\"\n", 1243 | " \n", 1244 | " \n", 1245 | " bot.remix_description =\"Automatic chiptune remix bot.\\nFollow if you want your tracks remixed.\\nUnfollow if you don't.\"\n", 1246 | " bot.remix()\n", 1247 | " #bot.remix_mp3 = bot.track_mp3\n", 1248 | " \n", 1249 | " # remix title\n", 1250 | " bot.remix_title = \"%s: %s [autochip rmx]\" % tuple([bot.follower['username'], bot.track.title])\n", 1251 | " print \"Remix title: \"+bot.remix_title\n", 1252 | " sys.stdout.flush()\n", 1253 | " # POST remix\n", 1254 | " remix = bot.post_remix()\n", 1255 | " \n", 1256 | " # delete all the files \n", 1257 | " print \"deleting tracks\"\n", 1258 | " !rm {bot.remix_mp3}\n", 1259 | " !rm {bot.track_mp3}\n", 1260 | " !rm {bot.remix_track_art}\n", 1261 | " !rm {bot.remix_user_art}\n", 1262 | " !rm {bot.user_art}\n", 1263 | " !rm {bot.track_art}\n", 1264 | "\n", 1265 | " # follow all the follower's followers\n", 1266 | " # off for now\n", 1267 | " bot.amicabilify(bot.follower['id'])\n", 1268 | " \n", 1269 | " # like track\n", 1270 | " bot.like_track(bot.track)\n", 1271 | " \n", 1272 | " # comment on original track\n", 1273 | " comment_string = bot.comment(bot.remix_track.permalink_url)\n", 1274 | " print \"Commenting . . . \" + comment_string + \"\\n\"\n", 1275 | " track_comment = bot.client.post('/tracks/%d/comments' % bot.track.id, comment={\n", 1276 | " 'body': comment_string,\n", 1277 | " 'timestamp': random.randint(0,bot.track.duration-1)\n", 1278 | " })\n", 1279 | " \n", 1280 | " # comment on remix\n", 1281 | " remix_comment_string = \"Original: \" + bot.track.permalink_url\n", 1282 | " print \"Commenting . . . \" + remix_comment_string + \"\\n\"\n", 1283 | " track_comment = bot.client.post('/tracks/%d/comments' % bot.remix_track.id, comment={\n", 1284 | " 'body': remix_comment_string,\n", 1285 | " 'timestamp': 100\n", 1286 | " })\n", 1287 | " \n", 1288 | " # delete old mixes\n", 1289 | " \n", 1290 | " \n", 1291 | " print \"bye\"\n", 1292 | " return True" 1293 | ], 1294 | "language": "python", 1295 | "metadata": {}, 1296 | "outputs": [], 1297 | "prompt_number": 7 1298 | }, 1299 | { 1300 | "cell_type": "code", 1301 | "collapsed": false, 1302 | "input": [], 1303 | "language": "python", 1304 | "metadata": {}, 1305 | "outputs": [], 1306 | "prompt_number": 7 1307 | }, 1308 | { 1309 | "cell_type": "code", 1310 | "collapsed": false, 1311 | "input": [], 1312 | "language": "python", 1313 | "metadata": {}, 1314 | "outputs": [] 1315 | }, 1316 | { 1317 | "cell_type": "code", 1318 | "collapsed": false, 1319 | "input": [ 1320 | "import gc\n", 1321 | "import traceback \n", 1322 | "\n", 1323 | "bot = DadaBot()\t\n", 1324 | "gc.enable()\n", 1325 | "\n", 1326 | "client_id = '***********************'\n", 1327 | "client_secret = '*********************'\n", 1328 | "while True:\n", 1329 | " print \"Autochiptune remix.\"\n", 1330 | "\n", 1331 | " tic = time.time()\n", 1332 | " bot = DadaBot()\t\n", 1333 | " try:\n", 1334 | " bot.main()\n", 1335 | " except:\n", 1336 | " print \"Unexpected error:\", sys.exc_info() \n", 1337 | " traceback.print_exc(file=sys.stdout)\n", 1338 | " \n", 1339 | " del bot \n", 1340 | " toc = time.time()\n", 1341 | " \n", 1342 | " print \"sleeping..\" \n", 1343 | " sys.stdout.flush()\n", 1344 | " gc.collect()\n", 1345 | " #time.sleep(1) # Delay \n", 1346 | " time.sleep(10) #delay \n", 1347 | " print \"awake.\"" 1348 | ], 1349 | "language": "python", 1350 | "metadata": {}, 1351 | "outputs": [ 1352 | { 1353 | "output_type": "stream", 1354 | "stream": "stdout", 1355 | "text": [ 1356 | "Autochiptune remix.\n", 1357 | "hi\n", 1358 | "Initializing soundcloud.Client . . . \n", 1359 | "Searching hillary was here's tracks . . . " 1360 | ] 1361 | }, 1362 | { 1363 | "output_type": "stream", 1364 | "stream": "stdout", 1365 | "text": [ 1366 | "\n", 1367 | "Titles: " 1368 | ] 1369 | } 1370 | ] 1371 | }, 1372 | { 1373 | "cell_type": "code", 1374 | "collapsed": false, 1375 | "input": [ 1376 | "\n", 1377 | "\n" 1378 | ], 1379 | "language": "python", 1380 | "metadata": {}, 1381 | "outputs": [] 1382 | }, 1383 | { 1384 | "cell_type": "code", 1385 | "collapsed": false, 1386 | "input": [], 1387 | "language": "python", 1388 | "metadata": {}, 1389 | "outputs": [] 1390 | }, 1391 | { 1392 | "cell_type": "code", 1393 | "collapsed": false, 1394 | "input": [], 1395 | "language": "python", 1396 | "metadata": {}, 1397 | "outputs": [] 1398 | } 1399 | ], 1400 | "metadata": {} 1401 | } 1402 | ] 1403 | } --------------------------------------------------------------------------------