-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
poetrygenerator.py
247 lines (206 loc) · 6.41 KB
/
poetrygenerator.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#!/usr/bin/env python
from cgi import parse_qs, escape
from time import sleep
import json
import os
import random
import re
from poem import *
html_template = """
<html>
<head>
<title>A simple poem generator</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src=https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-62257429-1', 'auto');
ga('send', 'pageview');
</script>
<style>
body {
background: #FFF;
color: #111;
font: 18px Baskerville, "Palatino Linotype", "Times New Roman", Times, serif;
text-align: center;
}
#poem div, h1, h2, p {
margin: 0;
padding: 0;
}
#poem {
margin: auto;
padding: 20px 0;
text-align: left;
width: 650px;
}
#poem h1, h2 {
font-weight: normal;
text-align: center;
}
#poem h1 {
font-size: 34px;
line-height: 1.2;
margin-bottom: 10px;
}
#poem h2 {
color: #666;
font-size: 18px;
font-style: italic;
margin-bottom: 30px;
}
#poem p {
line-height: 1.5;
margin-bottom: 15px;
}
/* The magic of selectors begins... */
#poem h2:before {
content: '- ';
}
#poem h2:after {
content: ' -';
}
#poem h2 + p:first-letter {
float: left;
font-size: 38px;
line-height: 1;
margin: 2px 5px 0 0;
}
#poem p:first-line {
font-variant: small-caps;
letter-spacing: 1px;
}
#poem p:last-child {
margin-bottom: 30px;
padding-bottom: 30px;
}
#footer {
position: fixed;
bottom: 0;
}
</style>
<script>
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
</script>
</head>
<body>
<h1>Poetry generator</h1>
<div class="well center-block" style="max-width: 600px;">
<form method="POST" action="/poem">
<div class="row">
<div class="col-md-6"><button type="submit" class="btn btn-primary btn-lg btn-block" name='poemtype' value='poem'>Regular Poem</button></div>
<div class="col-md-6"><button type="submit" class="btn btn-default btn-lg btn-block" name='poemtype' value='mushypoem'>Mushy poem</button></div>
</div>
</form>
</div>
<div id="poem">%(poem)s <h2>%(url)s</h2></div>
<footer class="footer">
<div class="container">
<p class="text-muted">See how this code passed the turing test <a href="http://rpiai.com/2015/01/24/turing-test-passed-using-computer-generated-poetry/">here</a> and <a href="http://motherboard.vice.com/read/the-poem-that-passed-the-turing-test">here</a>. Also check out the <a href="https://github.com/schollz/poetry-generator">source code!</a></p>
</div>
</footer>
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick='partA();' type='button' value='Play' />
<script>
document.addEventListener("DOMContentLoaded", function(event) {
msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
setTimeout(function () {
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 0; //0 to 2
msg.lang = 'en-US';
messages = %(lines)s;
var messageNumber = 0;
msg.text = messages[messageNumber];
msg.onend = function(e) {
console.log('Finished in ' + event.elapsedTime + ' seconds.');
messageNumber = messageNumber + 1;
msg.text = messages[messageNumber];
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.rate = 1; // 0.1 to 10
msg.pitch = 0; //0 to 2
msg.lang = 'en-US';
msg.volume = 1; // 0 to 1
if (msg.text=="pause") {
msg.volume = 0;
} else {
}
if (messageNumber < messages.length) {
speechSynthesis.speak(msg);
}
};
speechSynthesis.speak(msg);
}, 1000);
});
</script>
</body>
</html>
"""
pages = {
'index' : html_template,
}
class Router():
def __init__(self, url):
self.url = url
def match(self, pattern):
match = re.search(pattern, self.url)
if match:
self.params = match.groupdict()
return True
else:
return False
def application(environ, start_response):
url = environ['PATH_INFO']
router = Router(url)
if router.match('^/(?P<type>poem|mushypoem)/(?P<seed>[0-9a-zA-Z]+)$'):
return show_poem(environ, start_response, router)
else: # '/' '/poem' or anything else
return redirect_to_poem(environ, start_response)
def redirect_to_poem(environ, start_response):
# We might have a POST body indicating the poem type; try to read it.
# The environment variable CONTENT_LENGTH may be empty or missing
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
# Read and parse the HTTP request body which is passed by the WSGI server
request_body = environ['wsgi.input'].read(request_body_size)
poemtype = None
qs = parse_qs(request_body)
if qs:
poemtype = qs.get('poemtype')[0]
if poemtype != 'mushypoem':
poemtype = 'poem'
seed = os.urandom(8).encode('hex')
start_response('302 Found', [
('Location', '/' + poemtype + '/' + seed)
])
return []
def show_poem(environ, start_response, router):
# Ensure that we can always get back to a given poem
p,str_seed = bnf.generatePretty('<' + router.params['type'] + '>',router.params['seed'])
filtered = []
for line in re.sub("<.*?>", " ", p).split("\n"):
if len(line.strip()) > 0:
filtered.append(line.strip())
else:
filtered.append("pause")
response_body = pages['index'] % {
'poem': p,
'url': router.url,
'lines': json.dumps(filtered)
}
start_response('200 OK', [
('Content-Type', 'text/html'),
('Content-Length', str(len(response_body)))
])
return [response_body]