Debian Codegraph @

examples/ai/word2vec/poem-ungenerate.ck

raw
1 //------------------------------------------------------------------------------
2 // name: poem-ungenerate.ck
3 // desc: they just keep coming; more sus poem word2vec examples
4 //
5 // version: need chuck version 1.5.0.0 or higher
6 // sorting: part of ChAI (ChucK for AI)
7 //
8 // NOTE: because this example needs ConsoleInput, it needs to
9 // run command line chuck
10 // > chuck poem-ungenerate.ck
11 //
12 // "Degenerate"
13 // -- a stream of unconsciousness poem generator
14 //
15 // this example prompts for a line of text
16 // (e.g., roses are red) and a number of iterations,
17 // and outputs a series of lines that use word2vec to
18 // change one word to an adjacent word from the previous
19 // iteration, while generating unsettling descending
20 // shepard tones
21 //
22 // NOTE: need a pre-trained word vector model, e.g., from
23 // https://chuck.stanford.edu/chai/data/glove/
24 // glove-wiki-gigaword-50-tsne-2.txt (400000 words x 2 dimensions)
25 //
26 // author: Ge Wang
27 // date: Spring 2023
28 //------------------------------------------------------------------------------
29
30 // random seed (if set, sequence can be reproduce)
31 // Math.srandom( 515 );
32
33 // instantiate
34 Word2Vec model;
35 // pre-trained model to load
36 me.dir() + "glove-wiki-gigaword-50-tsne-2.txt" => string filepath;
37 // load pre-trained model (see URLs above for download)
38 if( !model.load( filepath ) )
39 {
40 <<< "cannot load model:", filepath >>>;
41 me.exit();
42 }
43
44 // conditions
45 3 => int LINES_PER_STANZA;
46 3 => int NUM_SECTIONS; // here each section is a fixed stanzas format
47
48 // number of nearest words to retrieve for each word
49 // higher this number the higher the variance per word
50 10 => int K_NEAREST;
51
52 // timing
53 100::ms => dur T_WORD; // duration per word
54 false => int shouldScaleTimeToWordLength; // longer words take longer?
55 T_WORD => dur T_LINE_PAUSE; // a little pause after each line
56 T_WORD * 2 => dur T_STANZA_PAUSE; // pause after each stanza
57
58 // make a ConsoleInput
59 ConsoleInput in;
60 // tokenizer
61 StringTokenizer tok;
62 // line
63 string line[0];
64
65 // ------------ audio: shepard tone generator ---------
66 // starting pitches (in MIDI note numbers, octaves apart)
67 [ 12.0, 24, 36, 48, 60, 72, 84, 96, 108 ] @=> float pitches[];
68 // number of tones
69 pitches.size() => int N;
70 // bank of tones
71 TriOsc tones[N];
72 // overall gain
73 Gain gain => Envelope envelope => NRev reverb => dac;
74 1.0/N => gain.gain;
75 .05 => reverb.mix;
76 // connect to dac
77 for( int i; i < N; i++ ) { tones[i] => gain; }
78 // set envelope
79 envelope.duration(1::second);
80
81 // increment per unit time (use negative for descending)
82 -.001 => float INC;
83
84 // keep shepard tone generating in the background;
85 // we will raise and lower volume
86 spork ~ shepard();
87 // ------------ audio: shepard tone generator ---------
88
89 // current word
90 string word;
91 // word vector
92 float vec[model.dim()];
93 // search results
94 string words[K_NEAREST];
95
96 // state
97 0 => int GET_TEXT;
98 1 => int GET_NUM;
99 GET_TEXT => int state;
100 // prompt
101 string prompt;
102 // the line
103 string theText[0];
104
105 // new line
106 endl();
107 // print program name
108 chout <= "\"Degenerate\"" <= IO.newline();
109 chout <= "-- a stream of unconsciousness poem generator" <= IO.newline();
110 chout.flush();
111 // new line
112 endl();
113
114 // loop
115 while( true )
116 {
117 if( state == GET_TEXT )
118 {
119 "enter a line (e.g., roses are red) => " => prompt;
120 }
121 else
122 {
123 "how many degenerations (e.g., 20) => " => prompt;
124 }
125 // prompt
126 in.prompt( prompt ) => now;
127
128 // read
129 while( in.more() )
130 {
131 // clear tokens array
132 line.clear();
133 // clear if in text input mode
134 if( state == GET_TEXT ) theText.clear();
135 // get the input line as one string; send to tokenizer
136 tok.set( in.getLine() );
137 // tokenize line into words separated by white space
138 while( tok.more() )
139 {
140 // put into array (lowercased)
141 line << tok.next().lower();
142 // copy into our text for later
143 if( state == GET_TEXT ) theText << line[line.size()-1];
144 }
145 // if non-empty
146 if( !line.size() )
147 continue;
148
149 // check state
150 if( state == GET_TEXT )
151 {
152 // set state to GET_NUM
153 GET_NUM => state;
154 }
155 else // GET_NUM
156 {
157 // check input
158 Std.atoi( line[0] ) => int n;
159 // make sure in range
160 if( n <= 0 ) continue;
161 // degenerate the input across n iterations
162 degenerate( theText, n );
163 // reset state to get text
164 GET_TEXT => state;
165 }
166 }
167 }
168
169 // do something with the text input
170 fun void degenerate( string input[], int iterations )
171 {
172 // start envelope (bring up audio)
173 envelope.keyOn();
174
175 // endline
176 endl();
177
178 // each iteration updates one word from the previous
179 for( int i; i < iterations; i++ )
180 {
181 for( int j; j < input.size(); j++ )
182 {
183 say(input[j]); wait();
184 }
185 endl();
186
187 // random word in the line
188 Math.random2(0,input.size()-1) => int which;
189 // take that work
190 input[which] => word;
191 // find similar words
192 model.getSimilar( word, words.size(), words );
193 // randomly take one and replace the word in question
194 words[Math.random2(0,words.size()-1)] => input[which];
195 }
196
197 // close envelope (ramp down audio)
198 envelope.keyOff();
199
200 // endline
201 endl();
202 // pause
203 T_STANZA_PAUSE => now;
204 }
205
206 // say a word with space after
207 fun void say( string word )
208 {
209 say( word, " " );
210 }
211
212 // say a word
213 fun void say( string word, string append )
214 {
215 // print it
216 chout <= word <= append; chout.flush();
217 }
218
219 // wait
220 fun void wait()
221 {
222 wait( T_WORD );
223 }
224
225 // wait
226 fun void wait( dur T )
227 {
228 // let time pass, let sound...sound
229 T => now;
230 }
231
232 // new line with timing
233 fun void endl()
234 {
235 endl( T_WORD );
236 }
237
238 // new line with timing
239 fun void endl( dur T )
240 {
241 // new line
242 chout <= IO.newline(); chout.flush();
243 // let time pass
244 T => now;
245 }
246
247 // shepard tone generator
248 fun void shepard()
249 {
250 //--------------------------------------------------------------------
251 // continuous shepard-risset tone generator
252 // adapted from https://chuck.stanford.edu/doc/examples/deep/shepard.ck
253 //--------------------------------------------------------------------
254
255 // mean for normal intensity curve
256 66 => float MU;
257 // standard deviation for normal intensity curve
258 42 => float SIGMA;
259 // normalize to 1.0 at x==MU
260 1 / Math.gauss(MU, MU, SIGMA) => float SCALE;
261 // unit time (change interval)
262 1::ms => dur T;
263
264 // infinite time loop
265 while( true )
266 {
267 for( int i; i < N; i++ )
268 {
269 // set frequency from pitch
270 pitches[i] => Std.mtof => tones[i].freq;
271 // compute loundess for each tone
272 Math.gauss( pitches[i], MU, SIGMA ) * SCALE => float intensity;
273 // map intensity to amplitude
274 intensity*96 => Math.dbtorms => tones[i].gain;
275 // increment pitch
276 INC +=> pitches[i];
277 // wrap (for positive INC)
278 if( pitches[i] > 120 ) 108 -=> pitches[i];
279 // wrap (for negative INC)
280 else if( pitches[i] < 12 ) 108 +=> pitches[i];
281 }
282
283 // advance time
284 T => now;
285 }
286 }