3morrrrr commited on
Commit
656db99
·
verified ·
1 Parent(s): fdfe94f

Update hand.py

Browse files
Files changed (1) hide show
  1. hand.py +152 -149
hand.py CHANGED
@@ -1,150 +1,153 @@
1
- import drawing
2
- from rnn import rnn
3
-
4
-
5
- import numpy as np
6
- import svgwrite
7
-
8
-
9
- import logging
10
- import os
11
-
12
-
13
- class Hand(object):
14
-
15
- def __init__(self):
16
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
17
- self.nn = rnn(
18
- log_dir='logs',
19
- checkpoint_dir='checkpoints',
20
- prediction_dir='predictions',
21
- learning_rates=[.0001, .00005, .00002],
22
- batch_sizes=[32, 64, 64],
23
- patiences=[1500, 1000, 500],
24
- beta1_decays=[.9, .9, .9],
25
- validation_batch_size=32,
26
- optimizer='rms',
27
- num_training_steps=100000,
28
- warm_start_init_step=17900,
29
- regularization_constant=0.0,
30
- keep_prob=1.0,
31
- enable_parameter_averaging=False,
32
- min_steps_to_checkpoint=2000,
33
- log_interval=20,
34
- logging_level=logging.CRITICAL,
35
- grad_clip=10,
36
- lstm_size=400,
37
- output_mixture_components=20,
38
- attention_mixture_components=10
39
- )
40
- self.nn.restore()
41
-
42
- def write(self, filename, lines, biases=None, styles=None, stroke_colors=None, stroke_widths=None):
43
- valid_char_set = set(drawing.alphabet)
44
- for line_num, line in enumerate(lines):
45
- if len(line) > 75:
46
- raise ValueError(
47
- (
48
- "Each line must be at most 75 characters. "
49
- "Line {} contains {}"
50
- ).format(line_num, len(line))
51
- )
52
-
53
- for char in line:
54
- if char not in valid_char_set:
55
- raise ValueError(
56
- (
57
- "Invalid character {} detected in line {}. "
58
- "Valid character set is {}"
59
- ).format(char, line_num, valid_char_set)
60
- )
61
-
62
- strokes = self._sample(lines, biases=biases, styles=styles)
63
- self._draw(strokes, lines, filename, stroke_colors=stroke_colors, stroke_widths=stroke_widths)
64
-
65
- def _sample(self, lines, biases=None, styles=None):
66
- num_samples = len(lines)
67
- max_tsteps = 40*max([len(i) for i in lines])
68
- biases = biases if biases is not None else [0.5]*num_samples
69
-
70
- x_prime = np.zeros([num_samples, 1200, 3])
71
- x_prime_len = np.zeros([num_samples])
72
- chars = np.zeros([num_samples, 120])
73
- chars_len = np.zeros([num_samples])
74
-
75
- if styles is not None:
76
- for i, (cs, style) in enumerate(zip(lines, styles)):
77
- x_p = np.load('styles/style-{}-strokes.npy'.format(style))
78
- c_p = np.load('styles/style-{}-chars.npy'.format(style)).tostring().decode('utf-8')
79
-
80
- c_p = str(c_p) + " " + cs
81
- c_p = drawing.encode_ascii(c_p)
82
- c_p = np.array(c_p)
83
-
84
- x_prime[i, :len(x_p), :] = x_p
85
- x_prime_len[i] = len(x_p)
86
- chars[i, :len(c_p)] = c_p
87
- chars_len[i] = len(c_p)
88
-
89
- else:
90
- for i in range(num_samples):
91
- encoded = drawing.encode_ascii(lines[i])
92
- chars[i, :len(encoded)] = encoded
93
- chars_len[i] = len(encoded)
94
-
95
- [samples] = self.nn.session.run(
96
- [self.nn.sampled_sequence],
97
- feed_dict={
98
- self.nn.prime: styles is not None,
99
- self.nn.x_prime: x_prime,
100
- self.nn.x_prime_len: x_prime_len,
101
- self.nn.num_samples: num_samples,
102
- self.nn.sample_tsteps: max_tsteps,
103
- self.nn.c: chars,
104
- self.nn.c_len: chars_len,
105
- self.nn.bias: biases
106
- }
107
- )
108
- samples = [sample[~np.all(sample == 0.0, axis=1)] for sample in samples]
109
- return samples
110
-
111
- def _draw(self, strokes, lines, filename, stroke_colors=None, stroke_widths=None):
112
- stroke_colors = stroke_colors or ['black']*len(lines)
113
- stroke_widths = stroke_widths or [2]*len(lines)
114
-
115
- line_height = 60
116
- view_width = 1000
117
- view_height = line_height*(len(strokes) + 1)
118
-
119
- dwg = svgwrite.Drawing(filename=filename)
120
- dwg.viewbox(width=view_width, height=view_height)
121
- dwg.add(dwg.rect(insert=(0, 0), size=(view_width, view_height), fill='white'))
122
-
123
- initial_coord = np.array([0, -(3*line_height / 4)])
124
- for offsets, line, color, width in zip(strokes, lines, stroke_colors, stroke_widths):
125
-
126
- if not line:
127
- initial_coord[1] -= line_height
128
- continue
129
-
130
- offsets[:, :2] *= 1.5
131
- strokes = drawing.offsets_to_coords(offsets)
132
- strokes = drawing.denoise(strokes)
133
- strokes[:, :2] = drawing.align(strokes[:, :2])
134
-
135
- strokes[:, 1] *= -1
136
- strokes[:, :2] -= strokes[:, :2].min() + initial_coord
137
- strokes[:, 0] += (view_width - strokes[:, 0].max()) / 2
138
-
139
- prev_eos = 1.0
140
- p = "M{},{} ".format(0, 0)
141
- for x, y, eos in zip(*strokes.T):
142
- p += '{}{},{} '.format('M' if prev_eos == 1.0 else 'L', x, y)
143
- prev_eos = eos
144
- path = svgwrite.path.Path(p)
145
- path = path.stroke(color=color, width=width, linecap='round').fill("none")
146
- dwg.add(path)
147
-
148
- initial_coord[1] -= line_height
149
-
 
 
 
150
  dwg.save()
 
1
+ import drawing
2
+ from rnn import rnn
3
+
4
+
5
+ import numpy as np
6
+ import svgwrite
7
+
8
+
9
+ import logging
10
+ import os
11
+
12
+
13
+ class Hand(object):
14
+
15
+ def __init__(self):
16
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
17
+ self.nn = rnn(
18
+ log_dir='logs',
19
+ checkpoint_dir='checkpoints',
20
+ prediction_dir='predictions',
21
+ learning_rates=[.0001, .00005, .00002],
22
+ batch_sizes=[32, 64, 64],
23
+ patiences=[1500, 1000, 500],
24
+ beta1_decays=[.9, .9, .9],
25
+ validation_batch_size=32,
26
+ optimizer='rms',
27
+ num_training_steps=100000,
28
+ warm_start_init_step=17900,
29
+ regularization_constant=0.0,
30
+ keep_prob=1.0,
31
+ enable_parameter_averaging=False,
32
+ min_steps_to_checkpoint=2000,
33
+ log_interval=20,
34
+ logging_level=logging.CRITICAL,
35
+ grad_clip=10,
36
+ lstm_size=400,
37
+ output_mixture_components=20,
38
+ attention_mixture_components=10
39
+ )
40
+ self.nn.restore()
41
+
42
+ def write(self, filename, lines, biases=None, styles=None, stroke_colors=None, stroke_widths=None):
43
+ valid_char_set = set(drawing.alphabet)
44
+ for line_num, line in enumerate(lines):
45
+ if len(line) > 75:
46
+ raise ValueError(
47
+ (
48
+ "Each line must be at most 75 characters. "
49
+ "Line {} contains {}"
50
+ ).format(line_num, len(line))
51
+ )
52
+
53
+ for char in line:
54
+ if char not in valid_char_set:
55
+ raise ValueError(
56
+ (
57
+ "Invalid character {} detected in line {}. "
58
+ "Valid character set is {}"
59
+ ).format(char, line_num, valid_char_set)
60
+ )
61
+
62
+ strokes = self._sample(lines, biases=biases, styles=styles)
63
+ self._draw(strokes, lines, filename, stroke_colors=stroke_colors, stroke_widths=stroke_widths)
64
+
65
+ def _sample(self, lines, biases=None, styles=None):
66
+ num_samples = len(lines)
67
+ max_tsteps = 40*max([len(i) for i in lines])
68
+ biases = biases if biases is not None else [0.5]*num_samples
69
+
70
+ x_prime = np.zeros([num_samples, 1200, 3])
71
+ x_prime_len = np.zeros([num_samples])
72
+ chars = np.zeros([num_samples, 120])
73
+ chars_len = np.zeros([num_samples])
74
+
75
+ if styles is not None:
76
+ for i, (cs, style) in enumerate(zip(lines, styles)):
77
+ x_p = np.load('styles/style-{}-strokes.npy'.format(style))
78
+ c_p = np.load('styles/style-{}-chars.npy'.format(style)).tostring().decode('utf-8')
79
+
80
+ c_p = str(c_p) + " " + cs
81
+ c_p = drawing.encode_ascii(c_p)
82
+ c_p = np.array(c_p)
83
+
84
+ x_prime[i, :len(x_p), :] = x_p
85
+ x_prime_len[i] = len(x_p)
86
+ chars[i, :len(c_p)] = c_p
87
+ chars_len[i] = len(c_p)
88
+
89
+ else:
90
+ for i in range(num_samples):
91
+ encoded = drawing.encode_ascii(lines[i])
92
+ chars[i, :len(encoded)] = encoded
93
+ chars_len[i] = len(encoded)
94
+
95
+ [samples] = self.nn.session.run(
96
+ [self.nn.sampled_sequence],
97
+ feed_dict={
98
+ self.nn.prime: styles is not None,
99
+ self.nn.x_prime: x_prime,
100
+ self.nn.x_prime_len: x_prime_len,
101
+ self.nn.num_samples: num_samples,
102
+ self.nn.sample_tsteps: max_tsteps,
103
+ self.nn.c: chars,
104
+ self.nn.c_len: chars_len,
105
+ self.nn.bias: biases
106
+ }
107
+ )
108
+ samples = [sample[~np.all(sample == 0.0, axis=1)] for sample in samples]
109
+ return samples
110
+
111
+ def _draw(self, strokes, lines, filename, stroke_colors=None, stroke_widths=None):
112
+ stroke_colors = stroke_colors or ['black']*len(lines)
113
+ stroke_widths = stroke_widths or [4]*len(lines) # Increased default from 2 to 4
114
+
115
+ line_height = 80 # Increased from 60 to 80
116
+ view_width = 800 # Reduced from 1000 to 800
117
+ view_height = line_height*(len(strokes) + 1)
118
+
119
+ dwg = svgwrite.Drawing(filename=filename)
120
+ dwg.viewbox(width=view_width, height=view_height)
121
+ dwg.add(dwg.rect(insert=(0, 0), size=(view_width, view_height), fill='white'))
122
+
123
+ initial_coord = np.array([0, -(3*line_height / 4)])
124
+ for offsets, line, color, width in zip(strokes, lines, stroke_colors, stroke_widths):
125
+
126
+ if not line:
127
+ initial_coord[1] -= line_height
128
+ continue
129
+
130
+ offsets[:, :2] *= 3.0 # Increased from 1.5 to 3.0
131
+ strokes = drawing.offsets_to_coords(offsets)
132
+ strokes = drawing.denoise(strokes)
133
+ strokes[:, :2] = drawing.align(strokes[:, :2])
134
+
135
+ strokes[:, 1] *= -1
136
+ strokes[:, :2] -= strokes[:, :2].min() + initial_coord
137
+
138
+ # Adjust centering to make text larger relative to the canvas
139
+ horizontal_padding = 50 # Fixed padding instead of centering
140
+ strokes[:, 0] += horizontal_padding
141
+
142
+ prev_eos = 1.0
143
+ p = "M{},{} ".format(0, 0)
144
+ for x, y, eos in zip(*strokes.T):
145
+ p += '{}{},{} '.format('M' if prev_eos == 1.0 else 'L', x, y)
146
+ prev_eos = eos
147
+ path = svgwrite.path.Path(p)
148
+ path = path.stroke(color=color, width=width, linecap='round').fill("none")
149
+ dwg.add(path)
150
+
151
+ initial_coord[1] -= line_height
152
+
153
  dwg.save()