tbsrn.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 (
  29. Transformer,
  30. LayerNorm,
  31. PositionwiseFeedForward,
  32. MultiHeadedAttention,
  33. )
  34. def positionalencoding2d(d_model, height, width):
  35. """
  36. :param d_model: dimension of the model
  37. :param height: height of the positions
  38. :param width: width of the positions
  39. :return: d_model*height*width position matrix
  40. """
  41. if d_model % 4 != 0:
  42. raise ValueError(
  43. "Cannot use sin/cos positional encoding with "
  44. "odd dimension (got dim={:d})".format(d_model)
  45. )
  46. pe = paddle.zeros([d_model, height, width])
  47. # Each dimension use half of d_model
  48. d_model = int(d_model / 2)
  49. div_term = paddle.exp(
  50. paddle.arange(0.0, d_model, 2, dtype="int64") * -(math.log(10000.0) / d_model)
  51. )
  52. pos_w = paddle.arange(0.0, width, dtype="float32").unsqueeze(1)
  53. pos_h = paddle.arange(0.0, height, dtype="float32").unsqueeze(1)
  54. pe[0:d_model:2, :, :] = (
  55. paddle.sin(pos_w * div_term).transpose([1, 0]).unsqueeze(1).tile([1, height, 1])
  56. )
  57. pe[1:d_model:2, :, :] = (
  58. paddle.cos(pos_w * div_term).transpose([1, 0]).unsqueeze(1).tile([1, height, 1])
  59. )
  60. pe[d_model::2, :, :] = (
  61. paddle.sin(pos_h * div_term).transpose([1, 0]).unsqueeze(2).tile([1, 1, width])
  62. )
  63. pe[d_model + 1 :: 2, :, :] = (
  64. paddle.cos(pos_h * div_term).transpose([1, 0]).unsqueeze(2).tile([1, 1, width])
  65. )
  66. return pe
  67. class FeatureEnhancer(nn.Layer):
  68. def __init__(self):
  69. super(FeatureEnhancer, self).__init__()
  70. self.multihead = MultiHeadedAttention(h=4, d_model=128, dropout=0.1)
  71. self.mul_layernorm1 = LayerNorm(features=128)
  72. self.pff = PositionwiseFeedForward(128, 128)
  73. self.mul_layernorm3 = LayerNorm(features=128)
  74. self.linear = nn.Linear(128, 64)
  75. def forward(self, conv_feature):
  76. """
  77. text : (batch, seq_len, embedding_size)
  78. global_info: (batch, embedding_size, 1, 1)
  79. conv_feature: (batch, channel, H, W)
  80. """
  81. batch = conv_feature.shape[0]
  82. position2d = (
  83. positionalencoding2d(64, 16, 64)
  84. .cast("float32")
  85. .unsqueeze(0)
  86. .reshape([1, 64, 1024])
  87. )
  88. position2d = position2d.tile([batch, 1, 1])
  89. conv_feature = paddle.concat(
  90. [conv_feature, position2d], 1
  91. ) # batch, 128(64+64), 32, 128
  92. result = conv_feature.transpose([0, 2, 1])
  93. origin_result = result
  94. result = self.mul_layernorm1(
  95. origin_result + self.multihead(result, result, result, mask=None)[0]
  96. )
  97. origin_result = result
  98. result = self.mul_layernorm3(origin_result + self.pff(result))
  99. result = self.linear(result)
  100. return result.transpose([0, 2, 1])
  101. def str_filt(str_, voc_type):
  102. alpha_dict = {
  103. "digit": string.digits,
  104. "lower": string.digits + string.ascii_lowercase,
  105. "upper": string.digits + string.ascii_letters,
  106. "all": string.digits + string.ascii_letters + string.punctuation,
  107. }
  108. if voc_type == "lower":
  109. str_ = str_.lower()
  110. for char in str_:
  111. if char not in alpha_dict[voc_type]:
  112. str_ = str_.replace(char, "")
  113. str_ = str_.lower()
  114. return str_
  115. class TBSRN(nn.Layer):
  116. def __init__(
  117. self,
  118. in_channels=3,
  119. scale_factor=2,
  120. width=128,
  121. height=32,
  122. STN=True,
  123. srb_nums=5,
  124. mask=False,
  125. hidden_units=32,
  126. infer_mode=False,
  127. ):
  128. super(TBSRN, self).__init__()
  129. in_planes = 3
  130. if mask:
  131. in_planes = 4
  132. assert math.log(scale_factor, 2) % 1 == 0
  133. upsample_block_num = int(math.log(scale_factor, 2))
  134. self.block1 = nn.Sequential(
  135. nn.Conv2D(in_planes, 2 * hidden_units, kernel_size=9, padding=4),
  136. nn.PReLU(),
  137. # nn.ReLU()
  138. )
  139. self.srb_nums = srb_nums
  140. for i in range(srb_nums):
  141. setattr(self, "block%d" % (i + 2), RecurrentResidualBlock(2 * hidden_units))
  142. setattr(
  143. self,
  144. "block%d" % (srb_nums + 2),
  145. nn.Sequential(
  146. nn.Conv2D(2 * hidden_units, 2 * hidden_units, kernel_size=3, padding=1),
  147. nn.BatchNorm2D(2 * hidden_units),
  148. ),
  149. )
  150. # self.non_local = NonLocalBlock2D(64, 64)
  151. block_ = [UpsampleBLock(2 * hidden_units, 2) for _ in range(upsample_block_num)]
  152. block_.append(nn.Conv2D(2 * hidden_units, in_planes, kernel_size=9, padding=4))
  153. setattr(self, "block%d" % (srb_nums + 3), nn.Sequential(*block_))
  154. self.tps_inputsize = [height // scale_factor, width // scale_factor]
  155. tps_outputsize = [height // scale_factor, width // scale_factor]
  156. num_control_points = 20
  157. tps_margins = [0.05, 0.05]
  158. self.stn = STN
  159. self.out_channels = in_channels
  160. if self.stn:
  161. self.tps = TPSSpatialTransformer(
  162. output_image_size=tuple(tps_outputsize),
  163. num_control_points=num_control_points,
  164. margins=tuple(tps_margins),
  165. )
  166. self.stn_head = STNHead(
  167. in_channels=in_planes,
  168. num_ctrlpoints=num_control_points,
  169. activation="none",
  170. )
  171. self.infer_mode = infer_mode
  172. self.english_alphabet = (
  173. "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  174. )
  175. self.english_dict = {}
  176. for index in range(len(self.english_alphabet)):
  177. self.english_dict[self.english_alphabet[index]] = index
  178. transformer = Transformer(alphabet="-0123456789abcdefghijklmnopqrstuvwxyz")
  179. self.transformer = transformer
  180. for param in self.transformer.parameters():
  181. param.trainable = False
  182. def label_encoder(self, label):
  183. batch = len(label)
  184. length = [len(i) for i in label]
  185. length_tensor = paddle.to_tensor(length, dtype="int64")
  186. max_length = max(length)
  187. input_tensor = np.zeros((batch, max_length))
  188. for i in range(batch):
  189. for j in range(length[i] - 1):
  190. input_tensor[i][j + 1] = self.english_dict[label[i][j]]
  191. text_gt = []
  192. for i in label:
  193. for j in i:
  194. text_gt.append(self.english_dict[j])
  195. text_gt = paddle.to_tensor(text_gt, dtype="int64")
  196. input_tensor = paddle.to_tensor(input_tensor, dtype="int64")
  197. return length_tensor, input_tensor, text_gt
  198. def forward(self, x):
  199. output = {}
  200. if self.infer_mode:
  201. output["lr_img"] = x
  202. y = x
  203. else:
  204. output["lr_img"] = x[0]
  205. output["hr_img"] = x[1]
  206. y = x[0]
  207. if self.stn and self.training:
  208. _, ctrl_points_x = self.stn_head(y)
  209. y, _ = self.tps(y, ctrl_points_x)
  210. block = {"1": self.block1(y)}
  211. for i in range(self.srb_nums + 1):
  212. block[str(i + 2)] = getattr(self, "block%d" % (i + 2))(block[str(i + 1)])
  213. block[str(self.srb_nums + 3)] = getattr(self, "block%d" % (self.srb_nums + 3))(
  214. (block["1"] + block[str(self.srb_nums + 2)])
  215. )
  216. sr_img = paddle.tanh(block[str(self.srb_nums + 3)])
  217. output["sr_img"] = sr_img
  218. if self.training:
  219. hr_img = x[1]
  220. # add transformer
  221. label = [str_filt(i, "lower") + "-" for i in x[2]]
  222. length_tensor, input_tensor, text_gt = self.label_encoder(label)
  223. hr_pred, word_attention_map_gt, hr_correct_list = self.transformer(
  224. hr_img, length_tensor, input_tensor
  225. )
  226. sr_pred, word_attention_map_pred, sr_correct_list = self.transformer(
  227. sr_img, length_tensor, input_tensor
  228. )
  229. output["hr_img"] = hr_img
  230. output["hr_pred"] = hr_pred
  231. output["text_gt"] = text_gt
  232. output["word_attention_map_gt"] = word_attention_map_gt
  233. output["sr_pred"] = sr_pred
  234. output["word_attention_map_pred"] = word_attention_map_pred
  235. return output
  236. class RecurrentResidualBlock(nn.Layer):
  237. def __init__(self, channels):
  238. super(RecurrentResidualBlock, self).__init__()
  239. self.conv1 = nn.Conv2D(channels, channels, kernel_size=3, padding=1)
  240. self.bn1 = nn.BatchNorm2D(channels)
  241. self.gru1 = GruBlock(channels, channels)
  242. # self.prelu = nn.ReLU()
  243. self.prelu = mish()
  244. self.conv2 = nn.Conv2D(channels, channels, kernel_size=3, padding=1)
  245. self.bn2 = nn.BatchNorm2D(channels)
  246. self.gru2 = GruBlock(channels, channels)
  247. self.feature_enhancer = FeatureEnhancer()
  248. for p in self.parameters():
  249. if p.dim() > 1:
  250. paddle.nn.initializer.XavierUniform(p)
  251. def forward(self, x):
  252. residual = self.conv1(x)
  253. residual = self.bn1(residual)
  254. residual = self.prelu(residual)
  255. residual = self.conv2(residual)
  256. residual = self.bn2(residual)
  257. size = residual.shape
  258. residual = residual.reshape([size[0], size[1], -1])
  259. residual = self.feature_enhancer(residual)
  260. residual = residual.reshape([size[0], size[1], size[2], size[3]])
  261. return x + residual