-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
142 lines (105 loc) · 3.56 KB
/
app.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
print("starting");
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.layers import Embedding, LSTM, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.models import load_model
import pickle
import numpy as np
import os
## Load the Dictionary
dictionary = 'dictionaries/chords-small.txt'
#dictionary = 'dictionaries/alice-in-wonderland.txt'
#dictionary = 'dictionaries/chords-small.txt'
file = open(dictionary, "r", encoding = "utf8")
# store file in list
lines = []
for i in file:
lines.append(i)
# Convert list to string
data = ""
for i in lines:
data = ' '. join(lines)
# --------------------------
# Data clean up
# replace unnecessary stuff with space
data = data.replace('\n', '').replace('\r', '').replace('\ufeff', '').replace('“','').replace('”','') #new line, carriage return, unicode character --> replace by space
#remove unnecessary spaces
data = data.split()
data = ' '.join(data)
print("Sample data: ", data[:20])
print ( 'Total length of data: ', len(data) )
tokenizer = Tokenizer()
tokenizer.fit_on_texts([data])
# saving the tokenizer for predict function
pickle.dump(tokenizer, open('token.pkl', 'wb'))
sequence_data = tokenizer.texts_to_sequences([data])[0]
# print(sequence_data[:15])
vocab_size = len(tokenizer.word_index) + 1
print("vocab_size: ", vocab_size)
sequences = []
for i in range(3, len(sequence_data)):
words = sequence_data[i-3:i+1]
sequences.append(words)
print("The Length of sequences are: ", len(sequences))
sequences = np.array(sequences)
print("Sequences Sample:", sequences[:3])
X = []
y = []
for i in sequences:
X.append(i[0:3])
y.append(i[3])
X = np.array(X)
y = np.array(y)
print("Data Sample: ", X[:2])
print("Response Sample: ", y[:2])
y = to_categorical(y, num_classes=vocab_size)
print("to_categorical sample:", y[:3])
model = Sequential()
model.add(Embedding(vocab_size, 10, input_length=3))
model.add(LSTM(1000, return_sequences=True))
model.add(LSTM(1000))
model.add(Dense(1000, activation="relu"))
model.add(Dense(vocab_size, activation="softmax"))
print(" --- Model Summary --- ")
print( model.summary() )
# ------------------------
# Train the model
print(" Traning the model... ")
epochs=70
checkpoint = ModelCheckpoint("next_chords.h5", monitor='loss', verbose=1, save_best_only=True)
model.compile(loss="categorical_crossentropy", optimizer=Adam(learning_rate=0.001))
model.fit(X, y, epochs=epochs, batch_size=64, callbacks=[checkpoint])
# ------------------------
# Prediction
model = load_model('next_chords.h5')
tokenizer = pickle.load(open('token.pkl', 'rb'))
last_predicted = ''
def Predict_Next_Words(model, tokenizer, text):
sequence = tokenizer.texts_to_sequences([text])
sequence = np.array(sequence)
preds = np.argmax(model.predict(sequence))
predicted_word = ""
for key, value in tokenizer.word_index.items():
if value == preds:
predicted_word = key
break
return predicted_word
while(True):
text = input("Enter a series of chords: ")
if text == "0":
print("Ending.")
break
else:
try:
text = text.split(" ")
text_last_3 = text[-3:]
last_predicted = Predict_Next_Words(model, tokenizer, text_last_3)
print("Chords: ", " ".join(text), " > ", last_predicted)
except Exception as e:
print("Error occurred: ",e)
continue
exit();