-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
compose.py
82 lines (60 loc) · 2.25 KB
/
compose.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
Implemented Markov Chain Composer by Kylie Ying
YouTube Kylie Ying: https://www.youtube.com/ycubed
Twitch KylieYing: https://www.twitch.tv/kylieying
Twitter @kylieyying: https://twitter.com/kylieyying
Instagram @kylieyying: https://www.instagram.com/kylieyying/
Website: https://www.kylieying.com
Github: https://www.github.com/kying18
Programmer Beast Mode Spotify playlist: https://open.spotify.com/playlist/4Akns5EUb3gzmlXIdsJkPs?si=qGc4ubKRRYmPHAJAIrCxVQ
"""
import os
import re
import string
import random
from graph import Graph, Vertex
def get_words_from_text(text_path):
with open(text_path, 'rb') as file:
text = file.read().decode("utf-8")
# remove [verse 1: artist]
# include the following line if you are doing song lyrics
# text = re.sub(r'\[(.+)\]', ' ', text)
text = ' '.join(text.split())
text = text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
words = text.split()
words = words[:1000]
return words
def make_graph(words):
g = Graph()
prev_word = None
# for each word
for word in words:
# check that word is in graph, and if not then add it
word_vertex = g.get_vertex(word)
# if there was a previous word, then add an edge if does not exist
# if exists, increment weight by 1
if prev_word: # prev word should be a Vertex
# check if edge exists from previous word to current word
prev_word.increment_edge(word_vertex)
prev_word = word_vertex
g.generate_probability_mappings()
return g
def compose(g, words, length=50):
composition = []
word = g.get_vertex(random.choice(words))
for _ in range(length):
composition.append(word.value)
word = g.get_next_word(word)
return composition
def main():
words = get_words_from_text('texts/hp_sorcerer_stone.txt')
# for song in os.listdir('songs/{}'.format(artist)):
# if song == '.DS_Store':
# continue
# words.extend(get_words_from_text('songs/{artist}/{song}'.format(artist=artist, song=song)))
g = make_graph(words)
composition = compose(g, words, 100)
print(' '.join(composition))
if __name__ == '__main__':
main()