tbsrn.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This code is refer from:
  16. https://github.com/FudanVI/FudanOCR/blob/main/scene-text-telescope/model/tbsrn.py
  17. """
  18. import math
  19. import warnings
  20. import numpy as np
  21. import paddle
  22. from paddle import nn
  23. import string
  24. warnings.filterwarnings("ignore")
  25. from .tps_spatial_transformer import TPSSpatialTransformer
  26. from .stn import STN as STNHead
  27. from .tsrn import GruBlock, mish, UpsampleBLock
  28. from ppocr.modeling.heads.sr_rensnet_transformer import Transformer, LayerNorm, \
  29. PositionwiseFeedForward, MultiHeadedAttention
  30. def positionalencoding2d(d_model, height, width):
  31. """
  32. :param d_model: dimension of the model
  33. :param height: height of the positions
  34. :param width: width of the positions
  35. :return: d_model*height*width position matrix
  36. """
  37. if d_model % 4 != 0:
  38. raise ValueError("Cannot use sin/cos positional encoding with "
  39. "odd dimension (got dim={:d})".format(d_model))
  40. pe = paddle.zeros([d_model, height, width])
  41. # Each dimension use half of d_model
  42. d_model = int(d_model / 2)
  43. div_term = paddle.exp(paddle.arange(0., d_model, 2) *
  44. -(math.log(10000.0) / d_model))
  45. pos_w = paddle.arange(0., width, dtype='float32').unsqueeze(1)
  46. pos_h = paddle.arange(0., height, dtype='float32').unsqueeze(1)
  47. pe[0:d_model:2, :, :] = paddle.sin(pos_w * div_term).transpose([1, 0]).unsqueeze(1).tile([1, height, 1])
  48. pe[1:d_model:2, :, :] = paddle.cos(pos_w * div_term).transpose([1, 0]).unsqueeze(1).tile([1, height, 1])
  49. pe[d_model::2, :, :] = paddle.sin(pos_h * div_term).transpose([1, 0]).unsqueeze(2).tile([1, 1, width])
  50. pe[d_model + 1::2, :, :] = paddle.cos(pos_h * div_term).transpose([1, 0]).unsqueeze(2).tile([1, 1, width])
  51. return pe
  52. class FeatureEnhancer(nn.Layer):
  53. def __init__(self):
  54. super(FeatureEnhancer, self).__init__()
  55. self.multihead = MultiHeadedAttention(h=4, d_model=128, dropout=0.1)
  56. self.mul_layernorm1 = LayerNorm(features=128)
  57. self.pff = PositionwiseFeedForward(128, 128)
  58. self.mul_layernorm3 = LayerNorm(features=128)
  59. self.linear = nn.Linear(128, 64)
  60. def forward(self, conv_feature):
  61. '''
  62. text : (batch, seq_len, embedding_size)
  63. global_info: (batch, embedding_size, 1, 1)
  64. conv_feature: (batch, channel, H, W)
  65. '''
  66. batch = conv_feature.shape[0]
  67. position2d = positionalencoding2d(64, 16, 64).cast('float32').unsqueeze(0).reshape([1, 64, 1024])
  68. position2d = position2d.tile([batch, 1, 1])
  69. conv_feature = paddle.concat([conv_feature, position2d], 1) # batch, 128(64+64), 32, 128
  70. result = conv_feature.transpose([0, 2, 1])
  71. origin_result = result
  72. result = self.mul_layernorm1(origin_result + self.multihead(result, result, result, mask=None)[0])
  73. origin_result = result
  74. result = self.mul_layernorm3(origin_result + self.pff(result))
  75. result = self.linear(result)
  76. return result.transpose([0, 2, 1])
  77. def str_filt(str_, voc_type):
  78. alpha_dict = {
  79. 'digit': string.digits,
  80. 'lower': string.digits + string.ascii_lowercase,
  81. 'upper': string.digits + string.ascii_letters,
  82. 'all': string.digits + string.ascii_letters + string.punctuation
  83. }
  84. if voc_type == 'lower':
  85. str_ = str_.lower()
  86. for char in str_:
  87. if char not in alpha_dict[voc_type]:
  88. str_ = str_.replace(char, '')
  89. str_ = str_.lower()
  90. return str_
  91. class TBSRN(nn.Layer):
  92. def __init__(self,
  93. in_channels=3,
  94. scale_factor=2,
  95. width=128,
  96. height=32,
  97. STN=True,
  98. srb_nums=5,
  99. mask=False,
  100. hidden_units=32,
  101. infer_mode=False):
  102. super(TBSRN, self).__init__()
  103. in_planes = 3
  104. if mask:
  105. in_planes = 4
  106. assert math.log(scale_factor, 2) % 1 == 0
  107. upsample_block_num = int(math.log(scale_factor, 2))
  108. self.block1 = nn.Sequential(
  109. nn.Conv2D(in_planes, 2 * hidden_units, kernel_size=9, padding=4),
  110. nn.PReLU()
  111. # nn.ReLU()
  112. )
  113. self.srb_nums = srb_nums
  114. for i in range(srb_nums):
  115. setattr(self, 'block%d' % (i + 2), RecurrentResidualBlock(2 * hidden_units))
  116. setattr(self, 'block%d' % (srb_nums + 2),
  117. nn.Sequential(
  118. nn.Conv2D(2 * hidden_units, 2 * hidden_units, kernel_size=3, padding=1),
  119. nn.BatchNorm2D(2 * hidden_units)
  120. ))
  121. # self.non_local = NonLocalBlock2D(64, 64)
  122. block_ = [UpsampleBLock(2 * hidden_units, 2) for _ in range(upsample_block_num)]
  123. block_.append(nn.Conv2D(2 * hidden_units, in_planes, kernel_size=9, padding=4))
  124. setattr(self, 'block%d' % (srb_nums + 3), nn.Sequential(*block_))
  125. self.tps_inputsize = [height // scale_factor, width // scale_factor]
  126. tps_outputsize = [height // scale_factor, width // scale_factor]
  127. num_control_points = 20
  128. tps_margins = [0.05, 0.05]
  129. self.stn = STN
  130. self.out_channels = in_channels
  131. if self.stn:
  132. self.tps = TPSSpatialTransformer(
  133. output_image_size=tuple(tps_outputsize),
  134. num_control_points=num_control_points,
  135. margins=tuple(tps_margins))
  136. self.stn_head = STNHead(
  137. in_channels=in_planes,
  138. num_ctrlpoints=num_control_points,
  139. activation='none')
  140. self.infer_mode = infer_mode
  141. self.english_alphabet = '-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  142. self.english_dict = {}
  143. for index in range(len(self.english_alphabet)):
  144. self.english_dict[self.english_alphabet[index]] = index
  145. transformer = Transformer(alphabet='-0123456789abcdefghijklmnopqrstuvwxyz')
  146. self.transformer = transformer
  147. for param in self.transformer.parameters():
  148. param.trainable = False
  149. def label_encoder(self, label):
  150. batch = len(label)
  151. length = [len(i) for i in label]
  152. length_tensor = paddle.to_tensor(length, dtype='int64')
  153. max_length = max(length)
  154. input_tensor = np.zeros((batch, max_length))
  155. for i in range(batch):
  156. for j in range(length[i] - 1):
  157. input_tensor[i][j + 1] = self.english_dict[label[i][j]]
  158. text_gt = []
  159. for i in label:
  160. for j in i:
  161. text_gt.append(self.english_dict[j])
  162. text_gt = paddle.to_tensor(text_gt, dtype='int64')
  163. input_tensor = paddle.to_tensor(input_tensor, dtype='int64')
  164. return length_tensor, input_tensor, text_gt
  165. def forward(self, x):
  166. output = {}
  167. if self.infer_mode:
  168. output["lr_img"] = x
  169. y = x
  170. else:
  171. output["lr_img"] = x[0]
  172. output["hr_img"] = x[1]
  173. y = x[0]
  174. if self.stn and self.training:
  175. _, ctrl_points_x = self.stn_head(y)
  176. y, _ = self.tps(y, ctrl_points_x)
  177. block = {'1': self.block1(y)}
  178. for i in range(self.srb_nums + 1):
  179. block[str(i + 2)] = getattr(self,
  180. 'block%d' % (i + 2))(block[str(i + 1)])
  181. block[str(self.srb_nums + 3)] = getattr(self, 'block%d' % (self.srb_nums + 3)) \
  182. ((block['1'] + block[str(self.srb_nums + 2)]))
  183. sr_img = paddle.tanh(block[str(self.srb_nums + 3)])
  184. output["sr_img"] = sr_img
  185. if self.training:
  186. hr_img = x[1]
  187. # add transformer
  188. label = [str_filt(i, 'lower') + '-' for i in x[2]]
  189. length_tensor, input_tensor, text_gt = self.label_encoder(label)
  190. hr_pred, word_attention_map_gt, hr_correct_list = self.transformer(hr_img, length_tensor,
  191. input_tensor)
  192. sr_pred, word_attention_map_pred, sr_correct_list = self.transformer(sr_img, length_tensor,
  193. input_tensor)
  194. output["hr_img"] = hr_img
  195. output["hr_pred"] = hr_pred
  196. output["text_gt"] = text_gt
  197. output["word_attention_map_gt"] = word_attention_map_gt
  198. output["sr_pred"] = sr_pred
  199. output["word_attention_map_pred"] = word_attention_map_pred
  200. return output
  201. class RecurrentResidualBlock(nn.Layer):
  202. def __init__(self, channels):
  203. super(RecurrentResidualBlock, self).__init__()
  204. self.conv1 = nn.Conv2D(channels, channels, kernel_size=3, padding=1)
  205. self.bn1 = nn.BatchNorm2D(channels)
  206. self.gru1 = GruBlock(channels, channels)
  207. # self.prelu = nn.ReLU()
  208. self.prelu = mish()
  209. self.conv2 = nn.Conv2D(channels, channels, kernel_size=3, padding=1)
  210. self.bn2 = nn.BatchNorm2D(channels)
  211. self.gru2 = GruBlock(channels, channels)
  212. self.feature_enhancer = FeatureEnhancer()
  213. for p in self.parameters():
  214. if p.dim() > 1:
  215. paddle.nn.initializer.XavierUniform(p)
  216. def forward(self, x):
  217. residual = self.conv1(x)
  218. residual = self.bn1(residual)
  219. residual = self.prelu(residual)
  220. residual = self.conv2(residual)
  221. residual = self.bn2(residual)
  222. size = residual.shape
  223. residual = residual.reshape([size[0], size[1], -1])
  224. residual = self.feature_enhancer(residual)
  225. residual = residual.reshape([size[0], size[1], size[2], size[3]])
  226. return x + residual