forked from markriedl/easygen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodules.py
More file actions
1443 lines (1123 loc) · 36 KB
/
Copy pathmodules.py
File metadata and controls
1443 lines (1123 loc) · 36 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 random
from glob import glob
from module import *
#import readWikipedia
#import lstm
#import seq2seq_translate
#import DCGAN.main as gan
from shutil import copyfile
from shutil import move
import urllib2
import time
import imageio # This needs to be installed first 'pip install imageio'
########################
CHECKPOINT_DIR = 'checkpoints'
########################
def checkFiles(*filenames):
for filename in filenames:
if not os.path.exists(filename):
return False
return True
#########################
def convertHexToACII(str):
return re.sub(r'\%([A-Z0-9][A-Z0-9])', lambda match: "{0}".format(match.group(1).decode("hex")), str)
#######################
class ReadTextFile(Module):
def __init__(self, file, output):
self.file = file
self.output = output
if checkFiles(file):
self.ready = True
def run(self):
copyfile(self.file, self.output)
#################
class WriteTextFile(Module):
def __init__(self, file, input):
self.file = file
self.input = input
self.ready = checkFiles(input)
def run(self):
copyfile(self.input, self.file)
###################
class ConcatenateTextFiles(Module):
def __init__(self, input_1, input_2, output):
self.input_1 = input_1
self.input_2 = input_2
self.output = output
if checkFiles(input_1, input_2):
self.ready = True
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input_1, 'rU'):
print >> outfile, line.strip()
for line in open(self.input_2, 'rU'):
print >> outfile, line.strip()
########################
class SplitSentences(Module):
def __init__(self, input, output):
self.input = input
self.output = output
if checkFiles(input):
self.ready = True
def run(self):
parser = re.compile(r'([\?\.\!:])')
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
lines = [s.strip() for s in parser.sub(r'\1\n', line).splitlines()]
for sent in lines:
if len(sent) > 0:
print >> outfile, sent
#######
class RemoveEmptyLines(Module):
def __init__(self, input, output):
self.input = input
self.output = output
if checkFiles(input):
self.ready = True
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
if len(line.strip()) > 0:
print >> outfile, line.strip()
############
class StripLines(Module):
def __init__(self, input, output):
self.input = input
self.output = output
if checkFiles(input):
self.ready = True
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
if len(line.strip()) > 0:
print >> outfile, line.strip()
##############
class ReplaceCharacters(Module):
def __init__(self, input, output, find, replace):
self.input = input
self.output = output
self.find = find
self.replace = replace
if checkFiles(input):
self.ready = True
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
print >> outfile, line.replace(self.find, self.replace)
##################
class MakeTrainTestData(Module):
def __init__(self, data, training_percent, training_data, testing_data):
self.data = data
self.training_percent = training_percent
self.training_data = training_data
self.testing_data = testing_data
if checkFiles(data):
self.ready = True
def run(self):
lines = []
for line in open(self.data, 'rU'):
lines.append(line)
cut = int(len(lines)*self.training_percent)
with open(self.training_data, 'w') as outfile:
for i in range(cut):
print >> outfile, lines[i]
with open(self.testing_data, 'w') as outfile:
for i in range(len(lines)-cut):
print >> outfile, lines[cut+i]
class MakeTransTrainTestData(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
self.data_y = data_y
self.training_percent = training_percent
self.training_x_data = training_x_data
self.training_y_data = training_y_data
self.testing_x_data = testing_x_data
self.testing_y_data = testing_y_data
if checkFiles(data_x, data_y):
self.ready = True
def run(self):
lines1 = []
lines2 = []
for line in open(self.data_x, 'rU'):
lines1.append(line)
for line in open(self.data_y, 'rU'):
lines2.append(line)
cut = int(len(lines1)*self.training_percent)
with open(self.training_x_data, 'w') as outfile:
for i in range(cut):
print >> outfile, lines1[i]
with open(self.training_y_data, 'w') as outfile:
for i in range(cut):
print >> outfile, lines2[i]
with open(self.testing_x_data, 'w') as outfile:
for i in range(len(lines1)-cut):
print >> outfile, lines1[cut+i]
with open(self.testing_y_data, 'w') as outfile:
for i in range(len(lines2)-cut):
print >> outfile, lines2[cut+i]
########################
class ReadWikipedia(Module):
def __init__(self, wiki_directory, pattern, categories, out_file, titles_file, break_sentences = False):
self.wiki_directory = wiki_directory
self.pattern = pattern
self.out_file = out_file
self.titles_file = titles_file
self.break_sentences = break_sentences
self.categories = categories
if checkFiles(wiki_directory):
self.ready = True
def run(self):
import readWikipedia
readWikipedia.ReadWikipedia(self.wiki_directory, self.pattern, self.categories, self.out_file, self.titles_file, self.break_sentences)
#########################
class SplitLines(Module):
def __init__(self, input, output1, output2, character):
self.input = input
self.output1 = output1
self.output2 = output2
self.character = character
if checkFiles(input):
self.ready = True
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:
print >> outfile1, line.strip()
with open(self.output2, 'w') as outfile2:
for line in data2:
print >> outfile2, line.strip()
#########################
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 MakeLSTMDictionary(Module):
def __init__(self, data, dictionary, history = 25):
self.data = data
self.dictionary = dictionary
self.history = history
def run(self):
lstm.MakeLSTMDictionary(self.data, self.dictionary, self.history)
'''
##########################
class CharRNN_Train(Module):
def __init__(self, data, model, dictionary, history = 25, layers = 3, epochs = 10, hidden_nodes = 512):
self.data = data
self.model = model
self.dictionary = dictionary
self.history = history
self.layers = layers
self.epochs = epochs
self.hidden_nodes = hidden_nodes
#self.dropout = dropout
if checkFiles(data):
self.ready = True
def run(self):
import lstm
lstm.CharacterLSTM_Train(self.data, self.model, self.dictionary, self.history, self.layers, self.epochs, self.hidden_nodes)
copyfile('temp/checkpoint', self.model)
##########################
class CharRNN_Train_More(Module):
def __init__(self, data, in_model, out_model, dictionary, history = 25, layers = 3, epochs = 10, hidden_nodes = 512):
self.data = data
self.in_model = in_model
self.out_model = out_model
self.dictionary = dictionary
self.history = history
self.layers = layers
self.epochs = epochs
self.hidden_nodes = hidden_nodes
#self.dropout = dropout
if checkFiles(data, in_model, directory):
self.ready = True
def run(self):
import lstm
lstm.CharacterLSTM_Train_More(self.data, self.in_model, self.dictionary, self.out_model, self.history, self.layers, self.epochs, self.hidden_nodes)
copyfile('temp/checkpoint', self.out_model)
#########################
class CharRNN_Run(Module):
def __init__(self, seed, dictionary, model, output, steps = 600, layers = 3, hidden_nodes = 512, history = 25, temperature = 0.5):
self.seed = seed
self.dictionary = dictionary
self.model = model
self.steps = steps
self.layers = layers
self.hidden_nodes = hidden_nodes
self.history = history
self.temperature = temperature
self.output = output
if checkFiles(seed, dictionary, model):
self.ready = True
def run(self):
import lstm
file = open(self.seed, 'r')
seed = file.read()
file.close()
copyfile(self.model, 'temp/checkpoint')
result = lstm.CharacterLSTM_Run(seed, self.dictionary, self.model, self.output, self.steps, self.layers, self.hidden_nodes, self.history, self.temperature)
with open(self.output, 'w') as outfile:
print >> outfile, result
############################
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, output, length):
self.input = input
self.output = output
self.length = length
if checkFiles(input):
self.ready = True
def run(self):
sequence = ''
import lstm
sequence = lstm.random_sequence_from_textfile(self.input, self.length)
with open(self.output, 'w') as f:
print >> f, sequence.strip()
############################################
class MakeString(Module):
def __init__(self, string, output):
self.string = string
self.output = output
def run(self):
with open(self.output, 'w') as f:
print >> f, self.string.strip()
###############################################
class UserInput(Module):
def __init__(self, prompt, output):
self.prompt = prompt
self.output = output
def run(self):
prompt = self.prompt
if len(self.prompt) == 0:
prompt = 'prompt: '
s = raw_input(prompt)
with open(self.output, 'w') as f:
print >> f, s
###################################################
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(model, 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 ParseWords(Module):
def __init__(self, input, output):
from stanford_corenlp_python import StanfordNLP # https://github.com/dasmith/stanford-corenlp-python
self.input = input
self.output = output
def run(self):
stanfordParser = StanfordNLP()
print stanfordParser
lines = []
new_lines = []
final_lines = []
for line in open(self.input, 'rU'):
lines.append(line)
parser = re.compile(r'([\?\.\!:])')
for line in lines:
split_lines = [s.strip() for s in parser.sub(r'\1\n', line).splitlines()]
for sent in split_lines:
if len(sent) > 0:
new_lines.append(sent)
for line in new_lines:
line = re.sub(r'\xe2\x80\x94', '-', line)
print line
try:
result = stanfordParser.parse(line)
sentences = result['sentences']
for sent_struct in sentences:
words = sent_struct['words']
parsed = map(lambda x: x[0], words)
text = ''
for word in parsed:
text = text + word + ' '
print text
final_lines.append(text.strip())
except:
print "error"
with open(self.output, 'w') as outfile:
for line in lines:
print >> outfile, line
'''
####################################
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
if checkFiles(wiki_directory, input):
self.ready = True
def run(self):
import readWikipedia
pattern = ''
first = True
for line in open(self.input, 'rU'):
line = line.strip()
if first:
if len(line) > 0:
pattern = line
first = False
else:
if len(line) > 0:
pattern = pattern + '|' + line
if len(self.section_name.strip()) > 0:
pattern = pattern + ':' + self.section_name.strip()
print pattern
readWikipedia.ReadWikipedia(self.wiki_directory, pattern, self.categories, self.output, 'temp/pickfromwikipediatitles', self.break_sentences)
#######################################
class RandomizeLines(Module):
def __init__(self, input, output):
self.input = input
self.output = output
if checkFiles(input):
self.ready = True
def run(self):
lines = []
for line in open(self.input, 'rU'):
lines.append(line)
random.shuffle(lines)
with open(self.output, 'w') as outfile:
for line in lines:
print >> outfile, line.strip()
#########################################
class RemoveTags(Module):
def __init__(self, input, output):
self.input = input
self.output = output
if checkFiles(input):
self.ready = True
def run(self):
lines = []
for line in open(self.input, 'rU'):
line = re.sub('<[^<]+?>', '', line)
if len(line) > 0:
lines.append(line.strip())
with open(self.output, 'w') as outfile:
for line in lines:
print >> outfile, line
##############################
class MakeLowercase(Module):
def __init__(self, input, output):
self.input = input
self.output = output
if checkFiles(input):
self.ready = True
def run(self):
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
print >> outfile, line.lower().strip()
################################
class Wordify(Module):
def __init__(self, input, output):
self.input = input
self.output = output
if checkFiles(input):
self.ready = True
def run(self):
parser = re.compile(r'([\,\.\?\!\'\"\(\)\[\]\{\}])')
with open(self.output, 'w') as outfile:
for line in open(self.input, 'rU'):
line = parser.sub(r' \1 ', line)
line = re.sub('[ ][ ]*', ' ', line) # might put too many spaces in
print >> outfile, line.strip()
#####################################
class SaveModel(Module):
def __init__(self, model, file):
self.model = model
self.file = file
def run(self):
split_model_path = os.path.split(self.model)
model_directory = split_model_path[0]
model_file = split_model_path[1]
split_file_path = os.path.split(self.file)
target_file = split_file_path[1]
target_directory = split_file_path[0]
if len(target_directory) == 0:
target_directory = '.'
for f in os.listdir(model_directory):
match = re.match(model_file, f)
if match is not None:
f_rest = f[len(model_file):]
filename = os.path.join(model_directory, f)
if not os.path.isdir(filename):
copyfile(filename, os.path.join(target_directory, target_file) + f_rest)
with open(self.file, 'w') as f:
print >> f, 'model_checkpoint_path: "'+ target_file + '"'
print >> f, 'all_model_checkpoint_paths: "' + target_file + '"'
###################################
class SaveDictionary(Module):
def __init__(self, dictionary, file):
self.dictionary = dictionary
self.file = file
def run(self):
copyfile(self.dictionary, self.file)
#####################################
class LoadDictionary(Module):
def __init__(self, file, dictionary):
self.dictionary = dictionary
self.file = file
if checkFiles(dictionary):
self.ready = True
def run(self):
copyfile(self.file, self.dictionary)
######################################
class LoadModel(Module):
def __init__(self, file, model):
self.file = file
self.model = model