Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
|
3 |
+
from tensorflow.keras.preprocessing.text import Tokenizer
|
4 |
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
# Default files
|
8 |
+
path_to_file = 'amy-winehouse.txt'
|
9 |
+
path_to_model = './amy_winehouse.h5'
|
10 |
+
|
11 |
+
# Open model and dataset
|
12 |
+
model = tf.keras.models.load_model(path_to_model)
|
13 |
+
|
14 |
+
#Get name of file
|
15 |
+
name = path_to_file.split('.')[0]
|
16 |
+
#print(name)
|
17 |
+
data= open(path_to_file).read()
|
18 |
+
corpus = data.lower().split('\n')
|
19 |
+
|
20 |
+
#Tokenize data
|
21 |
+
tokenizer = Tokenizer()
|
22 |
+
tokenizer.fit_on_texts(corpus)
|
23 |
+
total_words = len(tokenizer.word_index) + 1
|
24 |
+
word_index = tokenizer.word_index
|
25 |
+
index_word = {index:word for word, index in tokenizer.word_index.items()}
|
26 |
+
|
27 |
+
n_gram_sequences = []
|
28 |
+
for line in corpus:
|
29 |
+
token_list = tokenizer.texts_to_sequences([line])[0]
|
30 |
+
for i in range(1, len(token_list)):
|
31 |
+
n_gram_sequences.append(token_list[:i+1])
|
32 |
+
#print(np.shape(n_gram_sequences))
|
33 |
+
|
34 |
+
#for seq in n_gram_sequences:
|
35 |
+
# print ([index_word[w] for w in seq])
|
36 |
+
|
37 |
+
# pad sequences
|
38 |
+
max_len = max([len(seq) for seq in n_gram_sequences])
|
39 |
+
|
40 |
+
#print(max_sequence_len, total_words)
|
41 |
+
n_gram_sequences = np.array(pad_sequences(n_gram_sequences, padding='pre', maxlen=max_len))
|
42 |
+
|
43 |
+
|
44 |
+
# Generate next words with an initial prompt
|
45 |
+
def predict_n_words(prompt, n_words):
|
46 |
+
|
47 |
+
for _ in range(n_words):
|
48 |
+
token_list = tokenizer.texts_to_sequences([prompt])[0]
|
49 |
+
token_list = pad_sequences([token_list], padding='pre', maxlen=max_len-1,)
|
50 |
+
predicted = np.argmax( model.predict(token_list), axis = 1)
|
51 |
+
prompt += " " + index_word[predicted[0]]
|
52 |
+
return prompt
|
53 |
+
|
54 |
+
|
55 |
+
import gradio as gr
|
56 |
+
|
57 |
+
demo = gr.Interface(
|
58 |
+
fn=predict_n_words,
|
59 |
+
inputs=[gr.Textbox(lines=2, placeholder="Prompt text here..."), gr.Slider(0, 500)],
|
60 |
+
outputs="text",
|
61 |
+
examples=[
|
62 |
+
["the girl from ipanema", 200],
|
63 |
+
["A walk through Cagliari", 200],
|
64 |
+
],
|
65 |
+
title="Amy Winehouse RNN",
|
66 |
+
description="Simple word-based RNN text generator trained on Amy Winehouse's songs",
|
67 |
+
)
|
68 |
+
|
69 |
+
demo.launch()
|