-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmodules.py
More file actions
1765 lines (1438 loc) · 61.6 KB
/
Copy pathmodules.py
File metadata and controls
1765 lines (1438 loc) · 61.6 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import os
import pdb
import random
from module import *
import shutil
import urllib
import time
#import imageio # This needs to be installed first 'pip install imageio'
#######################
class ReadTextFile(Module):
def __init__(self, file, output):
self.file = file # path to file to read
self.output = output # path to file to save to
self.ready = checkFiles(file)
self.output_files = [output]
def run(self):
# copy the file to temp
if os.path.exists(self.file):
shutil.copy(self.file, self.output)
#################
class WriteTextFile(Module):
def __init__(self, input, file):
self.file = file # path of file to write to
self.input = input # path of file to write out
self.ready = checkFiles(input)
self.output_files = [file]
def run(self):
# copy file out of temp to final destination
if len(self.file) > 0 and os.path.exists(self.input):
shutil.copy(self.input, self.file)
###################
class ConcatenateTextFiles(Module):
def __init__(self, input_1, input_2, output):
self.input_1 = input_1 # path of file 1
self.input_2 = input_2 # path of file 2
self.output = output # path of joined file
self.ready = checkFiles(input_1, input_2)
self.output_files = [output]
def run(self):
# Open the output file and write the lines from input1 and input2 into it
with open(self.output, 'w') as outfile:
for line in open(self.input_1, 'rU'):
outfile.write(line.strip() + '\n')
for line in open(self.input_2, 'rU'):
outfile.write(line.strip() + '\n')
########################
class SplitSentences(Module):
def __init__(self, input, output):
self.input = input # path of file to split
self.output = output # path of finalized split
self.ready = checkFiles(input)
self.output_files = [output]
def run(self):
# Parser will look for relevant punctuation
parser = re.compile(r'([\?\.\!:])')
with open(self.output, 'w') as outfile:
# Read input file
for line in open(self.input, 'rU'):
# split up the line.
lines = [s.strip() for s in parser.sub(r'\1\n', line).splitlines()]
# write each fragment to file
for sent in lines:
if len(sent) > 0:
outfile.write(sent + '\n')
##################################
class RemoveEmptyLines(Module):
def __init__(self, input, output):
self.input = input # path of file to alter
self.output = output # path of altered file
self.ready = checkFiles(input)
self.output_files = [output]
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
if len(line.strip()) > 0:
outfile.write(line.strip() + '\n')
############
class StripLines(Module):
def __init__(self, input, output):
self.input = input # path of file to strip
self.output = output # path of output
self.ready = checkFiles(input)
self.output_files = [output]
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
if len(line.strip()) > 0:
outfile.write(line.strip() + '\n')
############
class TextSubtract(Module):
def __init__(self, main, subtract, diff):
self.main = main # path to text file to subtract lines from
self.subtract = subtract # path to text file of lines to subtract from main
self.diff = diff # path to result file
self.ready = checkFiles(main, subtract)
self.output_files = [diff]
def run(self):
lines1 = set()
lines2 = set()
for line in open(self.main, 'r'):
lines1.add(line.strip())
for line in open(self.subtract, 'r'):
lines2.add(line.strip())
lines3 = lines1.difference(lines2)
with open(self.diff, 'w') as outfile:
for line in lines3:
outfile.write(line.strip() + NEWLINE)
###############
class DuplicateText(Module):
def __init__(self, input, count, output):
self.input = input # path of file to modify
self.output = output # path of file with duplicates
self.count = count # number of times to duplicate the input (int)
self.ready = checkFiles(input)
self.output_files = [output]
def run(self):
lines = []
for line in open(self.input, 'r'):
lines.append(line.strip())
with open(self.output, 'w') as outfile:
for _ in range(self.count + 1):
for line in lines:
outfile.write(line.strip() + NEWLINE)
##############
class ReplaceCharacters(Module):
def __init__(self, input, output, find, replace):
self.input = input # path of file to modify
self.output = output # path of output
self.find = find # string containing substring of characters to replace
self.replace = replace # string containing the replacement substring
self.ready = checkFiles(input)
self.output_files = [output]
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
outfile.write(line.replace(self.find, self.replace) + '\n')
##################
class MakeTrainTestData(Module):
def __init__(self, data, training_percent, training_data, testing_data):
self.data = data # path to file containing a chunk of data
self.training_percent = float(training_percent) # float percentage for training
self.training_data = training_data # output path for training data
self.testing_data = testing_data # output path of testing data
self.ready = checkFiles(data)
self.output_files = [training_data, testing_data]
def run(self):
lines = [] # lines of data
# Read the data
for line in open(self.data, 'rU'):
lines.append(line)
# Find the cut point
cut = int(len(lines)*(self.training_percent/100.0))
# Write training portion
with open(self.training_data, 'w') as outfile:
for i in range(cut):
outfile.write(lines[i].strip() + '\n')
# write testing portion
with open(self.testing_data, 'w') as outfile:
for i in range(cut, len(lines)):
outfile.write(lines[i].strip + '\n')
#################################
class MakeXYTrainTestData(Module):
def __init__(self, data_x, data_y, training_percent, training_x_data, training_y_data, testing_x_data, testing_y_data):
self.data_x = data_x # path of X data
self.data_y = data_y # path of Y data
self.training_percent = float(training_percent) # float portion that is training
self.training_x_data = training_x_data # path output for training x
self.training_y_data = training_y_data # path output for training y
self.testing_x_data = testing_x_data # path output for testing x
self.testing_y_data = testing_y_data # path output for testing y
self.ready = checkFiles(data_x, data_y)
self.output_files = [training_x_data, training_y_data, testing_x_data, testing_y_data]
def run(self):
lines1 = [] # x data
lines2 = [] # y data
# Read x data
for line in open(self.data_x, 'rU'):
lines1.append(line)
# Read y data
for line in open(self.data_y, 'rU'):
lines2.append(line)
# find cut point
cut = int(len(lines1)*self.training_percent)
# Write training x data
with open(self.training_x_data, 'w') as outfile:
for i in range(cut):
outfile.write(lines1[i].strip() + NEWLINE)
# Write training y data
with open(self.training_y_data, 'w') as outfile:
for i in range(cut):
outfile.write(lines2[i].strip() + NEWLINE)
# Write testing x data
with open(self.testing_x_data, 'w') as outfile:
for i in range(cut, len(lines1)):
outfile.write(lines1[i].strip() + NEWLINE)
# Write testing y data
with open(self.testing_y_data, 'w') as outfile:
for i in range(cut, len(lines2)):
outfile.write(lines2[i].strip() + NEWLINE)
########################
class ReadWikipedia(Module):
def __init__(self, wiki_directory, pattern, categories, out_file, titles_file):
self.wiki_directory = wiki_directory # path to find wikipedia files
self.pattern = pattern # string of pattern to look for
self.out_file = out_file # path of output file
self.titles_file = titles_file # path of output titles file
self.categories = categories # string of categories
self.ready = checkFiles(wiki_directory)
self.output_files = [out_file, titles_file]
def run(self):
import readWikipedia
readWikipedia.ReadWikipedia(self.wiki_directory, self.pattern, self.categories, self.out_file, self.titles_file)
#########################
class SplitLines(Module):
def __init__(self, input, output1, output2, character):
self.input = input
self.output1 = output1
self.output2 = output2
self.character = character
self.ready = checkFiles(input)
self.output_files = [output1, output2]
def run(self):
data1 = []
data2 = []
for line in open(self.input, 'rU'):
splitLine = line.split(self.character, 1)
data1.append(splitLine[0])
if len(splitLine) > 1:
data2.append(splitLine[1])
else:
data2.append('')
with open(self.output1, 'w') as outfile1:
for line in data1:
outfile1.write(line.strip() + NEWLINE)
with open(self.output2, 'w') as outfile2:
for line in data2:
outfile2.write(line.strip() + NEWLINE)
#########################
'''
class MakePredictionData(Module):
def __init__(self, data, x, y):
self.data = data
self.x = x
self.y = y
if checkFiles(data):
self.ready = True
def run(self):
last = None
x_data = []
y_data = []
for line in open(self.data, 'rU'):
if last is not None:
x_data.append(last.strip())
y_data.append(line.strip())
last = line
with open(self.x, 'w') as xoutfile:
for line in x_data:
print >> xoutfile, line
with open(self.y, 'w') as youtfile:
for line in y_data:
print >> youtfile, line
'''
#########################
class WordRNN_Train(Module):
def __init__(self, data, dictionary, model, history = 35, layers = 2, epochs = 50, hidden_nodes = 512, learning_rate = 0.0001):
self.data = data # path to training data
self.model = model # path to save model to
self.dictionary = dictionary # path to save dictionary to
self.history = history # number of words to keep in history
self.layers = layers # number of layers
self.epochs = epochs # number of epochs
self.learning_rate = learning_rate # learning rate
self.hidden_nodes = hidden_nodes # number of hidden nodes
self.ready = checkFiles(data)
self.output_files = [model, dictionary]
def run(self):
import lstm
print("Keyboard interrupt will stop training but program will try to continue.")
try:
lstm.wordLSTM_Train(train_data_path=self.data,
dictionary_path=self.dictionary, model_out_path=self.model,
history=self.history, layers=self.layers, epochs=self.epochs,
lr=self.learning_rate)
except KeyboardInterrupt:
print("keyboard interrupt")
#########################
class WordRNN_Run(Module):
def __init__(self, model, dictionary, output, seed, steps = 600, temperature = 0.5, k = 40):
self.model = model # path to model
self.dictionary = dictionary # path to dictionary
self.output = output # path to write output text to
self.seed = seed # path to a file with a single string
self.steps = steps # number of words to generate
self.temperature = temperature # temperature value
self.k = k # top k sampling value
self.ready = checkFiles(model, dictionary, seed)
self.output_files = [output]
def run(self):
import lstm
seed = '' # the seed text
# Read the first line of the file to get the seed
for line in open(self.seed, 'rU'):
seed = line.strip()
break
lstm.wordLSTM_Run(model_path=self.model, dictionary_path=self.dictionary, output_path=self.output,
seed=seed, steps=self.steps, temperature=self.temperature, k = self.k)
############################
class CharRNN_Train(Module):
def __init__(self, data, dictionary, model, history = 35, layers = 2, epochs = 50, hidden_nodes = 512, learning_rate = 0.0001):
self.data = data # path to training data
self.model = model # path to save model to
self.dictionary = dictionary # path to save dictionary to
self.history = history # number of characters to keep in history
self.layers = layers # number of layers
self.epochs = epochs # number of epochs
self.learning_rate = learning_rate # learning rate
self.hidden_nodes = hidden_nodes # number of hidden nodes
self.ready = checkFiles(data)
self.output_files = [model, dictionary]
def run(self):
import lstm
print("Keyboard interrupt will stop training but program will try to continue.")
try:
lstm.charLSTM_Train(train_data_path=self.data,
dictionary_path=self.dictionary, model_out_path=self.model,
history=self.history, layers=self.layers, epochs=self.epochs,
lr=self.learning_rate)
except KeyboardInterrupt:
print("keyboard interrupt")
#########################
class CharRNN_Run(Module):
def __init__(self, model, dictionary, output, seed, steps = 600, temperature = 0.5):
self.model = model # path to model
self.dictionary = dictionary # path to dictionary
self.output = output # path to write output text to
self.seed = seed # starting string
self.steps = steps # number of characters to generate
self.temperature = temperature # temperature value
self.ready = checkFiles(model, dictionary, seed)
self.output_files = [output]
def run(self):
import lstm
seed = '' # the seed text
# Read the first line of the file to get the seed
for line in open(self.seed, 'rU'):
seed = line.strip()
break
lstm.charLSTM_Run(model_path=self.model, dictionary_path=self.dictionary, output_path=self.output,
seed=seed, steps=self.steps, temperature=self.temperature)
###############################
'''
class GPT2_Load(Module):
def __init__(self, model_size, model_out):
self.model_size = model_size # size of GPT-2 model (e.g., "117M")
self.model_out = model_out # path to model
self.ready = True
self.output_files = [model_out]
def run(self):
gpt_path = os.path.join(os.getcwd(), "gpt-2", "models", self.model_size)
if os.path.exists(self.model_out):
shutil.rmtree(self.model_out)
shutil.copytree(gpt_path, self.model_out)
'''
class GPT2_FineTune(Module):
def __init__(self, model_in, data, steps, model_size, model_out):
self.model_in = model_in # path to model file
self.model_out = model_out # path to model file
self.data = data # path to text file
self.steps = steps # int
self.model_size = model_size # size of GPT-2 model (e.g., "117M")
self.ready = checkFiles(data, model_in)
self.output_files = [model_out]
def run(self):
import gpt2
cwd = os.getcwd()
# Clear out any existing models that might bein the way
if os.path.exists(self.model_out):
if os.path.isdir(self.model_out):
shutil.rmtree(self.model_out)
else:
os.remove(self.model_out)
# Horrible hack because gpt-2 makes assumptions about relative paths instead of absolute paths
os.chdir('gpt-2')
print("Keyboard interrupt will stop training but program will try to continue.")
try:
gpt2.train(os.path.join(cwd, self.data),
os.path.join(cwd, self.model_in),
os.path.join(cwd, self.model_out),
steps = self.steps,
model_name = self.model_size)
except KeyboardInterrupt:
print("keyboard interrupt")
shutil.copy(os.path.join(cwd, self.model_in, 'encoder.json'), os.path.join(cwd, self.model_out))
shutil.copy(os.path.join(cwd, self.model_in, 'hparams.json'), os.path.join(cwd, self.model_out))
shutil.copy(os.path.join(cwd, self.model_in, 'vocab.bpe'), os.path.join(cwd, self.model_out))
os.chdir('..')
#######################################################
class GPT2_Run(Module):
def __init__(self, model_in, prompt, model_size, top_k, temperature, num_samples, output):
self.prompt = prompt # path to prompt text file
self.model_in = model_in # path to model file
self.model_size = model_size # size of GPT-2 model (e.g., "117M")
self.top_k = top_k # int
self.temperature = temperature # float
self.num_samples = num_samples # int
self.output = output # path to output text file
self.ready = checkFiles(prompt, model_in)
self.output_files = [output]
def run(self):
import gpt2
cwd = os.getcwd()
file = open(self.prompt, 'rU')
prompt_text = file.read()
prompt_text = prompt_text.strip()
file.close()
os.chdir('gpt-2')
output_text = gpt2.run_gpt(os.path.join(cwd, self.model_in),
model_name = self.model_size,
raw_text = prompt_text,
top_k = self.top_k,
temperature = self.temperature,
nsamples = self.num_samples)
output_text = prompt_text + output_text
os.chdir('..')
with open(self.output, 'w') as outfile:
outfile.write(output_text)
###############################
'''
class Seq2Seq_Train(Module):
def __init__(self, all_data, x, y, model, dictionary, layers, hidden_nodes, epochs):
self.all_data = all_data
self.model = model
self.layers = layers
self.hidden_nodes = hidden_nodes
self.epochs = epochs
self.x = x
self.y = y
self.dictionary = dictionary
if checkFiles(all_data, x, y):
self.ready = True
def run(self):
import seq2seq_translate
# read data
data = []
for line in open(self.all_data, 'rU'):
data.append(line.strip())
x_data = []
for line in open(self.x, 'rU'):
x_data.append(line.strip())
y_data = []
for line in open(self.y, 'rU'):
y_data.append(line.strip())
# split into training and validation
data_split = int(len(data) * 0.9)
train = data[0:data_split]
validation = data[data_split:]
x_split = int(len(x_data) * 0.9)
train_x = x_data[0:x_split]
validation_x = x_data[x_split:]
y_split = int(len(y_data) * 0.9)
train_y = y_data[0:y_split]
validation_y = y_data[y_split:]
name = self.all_data.split('/')[1]
out_name = self.model.split('/')[1]
print('writing ' + name + '.train')
f = open('temp/' + name + '.train', 'w')
for line in train:
print >> f, line
f.close()
print('writing ' + name + '.validation')
f = open('temp/' + name + '.validation', 'w')
for line in validation:
print >> f, line
f.close()
print('writing ' + name + '.train.input')
f = open('temp/' + name + '.train.input', 'w')
for line in train_x:
print >> f, line
f.close()
print('writing ' + name + '.train.output')
f = open('temp/' + name + '.train.output', 'w')
for line in train_y:
print >> f, line
f.close()
print('writing ' + name + '.validation.input')
f = open('temp/' + name + '.validation.input', 'w')
for line in validation_x:
print >> f, line
f.close()
print('writing ' + name + '.validation.output')
f = open('temp/' + name + '.validation.output', 'w')
for line in validation_y:
print >> f, line
f.close()
seq2seq_translate.train(input_name = name, output_name = out_name, data_dir = 'temp', num_layers = self.layers, size = self.hidden_nodes, max_epochs = self.epochs)
copyfile('temp/checkpoint', self.model)
copyfile(self.all_data+'.vocab', self.dictionary)
'''
#####################################
'''
class Seq2Seq_Train_More(Module):
def __init__(self, all_data, x, y, model_in, dictionary, model_out, layers, hidden_nodes, epochs):
self.all_data = all_data
self.model_in = model_in
self.model_out = model_out
self.layers = layers
self.hidden_nodes = hidden_nodes
self.epochs = epochs
self.x = x
self.y = y
self.dictionary = dictionary
if checkFiles(all_data, x, y, model_in, dictionary):
self.ready = True
def run(self):
import seq2seq_translate
# read data
data = []
for line in open(self.all_data, 'rU'):
data.append(line.strip())
x_data = []
for line in open(self.x, 'rU'):
x_data.append(line.strip())
y_data = []
for line in open(self.y, 'rU'):
y_data.append(line.strip())
# split into training and validation
data_split = int(len(data) * 0.9)
train = data[0:data_split]
validation = data[data_split:]
x_split = int(len(x_data) * 0.9)
train_x = x_data[0:x_split]
validation_x = x_data[x_split:]
y_split = int(len(y_data) * 0.9)
train_y = y_data[0:y_split]
validation_y = y_data[y_split:]
name = self.all_data.split('/')[1]
out_name = self.model_out.split('/')[1]
print('writing ' + name + '.train')
f = open('temp/' + name + '.train', 'w')
for line in train:
print >> f, line
f.close()
print('writing ' + name + '.validation')
f = open('temp/' + name + '.validation', 'w')
for line in validation:
print >> f, line
f.close()
print('writing ' + name + '.train.input')
f = open('temp/' + name + '.train.input', 'w')
for line in train_x:
print >> f, line
f.close()
print('writing ' + name + '.train.output')
f = open('temp/' + name + '.train.output', 'w')
for line in train_y:
print >> f, line
f.close()
print('writing ' + name + '.validation.input')
f = open('temp/' + name + '.validation.input', 'w')
for line in validation_x:
print >> f, line
f.close()
print('writing ' + name + '.validation.output')
f = open('temp/' + name + '.validation.output', 'w')
for line in validation_y:
print >> f, line
f.close()
split_model_path = os.path.split(self.model_in)
model_name = split_model_path[1]
model_directory = split_model_path[0]
if len(model_directory) == 0:
model_directory = '.'
#split_model_path = os.path.split(self.model)
#model_file = split_model_path[1]
#model_directory = split_model_path[0]
for f in os.listdir(model_directory):
match = re.match(model_name, f)
if match is not None:
f_rest = f[len(model_name):]
copyfile(os.path.join(model_directory, f), os.path.join(CHECKPOINT_DIR, f))
with open(os.path.join(CHECKPOINT_DIR, 'checkpoint'), 'w') as f:
print >> f, 'model_checkpoint_path: "'+ model_name + '"'
print >> f, 'all_model_checkpoint_paths: "' + model_name + '"'
copyfile(self.dictionary, self.all_data+'.vocab')
seq2seq_translate.train(input_name = name, output_name = out_name, data_dir = 'temp', num_layers = self.layers, size = self.hidden_nodes, max_epochs = self.epochs)
copyfile('temp/checkpoint', self.model_out)
#copyfile(self.all_data+'.vocab', self.dictionary)
'''
#######################################
'''
class Seq2Seq_Run(Module):
def __init__(self, model, data, dictionary, layers, hidden_nodes, stop, output):
self.model = model
self.data = data
self.dictionary = dictionary
self.layers = layers
self.hidden_nodes = hidden_nodes
self.stop = stop
self.output = output
if checkFiles(model, data, dictionary):
self.ready = True
def run(self):
import seq2seq_translate
the_data = []
for line in open(self.data, 'rU'):
the_data.append(line.strip())
name = self.data.split('/')[1]
print('writing ' + name + '.test')
f = open('temp/' + name + '.test', 'w')
for line in the_data:
print >> f, line
f.close()
copyfile(self.model, 'temp/checkpoint')
copyfile(self.dictionary, self.data+'.vocab')
results = seq2seq_translate.decode(name = name, data_dir = 'temp', stop_symbol = self.stop, num_layers = self.layers, size = self.hidden_nodes)
with open(self.output, 'w') as outfile:
for line in results:
print >> outfile, line
'''
##########################################
class RandomSequence(Module):
def __init__(self, input, length, output):
self.input = input # path to input
self.output = output # path to output
self.length = int(length) # integer sequence length
self.ready = checkFiles(input)
self.output_files = [output]
def run(self):
line = '' # final output sequence
all_lines = [] # Store all lines in input
length_lines = [] # store only lines greater than desired length
for line in open(self.input, 'rU'):
line = line.strip()
all_lines.append(line)
if len(line) > self.length:
length_lines.append(line)
# Pick from lines that are long enough if you can
if len(length_lines) > 0:
# There are lines long enough
# Get a line
pick = random.choice(length_lines)
# Get a portion of that line
start = random.randint(0, len(pick)-self.length-1)
# Picked substring
line = pick[start:start+self.length]
else:
# No lines long enough
line = random.choice(all_lines)
# Write the line
with open(self.output, 'w') as outfile:
outfile.write(line + NEWLINE)
############################################
class MakeString(Module):
def __init__(self, string, output):
self.string = string # A string input
self.output = output # path to output file
self.output_files = [output]
def run(self):
with open(self.output, 'w') as f:
f.write(self.string.strip() + NEWLINE)
###############################################
class UserInput(Module):
def __init__(self, prompt, output):
self.prompt = prompt # a string with the terminal prompt
self.output = output # path to output file
self.output_files = [output]
def run(self):
# Default prompt
prompt = self.prompt.strip()
if len(prompt) == 0:
prompt = 'prompt: '
s = raw_input(prompt)
with open(self.output, 'w') as f:
f.write(s.strip() + NEWLINE)
###################################################
'''
class ReadImages(Module):
def __init__(self, data_directory, output_images):
self.data_directory = data_directory
self.output_images = output_images
if checkFiles(data_directory):
self.ready = True
def run(self):
with open(self.output_images, 'w') as f:
print >> f, self.data_directory
'''
###################################################
'''
class WriteImages(Module):
def __init__(self, input_images, output_directory):
self.input_images = input_images
self.output_directory = output_directory
def run(self):
f = open(self.input_images, 'r')
data_dir = f.readline().strip()
f.close()
if not os.path.exists(self.output_directory):
os.makedirs(self.output_directory)
for item in os.listdir(data_dir):
s = os.path.join(data_dir, item)
d = os.path.join(self.output_directory, item)
copyfile(s, d)
'''
###################################################
'''
class DCGAN_Train(Module):
def __init__(self, input_images, animation, epochs, input_height, output_height, filetype, model):
self.input_images = input_images
self.epochs = epochs
self.input_height = input_height
self.output_height = output_height
self.filetype = filetype
#self.crop = crop
#self.output_images = output_images
#self.num_images = num_images
self.animation = animation
self.model = model
if checkFiles(input_images):
self.ready = True
def run(self):
import DCGAN.main as gan
filetype = ''
if len(self.filetype) == 0:
filetype = '*.jpg'
else:
filetype = '*.' + self.filetype
#crop = self.crop
#if isinstance(self.crop, basestring):
# crop = True
# Get data directory
f = open(self.input_images, 'r')
data_dir = f.readline().strip()
f.close()
# Create directory for samples and output and checkpoints
#output_dir = self.output_images + '_output'
sample_dir = self.model + '_samples'
checkpoint_dir = CHECKPOINT_DIR
#if not os.path.exists(output_dir):
# os.makedirs(output_dir)
if not os.path.exists(sample_dir):
os.makedirs(sample_dir)
# Figure out where to save the model
model_path_split = os.path.split(self.model)
model_dir = model_path_split[0]
model_filename = model_path_split[1]
if len(model_dir) == 0:
model_dir = '.'
gan.train(epoch = self.epochs, input_height = self.input_height, input_width = self.input_height, output_height = self.output_height, output_width = self.output_height, input_fname_pattern = filetype, dataset = data_dir, sample_dir = sample_dir, checkpoint_dir = checkpoint_dir, model_dir = model_dir, model_filename = model_filename)
#with open(self.output_images, 'w') as f:
# print >> f, output_dir
# Make the training animation
images = []
samples = sorted(os.listdir(sample_dir), key=lambda f: os.stat(os.path.join(sample_dir, f)).st_mtime)
for sample in samples:
images.append(imageio.imread(os.path.join(sample_dir, sample), 'png'))
if len(images) > 0:
imageio.mimsave(self.animation, images, 'gif')
'''
#####################################################
'''
class DCGAN_Run(Module):
def __init__ (self, input_images, input_height, output_height, filetype, output_image, model):
self.input_images = input_images
self.output_image = output_image
self.input_height = input_height
self.output_height = output_height
self.filetype = filetype
#self.num_images = num_images
self.model = model
self.ready = checkFiles(input_images)
def run(self):
import DCGAN.main as gan
filetype = ''
if len(self.filetype) == 0:
filetype = '*.jpg'
else:
filetype = '*.' + self.filetype
# Get data directory
f = open(self.input_images, 'r')
data_dir = f.readline().strip()
f.close()
# Run the model
#copyfile(self.model, 'temp/checkpoint')
gan.run(output_dir = self.output_image, input_height = self.input_height, input_width = self.input_height, output_height = self.output_height, output_width = self.output_height, input_fname_pattern = filetype, dataset = data_dir, checkpoint_dir = 'temp')
'''
####################################
class PickFromWikipedia(Module):
def __init__(self, wiki_directory, input, categories, section_name, output, break_sentences):
self.wiki_directory = wiki_directory # path to wikipedia dump files
self.input = input # name of file. Each line should be a title of a wikipedia article
self.output = output # name of file. Paragraphs pulled from wikipedia. <EOS> after each article.
self.section_name = section_name # Do you just want a sub-section? Or '' for all.
self.break_sentences = break_sentences # bool - one sentence per line?
self.categories = categories # Restrict to certain categories
self.ready = checkFiles(wiki_directory, input)
self.output_files = [output]
def run(self):
import readWikipedia
pattern = '' # The pattern is created by the lines of the input file
first = True # first pattern?
# Get each line and append it to the pattern
for line in open(self.input, 'rU'):
line = line.strip() # line from input file
if first:
# First line
if len(line) > 0:
pattern = line
first = False
else:
# Not the first line
if len(line) > 0:
pattern = pattern + '|' + line
# If a section name is specified, append it to pattern
if len(self.section_name.strip()) > 0:
pattern = pattern + ':' + self.section_name.strip()
readWikipedia.ReadWikipedia(self.wiki_directory, pattern, self.categories, self.output, 'temp/pickfromwikipediatitles')
#######################################
class RandomizeLines(Module):
def __init__(self, input, output):
self.input = input # path to input