File size: 161,599 Bytes
bafcf39 e9c4101 bafcf39 e9c4101 bafcf39 eea5c07 bafcf39 641ff3e bafcf39 641ff3e bafcf39 9ae09da bafcf39 34addbf bafcf39 f957846 eea5c07 6319afc bafcf39 6319afc 7907ad4 3bbf593 bafcf39 d60759d bafcf39 a03496e bafcf39 a03496e bafcf39 8652429 34addbf 8652429 7aa4d5f 8652429 34addbf f957846 34addbf f957846 8652429 bafcf39 8652429 bafcf39 ee6b7fb bafcf39 ef4000e bafcf39 ef4000e bafcf39 eea5c07 0ea8b9e bafcf39 f0f9378 ff290e1 0ea8b9e d60759d eea5c07 0ea8b9e eea5c07 0ea8b9e eea5c07 0ea8b9e ee6b7fb 0ea8b9e eea5c07 f0f9378 8235bbb 7907ad4 66e145d 68a91f4 08a3ec3 6319afc 0ea8b9e 8953ca0 f93e49c ee6b7fb 2878a94 9ae09da bafcf39 3bbf593 eea5c07 bafcf39 8652429 0ea8b9e bafcf39 0ea8b9e ee6b7fb bafcf39 3bff849 d60759d bafcf39 ee6b7fb d60759d bafcf39 d60759d bafcf39 9ae09da 601fcda 9ae09da 601fcda 9ae09da 601fcda 9ae09da 0ea8b9e 87e1451 bafcf39 87e1451 ee6b7fb bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e ee6b7fb 0ea8b9e f93e49c 0ea8b9e bafcf39 0ea8b9e f93e49c bafcf39 8652429 66e145d bafcf39 66e145d bafcf39 66e145d d3e6a24 66e145d 0ea8b9e bafcf39 0ea8b9e 66e145d ee6b7fb 66e145d bafcf39 0ea8b9e bafcf39 0ea8b9e 52c1a90 0ea8b9e bafcf39 d60759d 4276db1 bafcf39 4276db1 bafcf39 0ea8b9e f957846 f93e49c 5a21738 bafcf39 5a21738 0ea8b9e bce761b 0ea8b9e ee6b7fb bafcf39 f93e49c bafcf39 f93e49c bafcf39 0ea8b9e ee6b7fb bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 bce761b 0ea8b9e bafcf39 bce761b 0ea8b9e 66e145d 0ea8b9e 93b4c8a bafcf39 d60759d bafcf39 0ea8b9e bafcf39 391712c 0ea8b9e bafcf39 d3e6a24 0ea8b9e bafcf39 f93e49c 0ea8b9e 4276db1 0ea8b9e bce761b 0ea8b9e ee6b7fb bafcf39 0ea8b9e ee6b7fb bafcf39 cb349ad d60759d 0e1a4a7 bafcf39 d60759d 0e1a4a7 d60759d bafcf39 d60759d 0e1a4a7 3bff849 0e1a4a7 d60759d 0e1a4a7 aa5c211 d60759d aa5c211 3cecbfa 3bff849 1d772de bafcf39 d60759d 0e1a4a7 d60759d 0e1a4a7 d60759d 1d772de 3cecbfa 0e1a4a7 bafcf39 0e1a4a7 bafcf39 3cecbfa bafcf39 d60759d 34addbf d60759d 84c83c0 391712c bce761b d60759d bafcf39 d60759d bafcf39 391712c bafcf39 7907ad4 391712c bafcf39 e2aae24 391712c e2aae24 08a3ec3 bafcf39 a33b955 bafcf39 0ea8b9e bafcf39 d60759d bafcf39 d60759d bafcf39 391712c bafcf39 7907ad4 391712c bafcf39 e2aae24 a33b955 bafcf39 a33b955 e2aae24 9ae09da bafcf39 4c95b3c bafcf39 4c95b3c 601fcda 4c95b3c 601fcda 9ae09da 601fcda 9ae09da 68a91f4 bafcf39 0ea8b9e 68a91f4 bafcf39 68a91f4 66e145d 84c83c0 bafcf39 0ea8b9e bafcf39 7810536 bde6e5b cb349ad eea5c07 bafcf39 7810536 bafcf39 bce761b 7810536 08a3ec3 bafcf39 0ea8b9e 003292d bafcf39 52e26c1 bafcf39 52e26c1 bafcf39 0ea8b9e bafcf39 5b4b5fb bafcf39 8652429 bafcf39 ee6b7fb bafcf39 eea5c07 bce761b bafcf39 eea5c07 08a3ec3 bafcf39 eea5c07 bafcf39 eea5c07 08a3ec3 bafcf39 eea5c07 cb349ad eea5c07 04d80a1 bafcf39 0ea8b9e bce761b bafcf39 5a21738 bafcf39 3bbf593 bafcf39 36f8e9f bafcf39 3bbf593 bafcf39 ee6b7fb d60759d 66e145d ee6b7fb bafcf39 66e145d bafcf39 d60759d a770956 ef4000e bafcf39 ef4000e bafcf39 ef4000e bafcf39 d60759d bafcf39 ef4000e ee6b7fb bafcf39 52e26c1 bafcf39 d60759d bafcf39 ef4000e bafcf39 d60759d bafcf39 d60759d bafcf39 87e1451 0ea8b9e 5a21738 0ea8b9e bafcf39 bde6e5b bafcf39 d60759d 0ea8b9e bafcf39 d60759d bafcf39 d60759d bafcf39 d60759d bafcf39 e2aae24 bafcf39 eea5c07 f0f9378 0ea8b9e f0f9378 bafcf39 f0f9378 bafcf39 f0f9378 2e71433 0ea8b9e 34addbf bafcf39 6ea0852 5345e1f 6a6aac2 bafcf39 0f18146 5345e1f f957846 8652429 bafcf39 d60759d bafcf39 0ea8b9e 8953ca0 bafcf39 eea5c07 0ea8b9e 0e1a4a7 bafcf39 eea5c07 bafcf39 f93e49c ee6b7fb bafcf39 ec98119 bafcf39 ec98119 ebf9010 ec98119 bafcf39 ec98119 ebf9010 ec98119 ebf9010 ec98119 0ea8b9e ec98119 bafcf39 a03496e 0ea8b9e ec98119 ebf9010 ec98119 ebf9010 bafcf39 ec98119 bafcf39 ec98119 ebf9010 bafcf39 ebf9010 bafcf39 ebf9010 bafcf39 ebf9010 bafcf39 a03496e ebf9010 bafcf39 ebf9010 bafcf39 a03496e bafcf39 a03496e bafcf39 a03496e bafcf39 a03496e bafcf39 a03496e bafcf39 a03496e bafcf39 ebf9010 bafcf39 ebf9010 6ea0852 ebf9010 a03496e bafcf39 a03496e ebf9010 a03496e bafcf39 ec98119 a03496e ec98119 bafcf39 ebf9010 bafcf39 ebf9010 bafcf39 ebf9010 0ea8b9e bafcf39 0ea8b9e ebf9010 bafcf39 ebf9010 bafcf39 ebf9010 bafcf39 ebf9010 bafcf39 ebf9010 bafcf39 ebf9010 bafcf39 0ea8b9e bafcf39 0ea8b9e ed5f8c7 bafcf39 ed5f8c7 bafcf39 ed5f8c7 0ea8b9e bafcf39 0ea8b9e ed5f8c7 bafcf39 ed5f8c7 bafcf39 ed5f8c7 bafcf39 ed5f8c7 bafcf39 ed5f8c7 bafcf39 ed5f8c7 bafcf39 ed5f8c7 bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e 52c1a90 bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 5fcccbe 10f46e9 5fcccbe 10f46e9 5fcccbe 10f46e9 5fcccbe bafcf39 5fcccbe bafcf39 5fcccbe 10f46e9 bafcf39 339a165 15026f7 08a3ec3 0ea8b9e bafcf39 0ea8b9e bafcf39 339a165 bafcf39 0ea8b9e bafcf39 0ea8b9e 23f8ca3 ebf9010 3bff849 ebf9010 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 ebf9010 bafcf39 a03496e ebf9010 a03496e bafcf39 ebf9010 339a165 ebf9010 15026f7 ebf9010 52c1a90 ebf9010 23f8ca3 bafcf39 339a165 0ea8b9e 339a165 bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 bde6e5b bafcf39 66e145d bde6e5b 339a165 bafcf39 0ea8b9e ed5f8c7 bafcf39 15026f7 ebf9010 a03496e bafcf39 339a165 52c1a90 ebf9010 0ea8b9e a770956 339a165 a770956 bafcf39 23f8ca3 bafcf39 a770956 339a165 ebf9010 bafcf39 ebf9010 339a165 10f46e9 bafcf39 339a165 ebf9010 339a165 bafcf39 a265560 bafcf39 3bff849 a770956 3bff849 e9c4101 a770956 0ea8b9e d60759d 0ea8b9e d60759d 0ea8b9e ec98119 0ea8b9e d60759d 0ea8b9e ec98119 8652429 3bff849 8652429 bafcf39 a770956 8652429 a770956 3bff849 8652429 bafcf39 8652429 a748df6 bafcf39 8652429 bafcf39 a770956 bafcf39 ebf9010 8652429 a770956 bafcf39 8652429 bafcf39 8652429 e9c4101 8652429 e9c4101 bafcf39 0ea8b9e 0d3554e bafcf39 0d3554e ebf9010 e9c4101 bafcf39 a770956 6ea0852 bafcf39 e9c4101 a770956 e9c4101 eea5c07 a770956 bafcf39 a770956 bafcf39 2878a94 eea5c07 0ea8b9e eea5c07 f0f9378 eea5c07 bce761b 0ea8b9e 8953ca0 2878a94 eea5c07 f0f9378 ee6b7fb 0ea8b9e f0f9378 8235bbb e2aae24 aa5c211 e3365ed bde6e5b 0ea8b9e 2878a94 a770956 dacc782 9ae09da bafcf39 eea5c07 bde6e5b bafcf39 0ea8b9e bafcf39 8235bbb 9ae09da bafcf39 9ae09da 641ff3e e3365ed bafcf39 e3365ed aa5c211 bde6e5b 1d772de 82b9d9d bafcf39 bde6e5b e3365ed 2878a94 bafcf39 e3365ed e2aae24 08a3ec3 bafcf39 bce761b 0ea8b9e bafcf39 339a165 0ea8b9e bc4bdbd 641ff3e bc4bdbd bafcf39 641ff3e bafcf39 12224f5 e9c4101 bafcf39 f0c28d7 bafcf39 66e145d bafcf39 0ea8b9e f0c28d7 bafcf39 f93e49c bafcf39 f93e49c bafcf39 f93e49c f0c28d7 bafcf39 eea5c07 bafcf39 eea5c07 ab04c92 3bff849 ab04c92 ee6b7fb bafcf39 ab04c92 bafcf39 08a3ec3 0ea8b9e eea5c07 3bff849 eea5c07 bafcf39 0ea8b9e bc4bdbd bafcf39 bc4bdbd 0ea8b9e bc4bdbd bafcf39 5b4b5fb bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 66e145d e9c4101 93b4c8a bce761b f93e49c bafcf39 f93e49c bafcf39 f93e49c bafcf39 f93e49c bafcf39 f93e49c 72f39c9 bafcf39 0ea8b9e bce761b 3bff849 a33b955 143e2cc 0ea8b9e bafcf39 0ea8b9e bafcf39 66e145d eea5c07 bafcf39 143e2cc bafcf39 8953ca0 bafcf39 8953ca0 eea5c07 bafcf39 f0c28d7 bafcf39 eea5c07 f0c28d7 bafcf39 143e2cc 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e 143e2cc bafcf39 3bff849 bafcf39 eea5c07 0ea8b9e bafcf39 a33b955 bafcf39 8953ca0 bafcf39 f0c28d7 bafcf39 f93e49c 72f39c9 bafcf39 52e26c1 f93e49c bafcf39 f93e49c bce761b 0ea8b9e bafcf39 12224f5 0ea8b9e bafcf39 0ea8b9e e9c4101 bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 339a165 3bff849 ebf9010 0ea8b9e 36f8e9f 0ea8b9e 36f8e9f 0ea8b9e 12224f5 0ea8b9e ebf9010 36f8e9f ebf9010 36f8e9f bafcf39 36f8e9f bafcf39 36f8e9f ebf9010 0ea8b9e 1d772de bafcf39 36f8e9f bafcf39 12224f5 ebf9010 bafcf39 84c83c0 52c1a90 eea5c07 bafcf39 0ea8b9e eea5c07 0ea8b9e bafcf39 59ff822 0ea8b9e 59ff822 0ea8b9e eea5c07 ef4000e bce761b 0ea8b9e f957846 5345e1f f957846 143e2cc ef4000e bafcf39 f93e49c bafcf39 42180e4 eea5c07 bafcf39 eea5c07 0ea8b9e bafcf39 0ea8b9e 641ff3e 0ea8b9e bafcf39 59ff822 0ea8b9e 59ff822 0ea8b9e 6ea0852 eea5c07 5b4b5fb eea5c07 6ea0852 bce761b f0c28d7 0ea8b9e f957846 5345e1f f957846 143e2cc 0ea8b9e f0c28d7 bce761b bafcf39 f93e49c bafcf39 f93e49c bafcf39 f93e49c bafcf39 f93e49c bafcf39 0ea8b9e bce761b f0c28d7 bafcf39 0ea8b9e f957846 5345e1f f957846 eea5c07 0ea8b9e bce761b bafcf39 f93e49c bafcf39 f93e49c bafcf39 0ea8b9e f93e49c bafcf39 0ea8b9e ebf9010 a265560 ebf9010 339a165 bafcf39 641ff3e 93ac94f bafcf39 339a165 eea5c07 84c83c0 bafcf39 ee6b7fb 3bff849 339a165 84c83c0 ee6b7fb bafcf39 84c83c0 ee6b7fb cb349ad 84c83c0 613b1b4 ee6b7fb eea5c07 bafcf39 003292d bafcf39 ee6b7fb 42180e4 339a165 3bff849 339a165 bafcf39 003292d 84c83c0 ee6b7fb eea5c07 84c83c0 ee6b7fb 003292d ee6b7fb 003292d bafcf39 ee6b7fb 339a165 ee6b7fb ef4000e bafcf39 ee6b7fb ef4000e ee6b7fb ef4000e ee6b7fb ef4000e ee6b7fb ef4000e ee6b7fb ef4000e ee6b7fb bafcf39 ef4000e ee6b7fb ef4000e ee6b7fb ef4000e ee6b7fb bafcf39 ef4000e 3bff849 ee6b7fb bafcf39 ef4000e ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb ef4000e bafcf39 ef4000e ee6b7fb ef4000e ee6b7fb bafcf39 ee6b7fb ef4000e bafcf39 ef4000e ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ef4000e ee6b7fb ef4000e ee6b7fb bafcf39 ee6b7fb bafcf39 ef4000e ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb ef4000e bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb bafcf39 ee6b7fb 84c83c0 bafcf39 93ac94f ebf9010 93ac94f ebf9010 a03496e bafcf39 a03496e bafcf39 a03496e bafcf39 a03496e bafcf39 52c1a90 93ac94f bafcf39 a03496e 3bff849 ebf9010 bde6e5b ebf9010 93ac94f bafcf39 93ac94f bafcf39 ebf9010 bde6e5b 93ac94f bafcf39 93ac94f 0ea8b9e 93ac94f bafcf39 eea5c07 ef4000e eea5c07 f0f9378 eea5c07 ee6b7fb bafcf39 ee6b7fb bafcf39 e2aae24 bafcf39 0ea8b9e 9ae09da bafcf39 eea5c07 bafcf39 eea5c07 ef4000e eea5c07 f0f9378 eea5c07 0ea8b9e eea5c07 0ea8b9e eea5c07 f0f9378 e2aae24 e3365ed aa5c211 e3365ed bde6e5b 601fcda 0ea8b9e 9ae09da ef4000e eea5c07 9ae09da eea5c07 bafcf39 eea5c07 bafcf39 0ea8b9e ab04c92 e2aae24 0ea8b9e ab04c92 0ea8b9e 9ae09da bafcf39 9ae09da bafcf39 e3365ed bafcf39 e3365ed aa5c211 e3365ed e2aae24 82b9d9d bafcf39 9ae09da 339a165 ef4000e bafcf39 ef4000e bafcf39 ee6b7fb bc4bdbd bafcf39 bc4bdbd bafcf39 bc4bdbd bafcf39 eea5c07 0ea8b9e bafcf39 eea5c07 0ea8b9e ebf9010 0ea8b9e eea5c07 bafcf39 eea5c07 0ea8b9e bafcf39 eea5c07 ebf9010 08a3ec3 ebf9010 0ea8b9e bafcf39 3bff849 bafcf39 3bff849 bafcf39 3bff849 ebf9010 ee6b7fb bafcf39 3bff849 cb349ad bafcf39 0ea8b9e bafcf39 ebf9010 0ea8b9e ee6b7fb bafcf39 ee6b7fb ef4000e 0ea8b9e bafcf39 ebf9010 ee6b7fb cb349ad bafcf39 0ea8b9e bafcf39 ee6b7fb d60759d bafcf39 cb349ad 0ea8b9e bce761b cb349ad a265560 0ea8b9e 601fcda 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 a265560 bafcf39 42180e4 0ea8b9e bafcf39 e9c4101 0ea8b9e bafcf39 e9c4101 0ea8b9e bafcf39 1d772de 0ea8b9e bafcf39 0ea8b9e bafcf39 a03496e cb349ad bafcf39 eea5c07 59ff822 bafcf39 59ff822 0ea8b9e 59ff822 0ea8b9e bafcf39 339a165 bafcf39 003292d eea5c07 5b4b5fb bafcf39 59ff822 bafcf39 59ff822 0ea8b9e 59ff822 0ea8b9e eea5c07 0ea8b9e eea5c07 0ea8b9e bafcf39 0ea8b9e 52c1a90 ab04c92 bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 0ea8b9e bafcf39 97097ff 0ea8b9e 97097ff bafcf39 ef4000e ee6b7fb bafcf39 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 |
import copy
import io
import json
import os
import time
from collections import defaultdict # For efficient grouping
from typing import Any, Dict, List, Optional, Tuple
import boto3
import gradio as gr
import pandas as pd
from gradio import Progress
from pdfminer.high_level import extract_pages
from pdfminer.layout import (
LTAnno,
LTTextContainer,
LTTextLine,
LTTextLineHorizontal,
)
from pikepdf import Dictionary, Name, Pdf
from PIL import Image, ImageDraw, ImageFile
from presidio_analyzer import AnalyzerEngine
from pymupdf import Document, Page, Rect
from tqdm import tqdm
from tools.aws_textract import (
analyse_page_with_textract,
json_to_ocrresult,
load_and_convert_textract_json,
)
from tools.config import (
AWS_ACCESS_KEY,
AWS_PII_OPTION,
AWS_REGION,
AWS_SECRET_KEY,
CUSTOM_ENTITIES,
DEFAULT_LANGUAGE,
IMAGES_DPI,
INPUT_FOLDER,
LOAD_TRUNCATED_IMAGES,
MAX_DOC_PAGES,
MAX_IMAGE_PIXELS,
MAX_SIMULTANEOUS_FILES,
MAX_TIME_VALUE,
NO_REDACTION_PII_OPTION,
OUTPUT_FOLDER,
PAGE_BREAK_VALUE,
PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS,
RETURN_PDF_END_OF_REDACTION,
RUN_AWS_FUNCTIONS,
SELECTABLE_TEXT_EXTRACT_OPTION,
TESSERACT_TEXT_EXTRACT_OPTION,
TEXTRACT_TEXT_EXTRACT_OPTION,
aws_comprehend_language_choices,
textract_language_choices,
)
from tools.custom_image_analyser_engine import (
CustomImageAnalyzerEngine,
CustomImageRecognizerResult,
OCRResult,
combine_ocr_results,
recreate_page_line_level_ocr_results_with_page,
run_page_text_redaction,
)
from tools.file_conversion import (
convert_annotation_data_to_dataframe,
convert_annotation_json_to_review_df,
create_annotation_dicts_from_annotation_df,
divide_coordinates_by_page_sizes,
fill_missing_box_ids,
fill_missing_ids,
is_pdf,
is_pdf_or_image,
load_and_convert_ocr_results_with_words_json,
prepare_image_or_pdf,
redact_single_box,
redact_whole_pymupdf_page,
remove_duplicate_images_with_blank_boxes,
save_pdf_with_or_without_compression,
word_level_ocr_output_to_dataframe,
)
from tools.helper_functions import (
_get_env_list,
clean_unicode_text,
get_file_name_without_type,
)
from tools.load_spacy_model_custom_recognisers import (
CustomWordFuzzyRecognizer,
create_nlp_analyser,
custom_word_list_recogniser,
download_tesseract_lang_pack,
load_spacy_model,
nlp_analyser,
score_threshold,
)
from tools.secure_path_utils import secure_file_write
ImageFile.LOAD_TRUNCATED_IMAGES = LOAD_TRUNCATED_IMAGES.lower() == "true"
if not MAX_IMAGE_PIXELS:
Image.MAX_IMAGE_PIXELS = None
else:
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
image_dpi = float(IMAGES_DPI)
RETURN_PDF_END_OF_REDACTION = RETURN_PDF_END_OF_REDACTION.lower() == "true"
if CUSTOM_ENTITIES:
CUSTOM_ENTITIES = _get_env_list(CUSTOM_ENTITIES)
custom_entities = CUSTOM_ENTITIES
def bounding_boxes_overlap(box1, box2):
"""Check if two bounding boxes overlap."""
return (
box1[0] < box2[2]
and box2[0] < box1[2]
and box1[1] < box2[3]
and box2[1] < box1[3]
)
def sum_numbers_before_seconds(string: str):
"""Extracts numbers that precede the word 'seconds' from a string and adds them up.
Args:
string: The input string.
Returns:
The sum of all numbers before 'seconds' in the string.
"""
# Extract numbers before 'seconds' using secure regex
from tools.secure_regex_utils import safe_extract_numbers_with_seconds
numbers = safe_extract_numbers_with_seconds(string)
# Sum up the extracted numbers
sum_of_numbers = round(sum(numbers), 1)
return sum_of_numbers
def reverse_y_coords(df: pd.DataFrame, column: str):
df[column] = df[column]
df[column] = 1 - df[column].astype(float)
df[column] = df[column].round(6)
return df[column]
def merge_page_results(data: list):
merged = {}
for item in data:
page = item["page"]
if page not in merged:
merged[page] = {"page": page, "results": {}}
# Merge line-level results into the existing page
merged[page]["results"].update(item.get("results", {}))
return list(merged.values())
def choose_and_run_redactor(
file_paths: List[str],
prepared_pdf_file_paths: List[str],
pdf_image_file_paths: List[str],
chosen_redact_entities: List[str],
chosen_redact_comprehend_entities: List[str],
text_extraction_method: str,
in_allow_list: List[str] = list(),
in_deny_list: List[str] = list(),
redact_whole_page_list: List[str] = list(),
latest_file_completed: int = 0,
combined_out_message: List = list(),
out_file_paths: List = list(),
log_files_output_paths: List = list(),
first_loop_state: bool = False,
page_min: int = 0,
page_max: int = 999,
estimated_time_taken_state: float = 0.0,
handwrite_signature_checkbox: List[str] = list(["Extract handwriting"]),
all_request_metadata_str: str = "",
annotations_all_pages: List[dict] = list(),
all_page_line_level_ocr_results_df: pd.DataFrame = None,
all_pages_decision_process_table: pd.DataFrame = None,
pymupdf_doc=list(),
current_loop_page: int = 0,
page_break_return: bool = False,
pii_identification_method: str = "Local",
comprehend_query_number: int = 0,
max_fuzzy_spelling_mistakes_num: int = 1,
match_fuzzy_whole_phrase_bool: bool = True,
aws_access_key_textbox: str = "",
aws_secret_key_textbox: str = "",
annotate_max_pages: int = 1,
review_file_state: pd.DataFrame = list(),
output_folder: str = OUTPUT_FOLDER,
document_cropboxes: List = list(),
page_sizes: List[dict] = list(),
textract_output_found: bool = False,
text_extraction_only: bool = False,
duplication_file_path_outputs: list = list(),
review_file_path: str = "",
input_folder: str = INPUT_FOLDER,
total_textract_query_number: int = 0,
ocr_file_path: str = "",
all_page_line_level_ocr_results: list[dict] = list(),
all_page_line_level_ocr_results_with_words: list[dict] = list(),
all_page_line_level_ocr_results_with_words_df: pd.DataFrame = None,
chosen_local_model: str = "tesseract",
language: str = DEFAULT_LANGUAGE,
prepare_images: bool = True,
RETURN_PDF_END_OF_REDACTION: bool = RETURN_PDF_END_OF_REDACTION,
progress=gr.Progress(track_tqdm=True),
):
"""
This function orchestrates the redaction process based on the specified method and parameters. It takes the following inputs:
- file_paths (List[str]): A list of paths to the files to be redacted.
- prepared_pdf_file_paths (List[str]): A list of paths to the PDF files prepared for redaction.
- pdf_image_file_paths (List[str]): A list of paths to the PDF files converted to images for redaction.
- chosen_redact_entities (List[str]): A list of entity types to redact from the files using the local model (spacy) with Microsoft Presidio.
- chosen_redact_comprehend_entities (List[str]): A list of entity types to redact from files, chosen from the official list from AWS Comprehend service.
- text_extraction_method (str): The method to use to extract text from documents.
- in_allow_list (List[List[str]], optional): A list of allowed terms for redaction. Defaults to empty list. Can also be entered as a string path to a CSV file, or as a single column pandas dataframe.
- in_deny_list (List[List[str]], optional): A list of denied terms for redaction. Defaults to empty list. Can also be entered as a string path to a CSV file, or as a single column pandas dataframe.
- redact_whole_page_list (List[List[str]], optional): A list of whole page numbers for redaction. Defaults to empty list. Can also be entered as a string path to a CSV file, or as a single column pandas dataframe.
- latest_file_completed (int, optional): The index of the last completed file. Defaults to 0.
- combined_out_message (list, optional): A list to store output messages. Defaults to an empty list.
- out_file_paths (list, optional): A list to store paths to the output files. Defaults to an empty list.
- log_files_output_paths (list, optional): A list to store paths to the log files. Defaults to an empty list.
- first_loop_state (bool, optional): A flag indicating if this is the first iteration. Defaults to False.
- page_min (int, optional): The minimum page number to start redaction from. Defaults to 0.
- page_max (int, optional): The maximum page number to end redaction at. Defaults to 999.
- estimated_time_taken_state (float, optional): The estimated time taken for the redaction process. Defaults to 0.0.
- handwrite_signature_checkbox (List[str], optional): A list of options for redacting handwriting and signatures. Defaults to ["Extract handwriting", "Extract signatures"].
- all_request_metadata_str (str, optional): A string containing all request metadata. Defaults to an empty string.
- annotations_all_pages (List[dict], optional): A list of dictionaries containing all image annotations. Defaults to an empty list.
- all_page_line_level_ocr_results_df (pd.DataFrame, optional): A DataFrame containing all line-level OCR results. Defaults to an empty DataFrame.
- all_pages_decision_process_table (pd.DataFrame, optional): A DataFrame containing all decision process tables. Defaults to an empty DataFrame.
- pymupdf_doc (optional): A list containing the PDF document object. Defaults to an empty list.
- current_loop_page (int, optional): The current page being processed in the loop. Defaults to 0.
- page_break_return (bool, optional): A flag indicating if the function should return after a page break. Defaults to False.
- pii_identification_method (str, optional): The method to redact personal information. Either 'Local' (spacy model), or 'AWS Comprehend' (AWS Comprehend API).
- comprehend_query_number (int, optional): A counter tracking the number of queries to AWS Comprehend.
- max_fuzzy_spelling_mistakes_num (int, optional): The maximum number of spelling mistakes allowed in a searched phrase for fuzzy matching. Can range from 0-9.
- match_fuzzy_whole_phrase_bool (bool, optional): A boolean where 'True' means that the whole phrase is fuzzy matched, and 'False' means that each word is fuzzy matched separately (excluding stop words).
- aws_access_key_textbox (str, optional): AWS access key for account with Textract and Comprehend permissions.
- aws_secret_key_textbox (str, optional): AWS secret key for account with Textract and Comprehend permissions.
- annotate_max_pages (int, optional): Maximum page value for the annotation object.
- review_file_state (pd.DataFrame, optional): Output review file dataframe.
- output_folder (str, optional): Output folder for results.
- document_cropboxes (List, optional): List of document cropboxes for the PDF.
- page_sizes (List[dict], optional): List of dictionaries of PDF page sizes in PDF or image format.
- textract_output_found (bool, optional): Boolean is true when a textract OCR output for the file has been found.
- text_extraction_only (bool, optional): Boolean to determine if function should only extract text from the document, and not redact.
- duplication_file_outputs (list, optional): List to allow for export to the duplication function page.
- review_file_path (str, optional): The latest review file path created by the app
- input_folder (str, optional): The custom input path, if provided
- total_textract_query_number (int, optional): The number of textract queries up until this point.
- ocr_file_path (str, optional): The latest ocr file path created by the app.
- all_page_line_level_ocr_results (list, optional): All line level text on the page with bounding boxes.
- all_page_line_level_ocr_results_with_words (list, optional): All word level text on the page with bounding boxes.
- all_page_line_level_ocr_results_with_words_df (pd.Dataframe, optional): All word level text on the page with bounding boxes as a dataframe.
- chosen_local_model (str): Which local model is being used for OCR on images - "tesseract", "paddle" for PaddleOCR, or "hybrid" to combine both.
- language (str, optional): The language of the text in the files. Defaults to English.
- language (str, optional): The language to do AWS Comprehend calls. Defaults to value of language if not provided.
- prepare_images (bool, optional): Boolean to determine whether to load images for the PDF.
- RETURN_PDF_END_OF_REDACTION (bool, optional): Boolean to determine whether to return a redacted PDF at the end of the redaction process.
- progress (gr.Progress, optional): A progress tracker for the redaction process. Defaults to a Progress object with track_tqdm set to True.
The function returns a redacted document along with processing logs.
"""
tic = time.perf_counter()
out_message = ""
pdf_file_name_with_ext = ""
pdf_file_name_without_ext = ""
page_break_return = False
blank_request_metadata = list()
custom_recogniser_word_list_flat = list()
all_textract_request_metadata = (
all_request_metadata_str.split("\n") if all_request_metadata_str else []
)
review_out_file_paths = [prepared_pdf_file_paths[0]]
task_textbox = "redact"
# CLI mode may provide options to enter method names in a different format
if text_extraction_method == "AWS Textract":
text_extraction_method = TEXTRACT_TEXT_EXTRACT_OPTION
if text_extraction_method == "Local OCR":
text_extraction_method = TESSERACT_TEXT_EXTRACT_OPTION
if text_extraction_method == "Local text":
text_extraction_method = SELECTABLE_TEXT_EXTRACT_OPTION
if pii_identification_method == "None":
pii_identification_method = NO_REDACTION_PII_OPTION
# If output folder doesn't end with a forward slash, add one
if not output_folder.endswith("/"):
output_folder = output_folder + "/"
# Use provided language or default
language = language or DEFAULT_LANGUAGE
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
if language not in textract_language_choices:
out_message = f"Language '{language}' is not supported by AWS Textract. Please select a different language."
raise Warning(out_message)
elif pii_identification_method == AWS_PII_OPTION:
if language not in aws_comprehend_language_choices:
out_message = f"Language '{language}' is not supported by AWS Comprehend. Please select a different language."
raise Warning(out_message)
if all_page_line_level_ocr_results_with_words_df is None:
all_page_line_level_ocr_results_with_words_df = pd.DataFrame()
# Create copies of out_file_path objects to avoid overwriting each other on append actions
out_file_paths = out_file_paths.copy()
log_files_output_paths = log_files_output_paths.copy()
# Ensure all_pages_decision_process_table is in correct format for downstream processes
if isinstance(all_pages_decision_process_table, list):
if not all_pages_decision_process_table:
all_pages_decision_process_table = pd.DataFrame(
columns=[
"image_path",
"page",
"label",
"xmin",
"xmax",
"ymin",
"ymax",
"boundingBox",
"text",
"start",
"end",
"score",
"id",
]
)
elif isinstance(all_pages_decision_process_table, pd.DataFrame):
if all_pages_decision_process_table.empty:
all_pages_decision_process_table = pd.DataFrame(
columns=[
"image_path",
"page",
"label",
"xmin",
"xmax",
"ymin",
"ymax",
"boundingBox",
"text",
"start",
"end",
"score",
"id",
]
)
# If this is the first time around, set variables to 0/blank
if first_loop_state is True:
# print("First_loop_state is True")
latest_file_completed = 0
current_loop_page = 0
out_file_paths = list()
log_files_output_paths = list()
estimate_total_processing_time = 0
estimated_time_taken_state = 0
comprehend_query_number = 0
total_textract_query_number = 0
elif current_loop_page == 0:
comprehend_query_number = 0
total_textract_query_number = 0
# If not the first time around, and the current page loop has been set to a huge number (been through all pages), reset current page to 0
elif (first_loop_state is False) & (current_loop_page == 999):
current_loop_page = 0
total_textract_query_number = 0
comprehend_query_number = 0
# Choose the correct file to prepare
if isinstance(file_paths, str):
file_paths_list = [os.path.abspath(file_paths)]
elif isinstance(file_paths, dict):
file_paths = file_paths["name"]
file_paths_list = [os.path.abspath(file_paths)]
else:
file_paths_list = file_paths
if len(file_paths_list) > MAX_SIMULTANEOUS_FILES:
out_message = f"Number of files to redact is greater than {MAX_SIMULTANEOUS_FILES}. Please submit a smaller number of files."
print(out_message)
raise Exception(out_message)
valid_extensions = {".pdf", ".jpg", ".jpeg", ".png"}
# Filter only files with valid extensions. Currently only allowing one file to be redacted at a time
# Filter the file_paths_list to include only files with valid extensions
filtered_files = [
file
for file in file_paths_list
if os.path.splitext(file)[1].lower() in valid_extensions
]
# Check if any files were found and assign to file_paths_list
file_paths_list = filtered_files if filtered_files else []
print("Latest file completed:", latest_file_completed)
# If latest_file_completed is used, get the specific file
if not isinstance(file_paths, (str, dict)):
file_paths_loop = (
[file_paths_list[int(latest_file_completed)]]
if len(file_paths_list) > latest_file_completed
else []
)
else:
file_paths_loop = file_paths_list
latest_file_completed = int(latest_file_completed)
if isinstance(file_paths, str):
number_of_files = 1
else:
number_of_files = len(file_paths_list)
# If we have already redacted the last file, return the input out_message and file list to the relevant outputs
if latest_file_completed >= number_of_files:
print("Completed last file")
progress(0.95, "Completed last file, performing final checks")
current_loop_page = 0
if isinstance(combined_out_message, list):
combined_out_message = "\n".join(combined_out_message)
if isinstance(out_message, list) and out_message:
combined_out_message = combined_out_message + "\n".join(out_message)
elif out_message:
combined_out_message = combined_out_message + "\n" + out_message
from tools.secure_regex_utils import safe_remove_leading_newlines
combined_out_message = safe_remove_leading_newlines(combined_out_message)
end_message = "\n\nPlease review and modify the suggested redaction outputs on the 'Review redactions' tab of the app (you can find this under the introduction text at the top of the page)."
if end_message not in combined_out_message:
combined_out_message = combined_out_message + end_message
# Only send across review file if redaction has been done
if pii_identification_method != NO_REDACTION_PII_OPTION:
if len(review_out_file_paths) == 1:
if review_file_path:
review_out_file_paths.append(review_file_path)
if not isinstance(pymupdf_doc, list):
number_of_pages = pymupdf_doc.page_count
if total_textract_query_number > number_of_pages:
total_textract_query_number = number_of_pages
estimate_total_processing_time = sum_numbers_before_seconds(
combined_out_message
)
print("Estimated total processing time:", str(estimate_total_processing_time))
page_break_return = True
return (
combined_out_message,
out_file_paths,
out_file_paths,
latest_file_completed,
log_files_output_paths,
log_files_output_paths,
estimated_time_taken_state,
all_request_metadata_str,
pymupdf_doc,
annotations_all_pages,
current_loop_page,
page_break_return,
all_page_line_level_ocr_results_df,
all_pages_decision_process_table,
comprehend_query_number,
review_out_file_paths,
annotate_max_pages,
annotate_max_pages,
prepared_pdf_file_paths,
pdf_image_file_paths,
review_file_state,
page_sizes,
duplication_file_path_outputs,
duplication_file_path_outputs,
review_file_path,
total_textract_query_number,
ocr_file_path,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
all_page_line_level_ocr_results_with_words_df,
review_file_state,
task_textbox,
)
# if first_loop_state == False:
# Prepare documents and images as required if they don't already exist
prepare_images_flag = None # Determines whether to call prepare_image_or_pdf
if textract_output_found and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
print("Existing Textract outputs found, not preparing images or documents.")
prepare_images_flag = False
# return # No need to call `prepare_image_or_pdf`, exit early
elif text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION:
print("Running text extraction analysis, not preparing images.")
prepare_images_flag = False
elif prepare_images and not pdf_image_file_paths:
print("Prepared PDF images not found, loading from file")
prepare_images_flag = True
elif not prepare_images:
print("Not loading images for file")
prepare_images_flag = False
else:
print("Loading images for file")
prepare_images_flag = True
# Call prepare_image_or_pdf only if needed
if prepare_images_flag is not None:
(
out_message,
prepared_pdf_file_paths,
pdf_image_file_paths,
annotate_max_pages,
annotate_max_pages_bottom,
pymupdf_doc,
annotations_all_pages,
review_file_state,
document_cropboxes,
page_sizes,
textract_output_found,
all_img_details_state,
placeholder_ocr_results_df,
local_ocr_output_found_checkbox,
all_page_line_level_ocr_results_with_words_df,
) = prepare_image_or_pdf(
file_paths_loop,
text_extraction_method,
all_page_line_level_ocr_results_df,
all_page_line_level_ocr_results_with_words_df,
0,
out_message,
True,
annotate_max_pages,
annotations_all_pages,
document_cropboxes,
redact_whole_page_list,
output_folder=output_folder,
prepare_images=prepare_images_flag,
page_sizes=page_sizes,
pymupdf_doc=pymupdf_doc,
input_folder=input_folder,
)
page_sizes_df = pd.DataFrame(page_sizes)
if page_sizes_df.empty:
page_sizes_df = pd.DataFrame(
columns=[
"page",
"image_path",
"image_width",
"image_height",
"mediabox_width",
"mediabox_height",
"cropbox_width",
"cropbox_height",
"original_cropbox",
]
)
page_sizes_df[["page"]] = page_sizes_df[["page"]].apply(
pd.to_numeric, errors="coerce"
)
page_sizes = page_sizes_df.to_dict(orient="records")
number_of_pages = pymupdf_doc.page_count
if number_of_pages > MAX_DOC_PAGES:
out_message = f"Number of pages in document is greater than {MAX_DOC_PAGES}. Please submit a smaller document."
print(out_message)
raise Exception(out_message)
# If we have reached the last page, return message and outputs
if current_loop_page >= number_of_pages:
print("Reached last page of document:", current_loop_page)
if total_textract_query_number > number_of_pages:
total_textract_query_number = number_of_pages
# Set to a very high number so as not to mix up with subsequent file processing by the user
current_loop_page = 999
if out_message:
combined_out_message = combined_out_message + "\n" + out_message
# Only send across review file if redaction has been done
if pii_identification_method != NO_REDACTION_PII_OPTION:
# If only pdf currently in review outputs, add on the latest review file
if len(review_out_file_paths) == 1:
if review_file_path:
review_out_file_paths.append(review_file_path)
page_break_return = False
return (
combined_out_message,
out_file_paths,
out_file_paths,
latest_file_completed,
log_files_output_paths,
log_files_output_paths,
estimated_time_taken_state,
all_request_metadata_str,
pymupdf_doc,
annotations_all_pages,
current_loop_page,
page_break_return,
all_page_line_level_ocr_results_df,
all_pages_decision_process_table,
comprehend_query_number,
review_out_file_paths,
annotate_max_pages,
annotate_max_pages,
prepared_pdf_file_paths,
pdf_image_file_paths,
review_file_state,
page_sizes,
duplication_file_path_outputs,
duplication_file_path_outputs,
review_file_path,
total_textract_query_number,
ocr_file_path,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
all_page_line_level_ocr_results_with_words_df,
review_file_state,
task_textbox,
)
### Load/create allow list, deny list, and whole page redaction list
### Load/create allow list
# If string, assume file path
if isinstance(in_allow_list, str):
if in_allow_list:
in_allow_list = pd.read_csv(in_allow_list, header=None)
# Now, should be a pandas dataframe format
if isinstance(in_allow_list, pd.DataFrame):
if not in_allow_list.empty:
in_allow_list_flat = in_allow_list.iloc[:, 0].tolist()
else:
in_allow_list_flat = list()
else:
in_allow_list_flat = list()
### Load/create deny list
# If string, assume file path
if isinstance(in_deny_list, str):
if in_deny_list:
in_deny_list = pd.read_csv(in_deny_list, header=None)
if isinstance(in_deny_list, pd.DataFrame):
if not in_deny_list.empty:
custom_recogniser_word_list_flat = in_deny_list.iloc[:, 0].tolist()
else:
custom_recogniser_word_list_flat = list()
# Sort the strings in order from the longest string to the shortest
custom_recogniser_word_list_flat = sorted(
custom_recogniser_word_list_flat, key=len, reverse=True
)
else:
custom_recogniser_word_list_flat = list()
### Load/create whole page redaction list
# If string, assume file path
if isinstance(redact_whole_page_list, str):
if redact_whole_page_list:
redact_whole_page_list = pd.read_csv(redact_whole_page_list, header=None)
if isinstance(redact_whole_page_list, pd.DataFrame):
if not redact_whole_page_list.empty:
try:
redact_whole_page_list_flat = (
redact_whole_page_list.iloc[:, 0].astype(int).tolist()
)
except Exception as e:
print(
"Could not convert whole page redaction data to number list due to:",
e,
)
redact_whole_page_list_flat = redact_whole_page_list.iloc[:, 0].tolist()
else:
redact_whole_page_list_flat = list()
else:
redact_whole_page_list_flat = list()
### Load/create PII identification method
# Try to connect to AWS services directly only if RUN_AWS_FUNCTIONS environmental variable is 1, otherwise an environment variable or direct textbox input is needed.
if pii_identification_method == AWS_PII_OPTION:
if RUN_AWS_FUNCTIONS == "1" and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS == "1":
print("Connecting to Comprehend via existing SSO connection")
comprehend_client = boto3.client("comprehend", region_name=AWS_REGION)
elif aws_access_key_textbox and aws_secret_key_textbox:
print(
"Connecting to Comprehend using AWS access key and secret keys from user input."
)
comprehend_client = boto3.client(
"comprehend",
aws_access_key_id=aws_access_key_textbox,
aws_secret_access_key=aws_secret_key_textbox,
region_name=AWS_REGION,
)
elif RUN_AWS_FUNCTIONS == "1":
print("Connecting to Comprehend via existing SSO connection")
comprehend_client = boto3.client("comprehend", region_name=AWS_REGION)
elif AWS_ACCESS_KEY and AWS_SECRET_KEY:
print("Getting Comprehend credentials from environment variables")
comprehend_client = boto3.client(
"comprehend",
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY,
region_name=AWS_REGION,
)
else:
comprehend_client = ""
out_message = "Cannot connect to AWS Comprehend service. Please provide access keys under Textract settings on the Redaction settings tab, or choose another PII identification method."
print(out_message)
raise Exception(out_message)
else:
comprehend_client = ""
# Try to connect to AWS Textract Client if using that text extraction method
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
if RUN_AWS_FUNCTIONS == "1" and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS == "1":
print("Connecting to Textract via existing SSO connection")
textract_client = boto3.client("textract", region_name=AWS_REGION)
elif aws_access_key_textbox and aws_secret_key_textbox:
print(
"Connecting to Textract using AWS access key and secret keys from user input."
)
textract_client = boto3.client(
"textract",
aws_access_key_id=aws_access_key_textbox,
aws_secret_access_key=aws_secret_key_textbox,
region_name=AWS_REGION,
)
elif RUN_AWS_FUNCTIONS == "1":
print("Connecting to Textract via existing SSO connection")
textract_client = boto3.client("textract", region_name=AWS_REGION)
elif AWS_ACCESS_KEY and AWS_SECRET_KEY:
print("Getting Textract credentials from environment variables.")
textract_client = boto3.client(
"textract",
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY,
region_name=AWS_REGION,
)
elif textract_output_found is True:
print(
"Existing Textract data found for file, no need to connect to AWS Textract"
)
textract_client = boto3.client("textract", region_name=AWS_REGION)
else:
textract_client = ""
out_message = "Cannot connect to AWS Textract service."
print(out_message)
raise Exception(out_message)
else:
textract_client = ""
### Language check - check if selected language packs exist
try:
if (
text_extraction_method == TESSERACT_TEXT_EXTRACT_OPTION
and chosen_local_model == "tesseract"
):
if language != "en":
progress(
0.1, desc=f"Downloading Tesseract language pack for {language}"
)
download_tesseract_lang_pack(language)
if language != "en":
progress(0.1, desc=f"Loading SpaCy model for {language}")
load_spacy_model(language)
except Exception as e:
print(f"Error downloading language packs for {language}: {e}")
raise Exception(f"Error downloading language packs for {language}: {e}")
# Check if output_folder exists, create it if it doesn't
if not os.path.exists(output_folder):
os.makedirs(output_folder)
progress(0.5, desc="Extracting text and redacting document")
all_pages_decision_process_table = pd.DataFrame(
columns=[
"image_path",
"page",
"label",
"xmin",
"xmax",
"ymin",
"ymax",
"boundingBox",
"text",
"start",
"end",
"score",
"id",
]
)
all_page_line_level_ocr_results_df = pd.DataFrame(
columns=["page", "text", "left", "top", "width", "height", "line"]
)
# Run through file loop, redact each file at a time
for file in file_paths_loop:
# Get a string file path
if isinstance(file, str):
file_path = file
else:
file_path = file.name
if file_path:
pdf_file_name_without_ext = get_file_name_without_type(file_path)
pdf_file_name_with_ext = os.path.basename(file_path)
is_a_pdf = is_pdf(file_path) is True
if (
is_a_pdf is False
and text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION
):
# If user has not submitted a pdf, assume it's an image
print(
"File is not a PDF, assuming that image analysis needs to be used."
)
text_extraction_method = TESSERACT_TEXT_EXTRACT_OPTION
else:
out_message = "No file selected"
print(out_message)
raise Exception(out_message)
# Output file paths names
orig_pdf_file_path = output_folder + pdf_file_name_without_ext
review_file_path = orig_pdf_file_path + "_review_file.csv"
# Load in all_ocr_results_with_words if it exists as a file path and doesn't exist already
# file_name = get_file_name_without_type(file_path)
if text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION:
file_ending = "local_text"
elif text_extraction_method == TESSERACT_TEXT_EXTRACT_OPTION:
file_ending = "local_ocr"
elif text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
file_ending = "textract"
all_page_line_level_ocr_results_with_words_json_file_path = (
output_folder
+ pdf_file_name_without_ext
+ "_ocr_results_with_words_"
+ file_ending
+ ".json"
)
if not all_page_line_level_ocr_results_with_words:
if local_ocr_output_found_checkbox is True and os.path.exists(
all_page_line_level_ocr_results_with_words_json_file_path
):
(
all_page_line_level_ocr_results_with_words,
is_missing,
log_files_output_paths,
) = load_and_convert_ocr_results_with_words_json(
all_page_line_level_ocr_results_with_words_json_file_path,
log_files_output_paths,
page_sizes_df,
)
# original_all_page_line_level_ocr_results_with_words = all_page_line_level_ocr_results_with_words.copy()
# Remove any existing review_file paths from the review file outputs
if (
text_extraction_method == TESSERACT_TEXT_EXTRACT_OPTION
or text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION
):
# Analyse and redact image-based pdf or image
if is_pdf_or_image(file_path) is False:
out_message = "Please upload a PDF file or image file (JPG, PNG) for image analysis."
raise Exception(out_message)
print(
"Redacting file " + pdf_file_name_with_ext + " as an image-based file"
)
(
pymupdf_doc,
all_pages_decision_process_table,
out_file_paths,
new_textract_request_metadata,
annotations_all_pages,
current_loop_page,
page_break_return,
all_page_line_level_ocr_results_df,
comprehend_query_number,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
) = redact_image_pdf(
file_path,
pdf_image_file_paths,
language,
chosen_redact_entities,
chosen_redact_comprehend_entities,
in_allow_list_flat,
page_min,
page_max,
text_extraction_method,
handwrite_signature_checkbox,
blank_request_metadata,
current_loop_page,
page_break_return,
annotations_all_pages,
all_page_line_level_ocr_results_df,
all_pages_decision_process_table,
pymupdf_doc,
pii_identification_method,
comprehend_query_number,
comprehend_client,
textract_client,
custom_recogniser_word_list_flat,
redact_whole_page_list_flat,
max_fuzzy_spelling_mistakes_num,
match_fuzzy_whole_phrase_bool,
page_sizes_df,
text_extraction_only,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
chosen_local_model,
log_files_output_paths=log_files_output_paths,
nlp_analyser=nlp_analyser,
output_folder=output_folder,
)
# This line creates a copy of out_file_paths to break potential links with log_files_output_paths
out_file_paths = out_file_paths.copy()
# Save Textract request metadata (if exists)
if new_textract_request_metadata and isinstance(
new_textract_request_metadata, list
):
all_textract_request_metadata.extend(new_textract_request_metadata)
elif text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION:
if is_pdf(file_path) is False:
out_message = "Please upload a PDF file for text analysis. If you have an image, select 'Image analysis'."
raise Exception(out_message)
# Analyse text-based pdf
print("Redacting file as text-based PDF")
(
pymupdf_doc,
all_pages_decision_process_table,
all_page_line_level_ocr_results_df,
annotations_all_pages,
current_loop_page,
page_break_return,
comprehend_query_number,
all_page_line_level_ocr_results_with_words,
) = redact_text_pdf(
file_path,
language,
chosen_redact_entities,
chosen_redact_comprehend_entities,
in_allow_list_flat,
page_min,
page_max,
current_loop_page,
page_break_return,
annotations_all_pages,
all_page_line_level_ocr_results_df,
all_pages_decision_process_table,
pymupdf_doc,
all_page_line_level_ocr_results_with_words,
pii_identification_method,
comprehend_query_number,
comprehend_client,
custom_recogniser_word_list_flat,
redact_whole_page_list_flat,
max_fuzzy_spelling_mistakes_num,
match_fuzzy_whole_phrase_bool,
page_sizes_df,
document_cropboxes,
text_extraction_only,
output_folder=output_folder,
)
else:
out_message = "No redaction method selected"
print(out_message)
raise Exception(out_message)
# If at last page, save to file
if current_loop_page >= number_of_pages:
print("Current page loop:", current_loop_page, "is the last page.")
latest_file_completed += 1
current_loop_page = 999
if latest_file_completed != len(file_paths_list):
print(
"Completed file number:",
str(latest_file_completed),
"there are more files to do",
)
# Save redacted file
if pii_identification_method != NO_REDACTION_PII_OPTION:
if RETURN_PDF_END_OF_REDACTION is True:
progress(0.9, "Saving redacted file")
if is_pdf(file_path) is False:
out_redacted_pdf_file_path = (
output_folder + pdf_file_name_without_ext + "_redacted.png"
)
# pymupdf_doc is an image list in this case
if isinstance(pymupdf_doc[-1], str):
img = Image.open(pymupdf_doc[-1])
# Otherwise could be an image object
else:
img = pymupdf_doc[-1]
img.save(
out_redacted_pdf_file_path, "PNG", resolution=image_dpi
)
else:
out_redacted_pdf_file_path = (
output_folder + pdf_file_name_without_ext + "_redacted.pdf"
)
print("Saving redacted PDF file:", out_redacted_pdf_file_path)
save_pdf_with_or_without_compression(
pymupdf_doc, out_redacted_pdf_file_path
)
if isinstance(out_redacted_pdf_file_path, str):
out_file_paths.append(out_redacted_pdf_file_path)
else:
out_file_paths.append(out_redacted_pdf_file_path[0])
if not all_page_line_level_ocr_results_df.empty:
all_page_line_level_ocr_results_df = all_page_line_level_ocr_results_df[
["page", "text", "left", "top", "width", "height", "line"]
]
else:
all_page_line_level_ocr_results_df = pd.DataFrame(
columns=["page", "text", "left", "top", "width", "height", "line"]
)
# ocr_file_path = orig_pdf_file_path + "_ocr_output.csv"
ocr_file_path = (
output_folder
+ pdf_file_name_without_ext
+ "_ocr_output_"
+ file_ending
+ ".csv"
)
all_page_line_level_ocr_results_df.sort_values(
["page", "line"], inplace=True
)
all_page_line_level_ocr_results_df.to_csv(
ocr_file_path, index=None, encoding="utf-8-sig"
)
if isinstance(ocr_file_path, str):
out_file_paths.append(ocr_file_path)
else:
duplication_file_path_outputs.append(ocr_file_path[0])
if all_page_line_level_ocr_results_with_words:
all_page_line_level_ocr_results_with_words = merge_page_results(
all_page_line_level_ocr_results_with_words
)
with open(
all_page_line_level_ocr_results_with_words_json_file_path, "w"
) as json_file:
json.dump(
all_page_line_level_ocr_results_with_words,
json_file,
separators=(",", ":"),
)
all_page_line_level_ocr_results_with_words_df = (
word_level_ocr_output_to_dataframe(
all_page_line_level_ocr_results_with_words
)
)
all_page_line_level_ocr_results_with_words_df = (
divide_coordinates_by_page_sizes(
all_page_line_level_ocr_results_with_words_df,
page_sizes_df,
xmin="word_x0",
xmax="word_x1",
ymin="word_y0",
ymax="word_y1",
)
)
if text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION:
# Coordinates need to be reversed for ymin and ymax to match with image annotator objects downstream
if not all_page_line_level_ocr_results_with_words_df.empty:
all_page_line_level_ocr_results_with_words_df["word_y0"] = (
reverse_y_coords(
all_page_line_level_ocr_results_with_words_df, "word_y0"
)
)
all_page_line_level_ocr_results_with_words_df["word_y1"] = (
reverse_y_coords(
all_page_line_level_ocr_results_with_words_df, "word_y1"
)
)
all_page_line_level_ocr_results_with_words_df["line_text"] = ""
all_page_line_level_ocr_results_with_words_df["line_x0"] = ""
all_page_line_level_ocr_results_with_words_df["line_x1"] = ""
all_page_line_level_ocr_results_with_words_df["line_y0"] = ""
all_page_line_level_ocr_results_with_words_df["line_y1"] = ""
all_page_line_level_ocr_results_with_words_df.sort_values(
["page", "line", "word_x0"], inplace=True
)
all_page_line_level_ocr_results_with_words_df_file_path = (
all_page_line_level_ocr_results_with_words_json_file_path.replace(
".json", ".csv"
)
)
all_page_line_level_ocr_results_with_words_df.to_csv(
all_page_line_level_ocr_results_with_words_df_file_path,
index=None,
encoding="utf-8-sig",
)
if (
all_page_line_level_ocr_results_with_words_json_file_path
not in log_files_output_paths
):
if isinstance(
all_page_line_level_ocr_results_with_words_json_file_path, str
):
log_files_output_paths.append(
all_page_line_level_ocr_results_with_words_json_file_path
)
else:
log_files_output_paths.append(
all_page_line_level_ocr_results_with_words_json_file_path[0]
)
log_files_output_paths.append(
all_page_line_level_ocr_results_with_words_json_file_path
)
if (
all_page_line_level_ocr_results_with_words_df_file_path
not in log_files_output_paths
):
if isinstance(
all_page_line_level_ocr_results_with_words_df_file_path, str
):
log_files_output_paths.append(
all_page_line_level_ocr_results_with_words_df_file_path
)
else:
log_files_output_paths.append(
all_page_line_level_ocr_results_with_words_df_file_path[0]
)
if (
all_page_line_level_ocr_results_with_words_df_file_path
not in out_file_paths
):
if isinstance(
all_page_line_level_ocr_results_with_words_df_file_path, str
):
out_file_paths.append(
all_page_line_level_ocr_results_with_words_df_file_path
)
else:
out_file_paths.append(
all_page_line_level_ocr_results_with_words_df_file_path[0]
)
# Convert the gradio annotation boxes to relative coordinates
progress(0.93, "Creating review file output")
page_sizes = page_sizes_df.to_dict(orient="records")
all_image_annotations_df = convert_annotation_data_to_dataframe(
annotations_all_pages
)
all_image_annotations_df = divide_coordinates_by_page_sizes(
all_image_annotations_df,
page_sizes_df,
xmin="xmin",
xmax="xmax",
ymin="ymin",
ymax="ymax",
)
annotations_all_pages_divide = create_annotation_dicts_from_annotation_df(
all_image_annotations_df, page_sizes
)
annotations_all_pages_divide = remove_duplicate_images_with_blank_boxes(
annotations_all_pages_divide
)
# Save the gradio_annotation_boxes to a review csv file
review_file_state = convert_annotation_json_to_review_df(
annotations_all_pages_divide,
all_pages_decision_process_table,
page_sizes=page_sizes,
)
# Don't need page sizes in outputs
review_file_state.drop(
[
"image_width",
"image_height",
"mediabox_width",
"mediabox_height",
"cropbox_width",
"cropbox_height",
],
axis=1,
inplace=True,
errors="ignore",
)
if isinstance(review_file_path, str):
review_file_state.to_csv(
review_file_path, index=None, encoding="utf-8-sig"
)
else:
review_file_state.to_csv(
review_file_path[0], index=None, encoding="utf-8-sig"
)
if pii_identification_method != NO_REDACTION_PII_OPTION:
if isinstance(review_file_path, str):
out_file_paths.append(review_file_path)
else:
out_file_paths.append(review_file_path[0])
# Make a combined message for the file
if isinstance(combined_out_message, list):
combined_out_message = "\n".join(combined_out_message)
elif combined_out_message is None:
combined_out_message = ""
if isinstance(out_message, list) and out_message:
combined_out_message = combined_out_message + "\n".join(out_message)
elif isinstance(out_message, str) and out_message:
combined_out_message = combined_out_message + "\n" + out_message
toc = time.perf_counter()
time_taken = toc - tic
estimated_time_taken_state += time_taken
out_time_message = (
f" Redacted in {estimated_time_taken_state:0.1f} seconds."
)
combined_out_message = (
combined_out_message + " " + out_time_message
) # Ensure this is a single string
estimate_total_processing_time = sum_numbers_before_seconds(
combined_out_message
)
else:
toc = time.perf_counter()
time_taken = toc - tic
estimated_time_taken_state += time_taken
# If textract requests made, write to logging file. Also record number of Textract requests
if all_textract_request_metadata and isinstance(
all_textract_request_metadata, list
):
all_request_metadata_str = "\n".join(all_textract_request_metadata).strip()
# all_textract_request_metadata_file_path is constructed by output_folder + filename
# Split output_folder (trusted base) from pdf_file_name_without_ext + "_textract_metadata.txt" (untrusted)
secure_file_write(
output_folder,
pdf_file_name_without_ext + "_textract_metadata.txt",
all_request_metadata_str,
)
# Reconstruct the full path for logging purposes
all_textract_request_metadata_file_path = (
output_folder + pdf_file_name_without_ext + "_textract_metadata.txt"
)
# Add the request metadata to the log outputs if not there already
if all_textract_request_metadata_file_path not in log_files_output_paths:
if isinstance(all_textract_request_metadata_file_path, str):
log_files_output_paths.append(all_textract_request_metadata_file_path)
else:
log_files_output_paths.append(
all_textract_request_metadata_file_path[0]
)
new_textract_query_numbers = len(all_textract_request_metadata)
total_textract_query_number += new_textract_query_numbers
# Ensure no duplicated output files
log_files_output_paths = sorted(list(set(log_files_output_paths)))
out_file_paths = sorted(list(set(out_file_paths)))
# Output file paths
if not review_file_path:
review_out_file_paths = [prepared_pdf_file_paths[-1]]
else:
review_out_file_paths = [prepared_pdf_file_paths[-1], review_file_path]
if total_textract_query_number > number_of_pages:
total_textract_query_number = number_of_pages
page_break_return = True
return (
combined_out_message,
out_file_paths,
out_file_paths,
latest_file_completed,
log_files_output_paths,
log_files_output_paths,
estimated_time_taken_state,
all_request_metadata_str,
pymupdf_doc,
annotations_all_pages_divide,
current_loop_page,
page_break_return,
all_page_line_level_ocr_results_df,
all_pages_decision_process_table,
comprehend_query_number,
review_out_file_paths,
annotate_max_pages,
annotate_max_pages,
prepared_pdf_file_paths,
pdf_image_file_paths,
review_file_state,
page_sizes,
duplication_file_path_outputs,
duplication_file_path_outputs,
review_file_path,
total_textract_query_number,
ocr_file_path,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
all_page_line_level_ocr_results_with_words_df,
review_file_state,
task_textbox,
)
def convert_pikepdf_coords_to_pymupdf(
pymupdf_page: Page, pikepdf_bbox, type="pikepdf_annot"
):
"""
Convert annotations from pikepdf to pymupdf format, handling the mediabox larger than rect.
"""
# Use cropbox if available, otherwise use mediabox
reference_box = pymupdf_page.rect
mediabox = pymupdf_page.mediabox
reference_box_height = reference_box.height
reference_box_width = reference_box.width
# Convert PyMuPDF coordinates back to PDF coordinates (bottom-left origin)
media_height = mediabox.height
media_width = mediabox.width
media_reference_y_diff = media_height - reference_box_height
media_reference_x_diff = media_width - reference_box_width
y_diff_ratio = media_reference_y_diff / reference_box_height
x_diff_ratio = media_reference_x_diff / reference_box_width
# Extract the annotation rectangle field
if type == "pikepdf_annot":
rect_field = pikepdf_bbox["/Rect"]
else:
rect_field = pikepdf_bbox
rect_coordinates = [float(coord) for coord in rect_field] # Convert to floats
# Unpack coordinates
x1, y1, x2, y2 = rect_coordinates
new_x1 = x1 - (media_reference_x_diff * x_diff_ratio)
new_y1 = media_height - y2 - (media_reference_y_diff * y_diff_ratio)
new_x2 = x2 - (media_reference_x_diff * x_diff_ratio)
new_y2 = media_height - y1 - (media_reference_y_diff * y_diff_ratio)
return new_x1, new_y1, new_x2, new_y2
def convert_pikepdf_to_image_coords(
pymupdf_page, annot, image: Image, type="pikepdf_annot"
):
"""
Convert annotations from pikepdf coordinates to image coordinates.
"""
# Get the dimensions of the page in points with pymupdf
rect_height = pymupdf_page.rect.height
rect_width = pymupdf_page.rect.width
# Get the dimensions of the image
image_page_width, image_page_height = image.size
# Calculate scaling factors between pymupdf and PIL image
scale_width = image_page_width / rect_width
scale_height = image_page_height / rect_height
# Extract the /Rect field
if type == "pikepdf_annot":
rect_field = annot["/Rect"]
else:
rect_field = annot
# Convert the extracted /Rect field to a list of floats
rect_coordinates = [float(coord) for coord in rect_field]
# Convert the Y-coordinates (flip using the image height)
x1, y1, x2, y2 = rect_coordinates
x1_image = x1 * scale_width
new_y1_image = image_page_height - (
y2 * scale_height
) # Flip Y0 (since it starts from bottom)
x2_image = x2 * scale_width
new_y2_image = image_page_height - (y1 * scale_height) # Flip Y1
return x1_image, new_y1_image, x2_image, new_y2_image
def convert_pikepdf_decision_output_to_image_coords(
pymupdf_page: Document, pikepdf_decision_ouput_data: List[dict], image: Image
):
if isinstance(image, str):
image_path = image
image = Image.open(image_path)
# Loop through each item in the data
for item in pikepdf_decision_ouput_data:
# Extract the bounding box
bounding_box = item["boundingBox"]
# Create a pikepdf_bbox dictionary to match the expected input
pikepdf_bbox = {"/Rect": bounding_box}
# Call the conversion function
new_x1, new_y1, new_x2, new_y2 = convert_pikepdf_to_image_coords(
pymupdf_page, pikepdf_bbox, image, type="pikepdf_annot"
)
# Update the original object with the new bounding box values
item["boundingBox"] = [new_x1, new_y1, new_x2, new_y2]
return pikepdf_decision_ouput_data
def convert_image_coords_to_pymupdf(
pymupdf_page: Document, annot: dict, image: Image, type: str = "image_recognizer"
):
"""
Converts an image with redaction coordinates from a CustomImageRecognizerResult or pikepdf object with image coordinates to pymupdf coordinates.
"""
rect_height = pymupdf_page.rect.height
rect_width = pymupdf_page.rect.width
image_page_width, image_page_height = image.size
# Calculate scaling factors between PIL image and pymupdf
scale_width = rect_width / image_page_width
scale_height = rect_height / image_page_height
# Calculate scaled coordinates
if type == "image_recognizer":
x1 = annot.left * scale_width # + page_x_adjust
new_y1 = (
annot.top * scale_height
) # - page_y_adjust # Flip Y0 (since it starts from bottom)
x2 = (annot.left + annot.width) * scale_width # + page_x_adjust # Calculate x1
new_y2 = (
annot.top + annot.height
) * scale_height # - page_y_adjust # Calculate y1 correctly
# Else assume it is a pikepdf derived object
else:
rect_field = annot["/Rect"]
rect_coordinates = [float(coord) for coord in rect_field] # Convert to floats
# Unpack coordinates
x1, y1, x2, y2 = rect_coordinates
x1 = x1 * scale_width # + page_x_adjust
new_y1 = (
y2 + (y1 - y2)
) * scale_height # - page_y_adjust # Calculate y1 correctly
x2 = (x1 + (x2 - x1)) * scale_width # + page_x_adjust # Calculate x1
new_y2 = (
y2 * scale_height
) # - page_y_adjust # Flip Y0 (since it starts from bottom)
return x1, new_y1, x2, new_y2
def convert_gradio_image_annotator_object_coords_to_pymupdf(
pymupdf_page: Page, annot: dict, image: Image, image_dimensions: dict = None
):
"""
Converts an image with redaction coordinates from a gradio annotation component to pymupdf coordinates.
"""
rect_height = pymupdf_page.rect.height
rect_width = pymupdf_page.rect.width
if image_dimensions:
image_page_width = image_dimensions["image_width"]
image_page_height = image_dimensions["image_height"]
elif image:
image_page_width, image_page_height = image.size
# Calculate scaling factors between PIL image and pymupdf
scale_width = rect_width / image_page_width
scale_height = rect_height / image_page_height
# Calculate scaled coordinates
x1 = annot["xmin"] * scale_width # + page_x_adjust
new_y1 = (
annot["ymin"] * scale_height
) # - page_y_adjust # Flip Y0 (since it starts from bottom)
x2 = (annot["xmax"]) * scale_width # + page_x_adjust # Calculate x1
new_y2 = (annot["ymax"]) * scale_height # - page_y_adjust # Calculate y1 correctly
return x1, new_y1, x2, new_y2
def move_page_info(file_path: str) -> str:
# Split the string at '.png'
base, extension = file_path.rsplit(".pdf", 1)
# Extract the page info
page_info = base.split("page ")[1].split(" of")[0] # Get the page number
new_base = base.replace(
f"page {page_info} of ", ""
) # Remove the page info from the original position
# Construct the new file path
new_file_path = f"{new_base}_page_{page_info}.png"
return new_file_path
def prepare_custom_image_recogniser_result_annotation_box(
page: Page, annot: dict, image: Image, page_sizes_df: pd.DataFrame
):
"""
Prepare an image annotation box and coordinates based on a CustomImageRecogniserResult, PyMuPDF page, and PIL Image.
"""
img_annotation_box = {}
# For efficient lookup, set 'page' as index if it's not already
if "page" in page_sizes_df.columns:
page_sizes_df = page_sizes_df.set_index("page")
# PyMuPDF page numbers are 0-based, DataFrame index assumed 1-based
page_num_one_based = page.number + 1
pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = 0, 0, 0, 0 # Initialize defaults
if image:
pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = (
convert_image_coords_to_pymupdf(page, annot, image)
)
else:
# --- Calculate coordinates when no image is present ---
# Assumes annot coords are normalized relative to MediaBox (top-left origin)
try:
# 1. Get MediaBox dimensions from the DataFrame
page_info = page_sizes_df.loc[page_num_one_based]
mb_width = page_info["mediabox_width"]
mb_height = page_info["mediabox_height"]
x_offset = page_info["cropbox_x_offset"]
y_offset = page_info["cropbox_y_offset_from_top"]
# Check for invalid dimensions
if mb_width <= 0 or mb_height <= 0:
print(
f"Warning: Invalid MediaBox dimensions ({mb_width}x{mb_height}) for page {page_num_one_based}. Setting coords to 0."
)
else:
pymupdf_x1 = annot.left - x_offset
pymupdf_x2 = annot.left + annot.width - x_offset
pymupdf_y1 = annot.top - y_offset
pymupdf_y2 = annot.top + annot.height - y_offset
except KeyError:
print(
f"Warning: Page number {page_num_one_based} not found in page_sizes_df. Cannot get MediaBox dimensions. Setting coords to 0."
)
except AttributeError as e:
print(
f"Error accessing attributes ('left', 'top', etc.) on 'annot' object for page {page_num_one_based}: {e}"
)
except Exception as e:
print(
f"Error during coordinate calculation for page {page_num_one_based}: {e}"
)
rect = Rect(
pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2
) # Create the PyMuPDF Rect
# Now creating image annotation object
image_x1 = annot.left
image_x2 = annot.left + annot.width
image_y1 = annot.top
image_y2 = annot.top + annot.height
# Create image annotation boxes
img_annotation_box["xmin"] = image_x1
img_annotation_box["ymin"] = image_y1
img_annotation_box["xmax"] = image_x2 # annot.left + annot.width
img_annotation_box["ymax"] = image_y2 # annot.top + annot.height
img_annotation_box["color"] = (0, 0, 0)
try:
img_annotation_box["label"] = str(annot.entity_type)
except Exception as e:
print(f"Error getting entity type: {e}")
img_annotation_box["label"] = "Redaction"
if hasattr(annot, "text") and annot.text:
img_annotation_box["text"] = str(annot.text)
else:
img_annotation_box["text"] = ""
# Assign an id
img_annotation_box = fill_missing_box_ids(img_annotation_box)
return img_annotation_box, rect
def convert_pikepdf_annotations_to_result_annotation_box(
page: Page,
annot: dict,
image: Image = None,
convert_pikepdf_to_pymupdf_coords: bool = True,
page_sizes_df: pd.DataFrame = pd.DataFrame(),
image_dimensions: dict = {},
):
"""
Convert redaction objects with pikepdf coordinates to annotation boxes for PyMuPDF that can then be redacted from the document. First 1. converts pikepdf to pymupdf coordinates, then 2. converts pymupdf coordinates to image coordinates if page is an image.
"""
img_annotation_box = {}
page_no = page.number
if convert_pikepdf_to_pymupdf_coords is True:
pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = (
convert_pikepdf_coords_to_pymupdf(page, annot)
)
else:
pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = (
convert_image_coords_to_pymupdf(
page, annot, image, type="pikepdf_image_coords"
)
)
rect = Rect(pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2)
convert_df = pd.DataFrame(
{
"page": [page_no],
"xmin": [pymupdf_x1],
"ymin": [pymupdf_y1],
"xmax": [pymupdf_x2],
"ymax": [pymupdf_y2],
}
)
converted_df = convert_df # divide_coordinates_by_page_sizes(convert_df, page_sizes_df, xmin="xmin", xmax="xmax", ymin="ymin", ymax="ymax")
img_annotation_box["xmin"] = converted_df["xmin"].max()
img_annotation_box["ymin"] = converted_df["ymin"].max()
img_annotation_box["xmax"] = converted_df["xmax"].max()
img_annotation_box["ymax"] = converted_df["ymax"].max()
img_annotation_box["color"] = (0, 0, 0)
if isinstance(annot, Dictionary):
img_annotation_box["label"] = str(annot["/T"])
if hasattr(annot, "Contents"):
img_annotation_box["text"] = str(annot.Contents)
else:
img_annotation_box["text"] = ""
else:
img_annotation_box["label"] = "REDACTION"
img_annotation_box["text"] = ""
return img_annotation_box, rect
def set_cropbox_safely(page: Page, original_cropbox: Optional[Rect]):
"""
Sets the cropbox of a PyMuPDF page safely and defensively.
If the 'original_cropbox' is valid (i.e., a fitz.Rect instance, not None, not empty,
not infinite, and fully contained within the page's mediabox), it is set as the cropbox.
Otherwise, the page's mediabox is used, and a warning is printed to explain why.
Args:
page: The PyMuPDF page object.
original_cropbox: The Rect representing the desired cropbox.
"""
mediabox = page.mediabox
reason_for_defaulting = ""
# Check for None
if original_cropbox is None:
reason_for_defaulting = "the original cropbox is None."
# Check for incorrect type
elif not isinstance(original_cropbox, Rect):
reason_for_defaulting = f"the original cropbox is not a fitz.Rect instance (got {type(original_cropbox)})."
else:
# Normalise the cropbox (ensures x0 < x1 and y0 < y1)
original_cropbox.normalize()
# Check for empty or infinite or out-of-bounds
if original_cropbox.is_empty:
reason_for_defaulting = (
f"the provided original cropbox {original_cropbox} is empty."
)
elif original_cropbox.is_infinite:
reason_for_defaulting = (
f"the provided original cropbox {original_cropbox} is infinite."
)
elif not mediabox.contains(original_cropbox):
reason_for_defaulting = (
f"the provided original cropbox {original_cropbox} is not fully contained "
f"within the page's mediabox {mediabox}."
)
if reason_for_defaulting:
print(
f"Warning (Page {page.number}): Cannot use original cropbox because {reason_for_defaulting} "
f"Defaulting to the page's mediabox as the cropbox."
)
page.set_cropbox(mediabox)
else:
page.set_cropbox(original_cropbox)
def redact_page_with_pymupdf(
page: Page,
page_annotations: dict,
image: Image = None,
custom_colours: bool = False,
redact_whole_page: bool = False,
convert_pikepdf_to_pymupdf_coords: bool = True,
original_cropbox: List[Rect] = list(),
page_sizes_df: pd.DataFrame = pd.DataFrame(),
):
rect_height = page.rect.height
rect_width = page.rect.width
mediabox_height = page.mediabox.height
mediabox_width = page.mediabox.width
page_no = page.number
page_num_reported = page_no + 1
page_sizes_df[["page"]] = page_sizes_df[["page"]].apply(
pd.to_numeric, errors="coerce"
)
# Check if image dimensions for page exist in page_sizes_df
image_dimensions = {}
if not image and "image_width" in page_sizes_df.columns:
page_sizes_df[["image_width"]] = page_sizes_df[["image_width"]].apply(
pd.to_numeric, errors="coerce"
)
page_sizes_df[["image_height"]] = page_sizes_df[["image_height"]].apply(
pd.to_numeric, errors="coerce"
)
image_dimensions["image_width"] = page_sizes_df.loc[
page_sizes_df["page"] == page_num_reported, "image_width"
].max()
image_dimensions["image_height"] = page_sizes_df.loc[
page_sizes_df["page"] == page_num_reported, "image_height"
].max()
if pd.isna(image_dimensions["image_width"]):
image_dimensions = {}
out_annotation_boxes = {}
all_image_annotation_boxes = list()
if isinstance(image, Image.Image):
image_path = move_page_info(str(page))
image.save(image_path)
elif isinstance(image, str):
if os.path.exists(image):
image_path = image
image = Image.open(image_path)
elif "image_path" in page_sizes_df.columns:
try:
image_path = page_sizes_df.loc[
page_sizes_df["page"] == (page_no + 1), "image_path"
].iloc[0]
except IndexError:
image_path = ""
image = None
else:
image_path = ""
image = None
else:
# print("image is not an Image object or string")
image_path = ""
image = None
# Check if this is an object used in the Gradio Annotation component
if isinstance(page_annotations, dict):
page_annotations = page_annotations["boxes"]
for annot in page_annotations:
# Check if an Image recogniser result, or a Gradio annotation object
if (isinstance(annot, CustomImageRecognizerResult)) | isinstance(annot, dict):
img_annotation_box = {}
# Should already be in correct format if img_annotator_box is an input
if isinstance(annot, dict):
annot = fill_missing_box_ids(annot)
img_annotation_box = annot
box_coordinates = (
img_annotation_box["xmin"],
img_annotation_box["ymin"],
img_annotation_box["xmax"],
img_annotation_box["ymax"],
)
# Check if all coordinates are equal to or less than 1
are_coordinates_relative = all(coord <= 1 for coord in box_coordinates)
if are_coordinates_relative is True:
# Check if coordinates are relative, if so then multiply by mediabox size
pymupdf_x1 = img_annotation_box["xmin"] * mediabox_width
pymupdf_y1 = img_annotation_box["ymin"] * mediabox_height
pymupdf_x2 = img_annotation_box["xmax"] * mediabox_width
pymupdf_y2 = img_annotation_box["ymax"] * mediabox_height
elif image_dimensions or image:
pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = (
convert_gradio_image_annotator_object_coords_to_pymupdf(
page, img_annotation_box, image, image_dimensions
)
)
else:
print(
"Could not convert image annotator coordinates in redact_page_with_pymupdf"
)
print("img_annotation_box", img_annotation_box)
pymupdf_x1 = img_annotation_box["xmin"]
pymupdf_y1 = img_annotation_box["ymin"]
pymupdf_x2 = img_annotation_box["xmax"]
pymupdf_y2 = img_annotation_box["ymax"]
if hasattr(annot, "text") and annot.text:
img_annotation_box["text"] = str(annot.text)
else:
img_annotation_box["text"] = ""
rect = Rect(
pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2
) # Create the PyMuPDF Rect
# Else should be CustomImageRecognizerResult
elif isinstance(annot, CustomImageRecognizerResult):
# print("annot is a CustomImageRecognizerResult")
img_annotation_box, rect = (
prepare_custom_image_recogniser_result_annotation_box(
page, annot, image, page_sizes_df
)
)
# Else it should be a pikepdf annotation object
else:
if not image:
convert_pikepdf_to_pymupdf_coords = True
else:
convert_pikepdf_to_pymupdf_coords = False
img_annotation_box, rect = (
convert_pikepdf_annotations_to_result_annotation_box(
page,
annot,
image,
convert_pikepdf_to_pymupdf_coords,
page_sizes_df,
image_dimensions=image_dimensions,
)
)
img_annotation_box = fill_missing_box_ids(img_annotation_box)
all_image_annotation_boxes.append(img_annotation_box)
# Redact the annotations from the document
redact_single_box(page, rect, img_annotation_box, custom_colours)
# If whole page is to be redacted, do that here
if redact_whole_page is True:
whole_page_img_annotation_box = redact_whole_pymupdf_page(
rect_height, rect_width, page, custom_colours, border=5
)
all_image_annotation_boxes.append(whole_page_img_annotation_box)
out_annotation_boxes = {
"image": image_path, # Image.open(image_path), #image_path,
"boxes": all_image_annotation_boxes,
}
page.apply_redactions(images=0, graphics=0)
set_cropbox_safely(page, original_cropbox)
# page.set_cropbox(original_cropbox)
# Set CropBox to original size
page.clean_contents()
return page, out_annotation_boxes
###
# IMAGE-BASED OCR PDF TEXT DETECTION/REDACTION WITH TESSERACT OR AWS TEXTRACT
###
def merge_img_bboxes(
bboxes: list,
combined_results: Dict,
page_signature_recogniser_results: list = list(),
page_handwriting_recogniser_results: list = list(),
handwrite_signature_checkbox: List[str] = [
"Extract handwriting",
"Extract signatures",
],
horizontal_threshold: int = 50,
vertical_threshold: int = 12,
):
"""
Merges bounding boxes for image annotations based on the provided results from signature and handwriting recognizers.
Args:
bboxes (list): A list of bounding boxes to be merged.
combined_results (Dict): A dictionary containing combined results with line text and their corresponding bounding boxes.
page_signature_recogniser_results (list, optional): A list of results from the signature recognizer. Defaults to an empty list.
page_handwriting_recogniser_results (list, optional): A list of results from the handwriting recognizer. Defaults to an empty list.
handwrite_signature_checkbox (List[str], optional): A list of options indicating whether to extract handwriting and signatures. Defaults to ["Extract handwriting", "Extract signatures"].
horizontal_threshold (int, optional): The threshold for merging bounding boxes horizontally. Defaults to 50.
vertical_threshold (int, optional): The threshold for merging bounding boxes vertically. Defaults to 12.
Returns:
None: This function modifies the bounding boxes in place and does not return a value.
"""
all_bboxes = list()
merged_bboxes = list()
grouped_bboxes = defaultdict(list)
# Deep copy original bounding boxes to retain them
original_bboxes = copy.deepcopy(bboxes)
# Process signature and handwriting results
if page_signature_recogniser_results or page_handwriting_recogniser_results:
if "Extract handwriting" in handwrite_signature_checkbox:
print("Extracting handwriting in merge_img_bboxes function")
merged_bboxes.extend(copy.deepcopy(page_handwriting_recogniser_results))
if "Extract signatures" in handwrite_signature_checkbox:
print("Extracting signatures in merge_img_bboxes function")
merged_bboxes.extend(copy.deepcopy(page_signature_recogniser_results))
# Reconstruct bounding boxes for substrings of interest
reconstructed_bboxes = list()
for bbox in bboxes:
bbox_box = (bbox.left, bbox.top, bbox.left + bbox.width, bbox.top + bbox.height)
for line_text, line_info in combined_results.items():
line_box = line_info["bounding_box"]
if bounding_boxes_overlap(bbox_box, line_box):
if bbox.text in line_text:
start_char = line_text.index(bbox.text)
end_char = start_char + len(bbox.text)
relevant_words = list()
current_char = 0
for word in line_info["words"]:
word_end = current_char + len(word["text"])
if (
current_char <= start_char < word_end
or current_char < end_char <= word_end
or (start_char <= current_char and word_end <= end_char)
):
relevant_words.append(word)
if word_end >= end_char:
break
current_char = word_end
if not word["text"].endswith(" "):
current_char += 1 # +1 for space if the word doesn't already end with a space
if relevant_words:
left = min(word["bounding_box"][0] for word in relevant_words)
top = min(word["bounding_box"][1] for word in relevant_words)
right = max(word["bounding_box"][2] for word in relevant_words)
bottom = max(word["bounding_box"][3] for word in relevant_words)
combined_text = " ".join(
word["text"] for word in relevant_words
)
reconstructed_bbox = CustomImageRecognizerResult(
bbox.entity_type,
bbox.start,
bbox.end,
bbox.score,
left,
top,
right - left, # width
bottom - top, # height,
combined_text,
)
# reconstructed_bboxes.append(bbox) # Add original bbox
reconstructed_bboxes.append(
reconstructed_bbox
) # Add merged bbox
break
else:
reconstructed_bboxes.append(bbox)
# Group reconstructed bboxes by approximate vertical proximity
for box in reconstructed_bboxes:
grouped_bboxes[round(box.top / vertical_threshold)].append(box)
# Merge within each group
for _, group in grouped_bboxes.items():
group.sort(key=lambda box: box.left)
merged_box = group[0]
for next_box in group[1:]:
if (
next_box.left - (merged_box.left + merged_box.width)
<= horizontal_threshold
):
if next_box.text != merged_box.text:
new_text = merged_box.text + " " + next_box.text
else:
new_text = merged_box.text
if merged_box.entity_type != next_box.entity_type:
new_entity_type = (
merged_box.entity_type + " - " + next_box.entity_type
)
else:
new_entity_type = merged_box.entity_type
new_left = min(merged_box.left, next_box.left)
new_top = min(merged_box.top, next_box.top)
new_width = (
max(
merged_box.left + merged_box.width,
next_box.left + next_box.width,
)
- new_left
)
new_height = (
max(
merged_box.top + merged_box.height,
next_box.top + next_box.height,
)
- new_top
)
merged_box = CustomImageRecognizerResult(
new_entity_type,
merged_box.start,
merged_box.end,
merged_box.score,
new_left,
new_top,
new_width,
new_height,
new_text,
)
else:
merged_bboxes.append(merged_box)
merged_box = next_box
merged_bboxes.append(merged_box)
all_bboxes.extend(original_bboxes)
all_bboxes.extend(merged_bboxes)
# Return the unique original and merged bounding boxes
unique_bboxes = list(
{
(bbox.left, bbox.top, bbox.width, bbox.height): bbox for bbox in all_bboxes
}.values()
)
return unique_bboxes
def redact_image_pdf(
file_path: str,
pdf_image_file_paths: List[str],
language: str,
chosen_redact_entities: List[str],
chosen_redact_comprehend_entities: List[str],
allow_list: List[str] = None,
page_min: int = 0,
page_max: int = 999,
text_extraction_method: str = TESSERACT_TEXT_EXTRACT_OPTION,
handwrite_signature_checkbox: List[str] = [
"Extract handwriting",
"Extract signatures",
],
textract_request_metadata: list = list(),
current_loop_page: int = 0,
page_break_return: bool = False,
annotations_all_pages: List = list(),
all_page_line_level_ocr_results_df: pd.DataFrame = pd.DataFrame(
columns=["page", "text", "left", "top", "width", "height", "line"]
),
all_pages_decision_process_table: pd.DataFrame = pd.DataFrame(
columns=[
"image_path",
"page",
"label",
"xmin",
"xmax",
"ymin",
"ymax",
"boundingBox",
"text",
"start",
"end",
"score",
"id",
]
),
pymupdf_doc: Document = list(),
pii_identification_method: str = "Local",
comprehend_query_number: int = 0,
comprehend_client: str = "",
textract_client: str = "",
in_deny_list: List[str] = list(),
redact_whole_page_list: List[str] = list(),
max_fuzzy_spelling_mistakes_num: int = 1,
match_fuzzy_whole_phrase_bool: bool = True,
page_sizes_df: pd.DataFrame = pd.DataFrame(),
text_extraction_only: bool = False,
all_page_line_level_ocr_results=list(),
all_page_line_level_ocr_results_with_words=list(),
chosen_local_model: str = "tesseract",
page_break_val: int = int(PAGE_BREAK_VALUE),
log_files_output_paths: List = list(),
max_time: int = int(MAX_TIME_VALUE),
nlp_analyser: AnalyzerEngine = nlp_analyser,
output_folder: str = OUTPUT_FOLDER,
progress=Progress(track_tqdm=True),
):
"""
This function redacts sensitive information from a PDF document. It takes the following parameters in order:
- file_path (str): The path to the PDF file to be redacted.
- pdf_image_file_paths (List[str]): A list of paths to the PDF file pages converted to images.
- language (str): The language of the text in the PDF.
- chosen_redact_entities (List[str]): A list of entity types to redact from the PDF.
- chosen_redact_comprehend_entities (List[str]): A list of entity types to redact from the list allowed by the AWS Comprehend service.
- allow_list (List[str], optional): A list of entity types to allow in the PDF. Defaults to None.
- page_min (int, optional): The minimum page number to start redaction from. Defaults to 0.
- page_max (int, optional): The maximum page number to end redaction at. Defaults to 999.
- text_extraction_method (str, optional): The type of analysis to perform on the PDF. Defaults to TESSERACT_TEXT_EXTRACT_OPTION.
- handwrite_signature_checkbox (List[str], optional): A list of options for redacting handwriting and signatures. Defaults to ["Extract handwriting", "Extract signatures"].
- textract_request_metadata (list, optional): Metadata related to the redaction request. Defaults to an empty string.
- current_loop_page (int, optional): The current page being processed. Defaults to 0.
- page_break_return (bool, optional): Indicates if the function should return after a page break. Defaults to False.
- annotations_all_pages (List, optional): List of annotations on all pages that is used by the gradio_image_annotation object.
- all_page_line_level_ocr_results_df (pd.DataFrame, optional): All line level OCR results for the document as a Pandas dataframe,
- all_pages_decision_process_table (pd.DataFrame, optional): All redaction decisions for document as a Pandas dataframe.
- pymupdf_doc (Document, optional): The document as a PyMupdf object.
- pii_identification_method (str, optional): The method to redact personal information. Either 'Local' (spacy model), or 'AWS Comprehend' (AWS Comprehend API).
- comprehend_query_number (int, optional): A counter tracking the number of queries to AWS Comprehend.
- comprehend_client (optional): A connection to the AWS Comprehend service via the boto3 package.
- textract_client (optional): A connection to the AWS Textract service via the boto3 package.
- in_deny_list (optional): A list of custom words that the user has chosen specifically to redact.
- redact_whole_page_list (optional, List[str]): A list of pages to fully redact.
- max_fuzzy_spelling_mistakes_num (int, optional): The maximum number of spelling mistakes allowed in a searched phrase for fuzzy matching. Can range from 0-9.
- match_fuzzy_whole_phrase_bool (bool, optional): A boolean where 'True' means that the whole phrase is fuzzy matched, and 'False' means that each word is fuzzy matched separately (excluding stop words).
- page_sizes_df (pd.DataFrame, optional): A pandas dataframe of PDF page sizes in PDF or image format.
- text_extraction_only (bool, optional): Should the function only extract text, or also do redaction.
- all_page_line_level_ocr_results (optional): List of all page line level OCR results.
- all_page_line_level_ocr_results_with_words (optional): List of all page line level OCR results with words.
- chosen_local_model (str, optional): The local model chosen for OCR. Defaults to "tesseract", other choices are "paddle" for PaddleOCR, or "hybrid" for a combination of both.
- page_break_val (int, optional): The value at which to trigger a page break. Defaults to PAGE_BREAK_VALUE.
- log_files_output_paths (List, optional): List of file paths used for saving redaction process logging results.
- max_time (int, optional): The maximum amount of time (s) that the function should be running before it breaks. To avoid timeout errors with some APIs.
- nlp_analyser (AnalyzerEngine, optional): The nlp_analyser object to use for entity detection. Defaults to nlp_analyser.
- output_folder (str, optional): The folder for file outputs.
- progress (Progress, optional): A progress tracker for the redaction process. Defaults to a Progress object with track_tqdm set to True.
The function returns a redacted PDF document along with processing output objects.
"""
tic = time.perf_counter()
file_name = get_file_name_without_type(file_path)
comprehend_query_number_new = 0
# Try updating the supported languages for the spacy analyser
try:
nlp_analyser = create_nlp_analyser(language, existing_nlp_analyser=nlp_analyser)
# Check list of nlp_analyser recognisers and languages
if language != "en":
gr.Info(
f"Language: {language} only supports the following entity detection: {str(nlp_analyser.registry.get_supported_entities(languages=[language]))}"
)
except Exception as e:
print(f"Error creating nlp_analyser for {language}: {e}")
raise Exception(f"Error creating nlp_analyser for {language}: {e}")
# Update custom word list analyser object with any new words that have been added to the custom deny list
if in_deny_list:
nlp_analyser.registry.remove_recognizer("CUSTOM")
new_custom_recogniser = custom_word_list_recogniser(in_deny_list)
nlp_analyser.registry.add_recognizer(new_custom_recogniser)
nlp_analyser.registry.remove_recognizer("CustomWordFuzzyRecognizer")
new_custom_fuzzy_recogniser = CustomWordFuzzyRecognizer(
supported_entities=["CUSTOM_FUZZY"],
custom_list=in_deny_list,
spelling_mistakes_max=max_fuzzy_spelling_mistakes_num,
search_whole_phrase=match_fuzzy_whole_phrase_bool,
)
nlp_analyser.registry.add_recognizer(new_custom_fuzzy_recogniser)
# Only load in PaddleOCR models if not running Textract
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
image_analyser = CustomImageAnalyzerEngine(
analyzer_engine=nlp_analyser, ocr_engine="tesseract", language=language
)
else:
image_analyser = CustomImageAnalyzerEngine(
analyzer_engine=nlp_analyser,
ocr_engine=chosen_local_model,
language=language,
)
if pii_identification_method == "AWS Comprehend" and comprehend_client == "":
out_message = "Connection to AWS Comprehend service unsuccessful."
print(out_message)
raise Exception(out_message)
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and textract_client == "":
out_message_warning = "Connection to AWS Textract service unsuccessful. Redaction will only continue if local AWS Textract results can be found."
print(out_message_warning)
# raise Exception(out_message)
number_of_pages = pymupdf_doc.page_count
print("Number of pages:", str(number_of_pages))
# Check that page_min and page_max are within expected ranges
if page_max > number_of_pages or page_max == 0:
page_max = number_of_pages
if page_min <= 0:
page_min = 0
else:
page_min = page_min - 1
print("Page range:", str(page_min + 1), "to", str(page_max))
# If running Textract, check if file already exists. If it does, load in existing data
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
textract_json_file_path = output_folder + file_name + "_textract.json"
textract_data, is_missing, log_files_output_paths = (
load_and_convert_textract_json(
textract_json_file_path, log_files_output_paths, page_sizes_df
)
)
original_textract_data = textract_data.copy()
# print("Successfully loaded in Textract analysis results from file")
# If running local OCR option, check if file already exists. If it does, load in existing data
if text_extraction_method == TESSERACT_TEXT_EXTRACT_OPTION:
all_page_line_level_ocr_results_with_words_json_file_path = (
output_folder + file_name + "_ocr_results_with_words_local_ocr.json"
)
(
all_page_line_level_ocr_results_with_words,
is_missing,
log_files_output_paths,
) = load_and_convert_ocr_results_with_words_json(
all_page_line_level_ocr_results_with_words_json_file_path,
log_files_output_paths,
page_sizes_df,
)
original_all_page_line_level_ocr_results_with_words = (
all_page_line_level_ocr_results_with_words.copy()
)
# print("Loaded in local OCR analysis results from file")
###
if current_loop_page == 0:
page_loop_start = 0
else:
page_loop_start = current_loop_page
progress_bar = tqdm(
range(page_loop_start, number_of_pages),
unit="pages remaining",
desc="Redacting pages",
)
# If there's data from a previous run (passed in via the DataFrame parameters), add it
all_line_level_ocr_results_list = list()
all_pages_decision_process_list = list()
if not all_page_line_level_ocr_results_df.empty:
all_line_level_ocr_results_list.extend(
all_page_line_level_ocr_results_df.to_dict("records")
)
if not all_pages_decision_process_table.empty:
all_pages_decision_process_list.extend(
all_pages_decision_process_table.to_dict("records")
)
# Go through each page
for page_no in progress_bar:
handwriting_or_signature_boxes = list()
page_signature_recogniser_results = list()
page_handwriting_recogniser_results = list()
page_line_level_ocr_results_with_words = list()
page_break_return = False
reported_page_number = str(page_no + 1)
# Try to find image location
try:
image_path = page_sizes_df.loc[
page_sizes_df["page"] == (page_no + 1), "image_path"
].iloc[0]
except Exception as e:
print("Could not find image_path in page_sizes_df due to:", e)
image_path = pdf_image_file_paths[page_no]
page_image_annotations = {"image": image_path, "boxes": []}
pymupdf_page = pymupdf_doc.load_page(page_no)
if page_no >= page_min and page_no < page_max:
# Need image size to convert OCR outputs to the correct sizes
if isinstance(image_path, str):
if os.path.exists(image_path):
image = Image.open(image_path)
page_width, page_height = image.size
else:
# print("Image path does not exist, using mediabox coordinates as page sizes")
image = None
page_width = pymupdf_page.mediabox.width
page_height = pymupdf_page.mediabox.height
elif not isinstance(image_path, Image.Image):
print(
f"Unexpected image_path type: {type(image_path)}, using page mediabox coordinates as page sizes"
) # Ensure image_path is valid
image = None
page_width = pymupdf_page.mediabox.width
page_height = pymupdf_page.mediabox.height
try:
if not page_sizes_df.empty:
original_cropbox = page_sizes_df.loc[
page_sizes_df["page"] == (page_no + 1), "original_cropbox"
].iloc[0]
except IndexError:
print(
"Can't find original cropbox details for page, using current PyMuPDF page cropbox"
)
original_cropbox = pymupdf_page.cropbox.irect
# Step 1: Perform OCR. Either with Tesseract, or with AWS Textract
# If using Tesseract
if text_extraction_method == TESSERACT_TEXT_EXTRACT_OPTION:
if all_page_line_level_ocr_results_with_words:
# Find the first dict where 'page' matches
matching_page = next(
(
item
for item in all_page_line_level_ocr_results_with_words
if int(item.get("page", -1)) == int(reported_page_number)
),
None,
)
page_line_level_ocr_results_with_words = (
matching_page if matching_page else []
)
else:
page_line_level_ocr_results_with_words = list()
if page_line_level_ocr_results_with_words:
print(
"Found OCR results for page in existing OCR with words object"
)
page_line_level_ocr_results = (
recreate_page_line_level_ocr_results_with_page(
page_line_level_ocr_results_with_words
)
)
else:
page_word_level_ocr_results = image_analyser.perform_ocr(image_path)
(
page_line_level_ocr_results,
page_line_level_ocr_results_with_words,
) = combine_ocr_results(
page_word_level_ocr_results, page=reported_page_number
)
if all_page_line_level_ocr_results_with_words is None:
all_page_line_level_ocr_results_with_words = list()
all_page_line_level_ocr_results_with_words.append(
page_line_level_ocr_results_with_words
)
# Check if page exists in existing textract data. If not, send to service to analyse
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
text_blocks = list()
if not textract_data:
try:
# Convert the image_path to bytes using an in-memory buffer
image_buffer = io.BytesIO()
image.save(
image_buffer, format="PNG"
) # Save as PNG, or adjust format if needed
pdf_page_as_bytes = image_buffer.getvalue()
text_blocks, new_textract_request_metadata = (
analyse_page_with_textract(
pdf_page_as_bytes,
reported_page_number,
textract_client,
handwrite_signature_checkbox,
)
) # Analyse page with Textract
if textract_json_file_path not in log_files_output_paths:
log_files_output_paths.append(textract_json_file_path)
textract_data = {"pages": [text_blocks]}
except Exception as e:
print(
"Textract extraction for page",
reported_page_number,
"failed due to:",
e,
)
textract_data = {"pages": []}
new_textract_request_metadata = "Failed Textract API call"
textract_request_metadata.append(new_textract_request_metadata)
else:
# Check if the current reported_page_number exists in the loaded JSON
page_exists = any(
page["page_no"] == reported_page_number
for page in textract_data.get("pages", [])
)
if not page_exists: # If the page does not exist, analyze again
print(
f"Page number {reported_page_number} not found in existing Textract data. Analysing."
)
try:
# Convert the image_path to bytes using an in-memory buffer
image_buffer = io.BytesIO()
image.save(
image_buffer, format="PNG"
) # Save as PNG, or adjust format if needed
pdf_page_as_bytes = image_buffer.getvalue()
text_blocks, new_textract_request_metadata = (
analyse_page_with_textract(
pdf_page_as_bytes,
reported_page_number,
textract_client,
handwrite_signature_checkbox,
)
) # Analyse page with Textract
# Check if "pages" key exists, if not, initialise it as an empty list
if "pages" not in textract_data:
textract_data["pages"] = list()
# Append the new page data
textract_data["pages"].append(text_blocks)
except Exception as e:
out_message = (
"Textract extraction for page "
+ reported_page_number
+ " failed due to:"
+ str(e)
)
print(out_message)
text_blocks = list()
new_textract_request_metadata = "Failed Textract API call"
# Check if "pages" key exists, if not, initialise it as an empty list
if "pages" not in textract_data:
textract_data["pages"] = list()
raise Exception(out_message)
textract_request_metadata.append(new_textract_request_metadata)
else:
# If the page exists, retrieve the data
text_blocks = next(
page["data"]
for page in textract_data["pages"]
if page["page_no"] == reported_page_number
)
(
page_line_level_ocr_results,
handwriting_or_signature_boxes,
page_signature_recogniser_results,
page_handwriting_recogniser_results,
page_line_level_ocr_results_with_words,
) = json_to_ocrresult(
text_blocks, page_width, page_height, reported_page_number
)
if all_page_line_level_ocr_results_with_words is None:
all_page_line_level_ocr_results_with_words = list()
all_page_line_level_ocr_results_with_words.append(
page_line_level_ocr_results_with_words
)
# Convert to DataFrame and add to ongoing logging table
line_level_ocr_results_df = pd.DataFrame(
[
{
"page": page_line_level_ocr_results["page"],
"text": result.text,
"left": result.left,
"top": result.top,
"width": result.width,
"height": result.height,
"line": result.line,
}
for result in page_line_level_ocr_results["results"]
]
)
if not line_level_ocr_results_df.empty: # Ensure there are records to add
all_line_level_ocr_results_list.extend(
line_level_ocr_results_df.to_dict("records")
)
if pii_identification_method != NO_REDACTION_PII_OPTION:
# Step 2: Analyse text and identify PII
if chosen_redact_entities or chosen_redact_comprehend_entities:
page_redaction_bounding_boxes, comprehend_query_number_new = (
image_analyser.analyze_text(
page_line_level_ocr_results["results"],
page_line_level_ocr_results_with_words["results"],
chosen_redact_comprehend_entities=chosen_redact_comprehend_entities,
pii_identification_method=pii_identification_method,
comprehend_client=comprehend_client,
custom_entities=chosen_redact_entities,
language=language,
allow_list=allow_list,
score_threshold=score_threshold,
nlp_analyser=nlp_analyser,
)
)
comprehend_query_number = (
comprehend_query_number + comprehend_query_number_new
)
else:
page_redaction_bounding_boxes = list()
# Merge redaction bounding boxes that are close together
page_merged_redaction_bboxes = merge_img_bboxes(
page_redaction_bounding_boxes,
page_line_level_ocr_results_with_words["results"],
page_signature_recogniser_results,
page_handwriting_recogniser_results,
handwrite_signature_checkbox,
)
else:
page_merged_redaction_bboxes = list()
# 3. Draw the merged boxes
## Apply annotations to pdf with pymupdf
if is_pdf(file_path) is True:
if redact_whole_page_list:
int_reported_page_number = int(reported_page_number)
if int_reported_page_number in redact_whole_page_list:
redact_whole_page = True
else:
redact_whole_page = False
else:
redact_whole_page = False
pymupdf_page, page_image_annotations = redact_page_with_pymupdf(
pymupdf_page,
page_merged_redaction_bboxes,
image_path,
redact_whole_page=redact_whole_page,
original_cropbox=original_cropbox,
page_sizes_df=page_sizes_df,
)
# If an image_path file, draw onto the image_path
elif is_pdf(file_path) is False:
if isinstance(image_path, str):
if os.path.exists(image_path):
image = Image.open(image_path)
elif isinstance(image_path, Image.Image):
image = image_path
else:
# Assume image_path is an image
image = image_path
fill = (0, 0, 0) # Fill colour for redactions
draw = ImageDraw.Draw(image)
all_image_annotations_boxes = list()
for box in page_merged_redaction_bboxes:
try:
x0 = box.left
y0 = box.top
x1 = x0 + box.width
y1 = y0 + box.height
label = box.entity_type # Attempt to get the label
text = box.text
except AttributeError as e:
print(f"Error accessing box attributes: {e}")
label = "Redaction" # Default label if there's an error
# Check if coordinates are valid numbers
if any(v is None for v in [x0, y0, x1, y1]):
print(f"Invalid coordinates for box: {box}")
continue # Skip this box if coordinates are invalid
img_annotation_box = {
"xmin": x0,
"ymin": y0,
"xmax": x1,
"ymax": y1,
"label": label,
"color": (0, 0, 0),
"text": text,
}
img_annotation_box = fill_missing_box_ids(img_annotation_box)
# Directly append the dictionary with the required keys
all_image_annotations_boxes.append(img_annotation_box)
# Draw the rectangle
try:
draw.rectangle([x0, y0, x1, y1], fill=fill)
except Exception as e:
print(f"Error drawing rectangle: {e}")
page_image_annotations = {
"image": file_path,
"boxes": all_image_annotations_boxes,
}
redacted_image = image.copy()
# Convert decision process to table
decision_process_table = pd.DataFrame(
[
{
"text": result.text,
"xmin": result.left,
"ymin": result.top,
"xmax": result.left + result.width,
"ymax": result.top + result.height,
"label": result.entity_type,
"start": result.start,
"end": result.end,
"score": result.score,
"page": reported_page_number,
}
for result in page_merged_redaction_bboxes
]
)
# all_pages_decision_process_list.append(decision_process_table.to_dict('records'))
if not decision_process_table.empty: # Ensure there are records to add
all_pages_decision_process_list.extend(
decision_process_table.to_dict("records")
)
decision_process_table = fill_missing_ids(decision_process_table)
toc = time.perf_counter()
time_taken = toc - tic
# Break if time taken is greater than max_time seconds
if time_taken > max_time:
print("Processing for", max_time, "seconds, breaking loop.")
page_break_return = True
progress.close(_tqdm=progress_bar)
tqdm._instances.clear()
if is_pdf(file_path) is False:
pdf_image_file_paths.append(redacted_image) # .append(image_path)
pymupdf_doc = pdf_image_file_paths
# Check if the image_path already exists in annotations_all_pages
existing_index = next(
(
index
for index, ann in enumerate(annotations_all_pages)
if ann["image"] == page_image_annotations["image"]
),
None,
)
if existing_index is not None:
# Replace the existing annotation
annotations_all_pages[existing_index] = page_image_annotations
else:
# Append new annotation if it doesn't exist
annotations_all_pages.append(page_image_annotations)
# Save word level options
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
if original_textract_data != textract_data:
# Write the updated existing textract data back to the JSON file
secure_file_write(
output_folder,
file_name + "_textract.json",
json.dumps(textract_data, separators=(",", ":")),
)
if textract_json_file_path not in log_files_output_paths:
log_files_output_paths.append(textract_json_file_path)
all_pages_decision_process_table = pd.DataFrame(
all_pages_decision_process_list
)
all_line_level_ocr_results_df = pd.DataFrame(
all_line_level_ocr_results_list
)
current_loop_page += 1
return (
pymupdf_doc,
all_pages_decision_process_table,
log_files_output_paths,
textract_request_metadata,
annotations_all_pages,
current_loop_page,
page_break_return,
all_line_level_ocr_results_df,
comprehend_query_number,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
)
# If it's an image file
if is_pdf(file_path) is False:
pdf_image_file_paths.append(redacted_image) # .append(image_path)
pymupdf_doc = pdf_image_file_paths
# Check if the image_path already exists in annotations_all_pages
existing_index = next(
(
index
for index, ann in enumerate(annotations_all_pages)
if ann["image"] == page_image_annotations["image"]
),
None,
)
if existing_index is not None:
# Replace the existing annotation
annotations_all_pages[existing_index] = page_image_annotations
else:
# Append new annotation if it doesn't exist
annotations_all_pages.append(page_image_annotations)
current_loop_page += 1
# Break if new page is a multiple of chosen page_break_val
if current_loop_page % page_break_val == 0:
page_break_return = True
progress.close(_tqdm=progress_bar)
tqdm._instances.clear()
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
# Write the updated existing textract data back to the JSON file
if original_textract_data != textract_data:
secure_file_write(
output_folder,
file_name + "_textract.json",
json.dumps(textract_data, separators=(",", ":")),
)
if textract_json_file_path not in log_files_output_paths:
log_files_output_paths.append(textract_json_file_path)
if text_extraction_method == TESSERACT_TEXT_EXTRACT_OPTION:
if (
original_all_page_line_level_ocr_results_with_words
!= all_page_line_level_ocr_results_with_words
):
# Write the updated existing textract data back to the JSON file
with open(
all_page_line_level_ocr_results_with_words_json_file_path, "w"
) as json_file:
json.dump(
all_page_line_level_ocr_results_with_words,
json_file,
separators=(",", ":"),
) # indent=4 makes the JSON file pretty-printed
if (
all_page_line_level_ocr_results_with_words_json_file_path
not in log_files_output_paths
):
log_files_output_paths.append(
all_page_line_level_ocr_results_with_words_json_file_path
)
# all_pages_decision_process_table = pd.concat(all_pages_decision_process_list)
# all_line_level_ocr_results_df = pd.concat(all_line_level_ocr_results_list)
all_pages_decision_process_table = pd.DataFrame(
all_pages_decision_process_list
)
all_line_level_ocr_results_df = pd.DataFrame(
all_line_level_ocr_results_list
)
return (
pymupdf_doc,
all_pages_decision_process_table,
log_files_output_paths,
textract_request_metadata,
annotations_all_pages,
current_loop_page,
page_break_return,
all_line_level_ocr_results_df,
comprehend_query_number,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
)
if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION:
# Write the updated existing textract data back to the JSON file
if original_textract_data != textract_data:
secure_file_write(
output_folder,
file_name + "_textract.json",
json.dumps(textract_data, separators=(",", ":")),
)
if textract_json_file_path not in log_files_output_paths:
log_files_output_paths.append(textract_json_file_path)
if text_extraction_method == TESSERACT_TEXT_EXTRACT_OPTION:
if (
original_all_page_line_level_ocr_results_with_words
!= all_page_line_level_ocr_results_with_words
):
# Write the updated existing textract data back to the JSON file
with open(
all_page_line_level_ocr_results_with_words_json_file_path, "w"
) as json_file:
json.dump(
all_page_line_level_ocr_results_with_words,
json_file,
separators=(",", ":"),
) # indent=4 makes the JSON file pretty-printed
if (
all_page_line_level_ocr_results_with_words_json_file_path
not in log_files_output_paths
):
log_files_output_paths.append(
all_page_line_level_ocr_results_with_words_json_file_path
)
all_pages_decision_process_table = pd.DataFrame(
all_pages_decision_process_list
) # pd.concat(all_pages_decision_process_list)
all_line_level_ocr_results_df = pd.DataFrame(
all_line_level_ocr_results_list
) # pd.concat(all_line_level_ocr_results_list)
# Convert decision table and ocr results to relative coordinates
all_pages_decision_process_table = divide_coordinates_by_page_sizes(
all_pages_decision_process_table,
page_sizes_df,
xmin="xmin",
xmax="xmax",
ymin="ymin",
ymax="ymax",
)
all_line_level_ocr_results_df = divide_coordinates_by_page_sizes(
all_line_level_ocr_results_df,
page_sizes_df,
xmin="left",
xmax="width",
ymin="top",
ymax="height",
)
return (
pymupdf_doc,
all_pages_decision_process_table,
log_files_output_paths,
textract_request_metadata,
annotations_all_pages,
current_loop_page,
page_break_return,
all_line_level_ocr_results_df,
comprehend_query_number,
all_page_line_level_ocr_results,
all_page_line_level_ocr_results_with_words,
)
###
# PIKEPDF TEXT DETECTION/REDACTION
###
def get_text_container_characters(text_container: LTTextContainer):
if isinstance(text_container, LTTextContainer):
characters = [
char
for line in text_container
if isinstance(line, LTTextLine) or isinstance(line, LTTextLineHorizontal)
for char in line
]
return characters
return []
def create_line_level_ocr_results_from_characters(
char_objects: List, line_number: int
) -> Tuple[List[OCRResult], List[List]]:
"""
Create OCRResult objects based on a list of pdfminer LTChar objects.
This version is corrected to use the specified OCRResult class definition.
"""
line_level_results_out = list()
line_level_characters_out = list()
character_objects_out = list()
full_text = ""
# [x0, y0, x1, y1]
overall_bbox = [float("inf"), float("inf"), float("-inf"), float("-inf")]
for char in char_objects:
character_objects_out.append(char)
if isinstance(char, LTAnno):
added_text = char.get_text()
full_text += added_text
if "\n" in added_text:
if full_text.strip():
# Create OCRResult for line
line_level_results_out.append(
OCRResult(
text=full_text.strip(),
left=round(overall_bbox[0], 2),
top=round(overall_bbox[1], 2),
width=round(overall_bbox[2] - overall_bbox[0], 2),
height=round(overall_bbox[3] - overall_bbox[1], 2),
line=line_number,
)
)
line_level_characters_out.append(character_objects_out)
# Reset for the next line
character_objects_out = list()
full_text = ""
overall_bbox = [
float("inf"),
float("inf"),
float("-inf"),
float("-inf"),
]
line_number += 1
continue
# This part handles LTChar objects
added_text = clean_unicode_text(char.get_text())
full_text += added_text
x0, y0, x1, y1 = char.bbox
overall_bbox[0] = min(overall_bbox[0], x0)
overall_bbox[1] = min(overall_bbox[1], y0)
overall_bbox[2] = max(overall_bbox[2], x1)
overall_bbox[3] = max(overall_bbox[3], y1)
# Process the last line
if full_text.strip():
line_number += 1
line_ocr_result = OCRResult(
text=full_text.strip(),
left=round(overall_bbox[0], 2),
top=round(overall_bbox[1], 2),
width=round(overall_bbox[2] - overall_bbox[0], 2),
height=round(overall_bbox[3] - overall_bbox[1], 2),
line=line_number,
)
line_level_results_out.append(line_ocr_result)
line_level_characters_out.append(character_objects_out)
return line_level_results_out, line_level_characters_out
def generate_words_for_line(line_chars: List) -> List[Dict[str, Any]]:
"""
Generates word-level results for a single, pre-defined line of characters.
This robust version correctly identifies word breaks by:
1. Treating specific punctuation characters as standalone words.
2. Explicitly using space characters (' ') as a primary word separator.
3. Using a geometric gap between characters as a secondary, heuristic separator.
Args:
line_chars: A list of pdfminer.six LTChar/LTAnno objects for one line.
Returns:
A list of dictionaries, where each dictionary represents an individual word.
"""
# We only care about characters with coordinates and text for word building.
text_chars = [c for c in line_chars if hasattr(c, "bbox") and c.get_text()]
if not text_chars:
return []
# Sort characters by horizontal position for correct processing.
text_chars.sort(key=lambda c: c.bbox[0])
# NEW: Define punctuation that should be split into separate words.
# The hyphen '-' is intentionally excluded to keep words like 'high-tech' together.
PUNCTUATION_TO_SPLIT = {".", ",", "?", "!", ":", ";", "(", ")", "[", "]", "{", "}"}
line_words = list()
current_word_text = ""
current_word_bbox = [float("inf"), float("inf"), -1, -1] # [x0, y0, x1, y1]
prev_char = None
def finalize_word():
nonlocal current_word_text, current_word_bbox
# Only add the word if it contains non-space text
if current_word_text.strip():
# bbox from [x0, y0, x1, y1] to your required format
final_bbox = [
round(current_word_bbox[0], 2),
round(current_word_bbox[3], 2), # Note: using y1 from pdfminer bbox
round(current_word_bbox[2], 2),
round(current_word_bbox[1], 2), # Note: using y0 from pdfminer bbox
]
line_words.append(
{"text": current_word_text.strip(), "bounding_box": final_bbox}
)
# Reset for the next word
current_word_text = ""
current_word_bbox = [float("inf"), float("inf"), -1, -1]
for char in text_chars:
char_text = clean_unicode_text(char.get_text())
# 1. NEW: Check for splitting punctuation first.
if char_text in PUNCTUATION_TO_SPLIT:
# Finalize any word that came immediately before the punctuation.
finalize_word()
# Treat the punctuation itself as a separate word.
px0, py0, px1, py1 = char.bbox
punc_bbox = [round(px0, 2), round(py1, 2), round(px1, 2), round(py0, 2)]
line_words.append({"text": char_text, "bounding_box": punc_bbox})
prev_char = char
continue # Skip to the next character
# 2. Primary Signal: Is the character a space?
if char_text.isspace():
finalize_word() # End the preceding word
prev_char = char
continue # Skip to the next character, do not add the space to any word
# 3. Secondary Signal: Is there a large geometric gap?
if prev_char:
# A gap is considered a word break if it's larger than a fraction of the font size.
space_threshold = prev_char.size * 0.25 # 25% of the char size
min_gap = 1.0 # Or at least 1.0 unit
gap = (
char.bbox[0] - prev_char.bbox[2]
) # gap = current_char.x0 - prev_char.x1
if gap > max(space_threshold, min_gap):
finalize_word() # Found a gap, so end the previous word.
# Append the character's text and update the bounding box for the current word
current_word_text += char_text
x0, y0, x1, y1 = char.bbox
current_word_bbox[0] = min(current_word_bbox[0], x0)
current_word_bbox[1] = min(current_word_bbox[3], y0) # pdfminer y0 is bottom
current_word_bbox[2] = max(current_word_bbox[2], x1)
current_word_bbox[3] = max(current_word_bbox[1], y1) # pdfminer y1 is top
prev_char = char
# After the loop, finalize the last word that was being built.
finalize_word()
return line_words
def process_page_to_structured_ocr(
all_char_objects: List,
page_number: int,
text_line_number: int, # This will now be treated as the STARTING line number
) -> Tuple[Dict[str, Any], List[OCRResult], List[List]]:
"""
Orchestrates the OCR process, correctly handling multiple lines.
Returns:
A tuple containing:
1. A dictionary with detailed line/word results for the page.
2. A list of the complete OCRResult objects for each line.
3. A list of lists, containing the character objects for each line.
"""
page_data = {"page": str(page_number), "results": {}}
# Step 1: Get definitive lines and their character groups.
# This function correctly returns all lines found in the input characters.
line_results, lines_char_groups = create_line_level_ocr_results_from_characters(
all_char_objects, text_line_number
)
if not line_results:
return {}, [], []
# Step 2: Iterate through each found line and generate its words.
for i, (line_info, char_group) in enumerate(zip(line_results, lines_char_groups)):
current_line_number = line_info.line # text_line_number + i
word_level_results = generate_words_for_line(char_group)
# Create a unique, incrementing line number for each iteration.
line_key = f"text_line_{current_line_number}"
line_bbox = [
line_info.left,
line_info.top,
line_info.left + line_info.width,
line_info.top + line_info.height,
]
# Now, each line is added to the dictionary with its own unique key.
page_data["results"][line_key] = {
"line": current_line_number, # Use the unique line number
"text": line_info.text,
"bounding_box": line_bbox,
"words": word_level_results,
}
# The list of OCRResult objects is already correct.
line_level_ocr_results_list = line_results
# Return the structured dictionary, the list of OCRResult objects, and the character groups
return page_data, line_level_ocr_results_list, lines_char_groups
def create_text_redaction_process_results(
analyser_results, analysed_bounding_boxes, page_num
):
decision_process_table = pd.DataFrame()
if len(analyser_results) > 0:
# Create summary df of annotations to be made
analysed_bounding_boxes_df_new = pd.DataFrame(analysed_bounding_boxes)
# Remove brackets and split the string into four separate columns
# Split the boundingBox list into four separate columns
analysed_bounding_boxes_df_new[["xmin", "ymin", "xmax", "ymax"]] = (
analysed_bounding_boxes_df_new["boundingBox"].apply(pd.Series)
)
# Convert the new columns to integers (if needed)
# analysed_bounding_boxes_df_new.loc[:, ['xmin', 'ymin', 'xmax', 'ymax']] = (analysed_bounding_boxes_df_new[['xmin', 'ymin', 'xmax', 'ymax']].astype(float) / 5).round() * 5
analysed_bounding_boxes_df_text = (
analysed_bounding_boxes_df_new["result"]
.astype(str)
.str.split(",", expand=True)
.replace(".*: ", "", regex=True)
)
analysed_bounding_boxes_df_text.columns = ["label", "start", "end", "score"]
analysed_bounding_boxes_df_new = pd.concat(
[analysed_bounding_boxes_df_new, analysed_bounding_boxes_df_text], axis=1
)
analysed_bounding_boxes_df_new["page"] = page_num + 1
decision_process_table = pd.concat(
[decision_process_table, analysed_bounding_boxes_df_new], axis=0
).drop("result", axis=1)
return decision_process_table
def create_pikepdf_annotations_for_bounding_boxes(analysed_bounding_boxes):
pikepdf_redaction_annotations_on_page = list()
for analysed_bounding_box in analysed_bounding_boxes:
bounding_box = analysed_bounding_box["boundingBox"]
annotation = Dictionary(
Type=Name.Annot,
Subtype=Name.Square, # Name.Highlight,
QuadPoints=[
bounding_box[0],
bounding_box[3],
bounding_box[2],
bounding_box[3],
bounding_box[0],
bounding_box[1],
bounding_box[2],
bounding_box[1],
],
Rect=[bounding_box[0], bounding_box[1], bounding_box[2], bounding_box[3]],
C=[0, 0, 0],
IC=[0, 0, 0],
CA=1, # Transparency
T=analysed_bounding_box["result"].entity_type,
Contents=analysed_bounding_box["text"],
BS=Dictionary(
W=0, S=Name.S # Border width: 1 point # Border style: solid
),
)
pikepdf_redaction_annotations_on_page.append(annotation)
return pikepdf_redaction_annotations_on_page
def redact_text_pdf(
file_path: str, # Path to the PDF file to be redacted
language: str, # Language of the PDF content
chosen_redact_entities: List[str], # List of entities to be redacted
chosen_redact_comprehend_entities: List[str],
allow_list: List[str] = None, # Optional list of allowed entities
page_min: int = 0, # Minimum page number to start redaction
page_max: int = 999, # Maximum page number to end redaction
current_loop_page: int = 0, # Current page being processed in the loop
page_break_return: bool = False, # Flag to indicate if a page break should be returned
annotations_all_pages: List[dict] = list(), # List of annotations across all pages
all_line_level_ocr_results_df: pd.DataFrame = pd.DataFrame(
columns=["page", "text", "left", "top", "width", "height", "line"]
), # DataFrame for OCR results
all_pages_decision_process_table: pd.DataFrame = pd.DataFrame(
columns=[
"image_path",
"page",
"label",
"xmin",
"xmax",
"ymin",
"ymax",
"text",
"id",
]
), # DataFrame for decision process table
pymupdf_doc: List = list(), # List of PyMuPDF documents
all_page_line_level_ocr_results_with_words: List = list(),
pii_identification_method: str = "Local",
comprehend_query_number: int = 0,
comprehend_client="",
in_deny_list: List[str] = list(),
redact_whole_page_list: List[str] = list(),
max_fuzzy_spelling_mistakes_num: int = 1,
match_fuzzy_whole_phrase_bool: bool = True,
page_sizes_df: pd.DataFrame = pd.DataFrame(),
original_cropboxes: List[dict] = list(),
text_extraction_only: bool = False,
output_folder: str = OUTPUT_FOLDER,
page_break_val: int = int(PAGE_BREAK_VALUE), # Value for page break
max_time: int = int(MAX_TIME_VALUE),
nlp_analyser: AnalyzerEngine = nlp_analyser,
progress: Progress = Progress(track_tqdm=True), # Progress tracking object
):
"""
Redact chosen entities from a PDF that is made up of multiple pages that are not images.
Input Variables:
- file_path: Path to the PDF file to be redacted
- language: Language of the PDF content
- chosen_redact_entities: List of entities to be redacted
- chosen_redact_comprehend_entities: List of entities to be redacted for AWS Comprehend
- allow_list: Optional list of allowed entities
- page_min: Minimum page number to start redaction
- page_max: Maximum page number to end redaction
- text_extraction_method: Type of analysis to perform
- current_loop_page: Current page being processed in the loop
- page_break_return: Flag to indicate if a page break should be returned
- annotations_all_pages: List of annotations across all pages
- all_line_level_ocr_results_df: DataFrame for OCR results
- all_pages_decision_process_table: DataFrame for decision process table
- pymupdf_doc: List of PyMuPDF documents
- pii_identification_method (str, optional): The method to redact personal information. Either 'Local' (spacy model), or 'AWS Comprehend' (AWS Comprehend API).
- comprehend_query_number (int, optional): A counter tracking the number of queries to AWS Comprehend.
- comprehend_client (optional): A connection to the AWS Comprehend service via the boto3 package.
- in_deny_list (optional, List[str]): A list of custom words that the user has chosen specifically to redact.
- redact_whole_page_list (optional, List[str]): A list of pages to fully redact.
- max_fuzzy_spelling_mistakes_num (int, optional): The maximum number of spelling mistakes allowed in a searched phrase for fuzzy matching. Can range from 0-9.
- match_fuzzy_whole_phrase_bool (bool, optional): A boolean where 'True' means that the whole phrase is fuzzy matched, and 'False' means that each word is fuzzy matched separately (excluding stop words).
- page_sizes_df (pd.DataFrame, optional): A pandas dataframe of PDF page sizes in PDF or image format.
- original_cropboxes (List[dict], optional): A list of dictionaries containing pymupdf cropbox information.
- text_extraction_only (bool, optional): Should the function only extract text, or also do redaction.
- language (str, optional): The language to do AWS Comprehend calls. Defaults to value of language if not provided.
- output_folder (str, optional): The output folder for the function
- page_break_val: Value for page break
- max_time (int, optional): The maximum amount of time (s) that the function should be running before it breaks. To avoid timeout errors with some APIs.
- nlp_analyser (AnalyzerEngine, optional): The nlp_analyser object to use for entity detection. Defaults to nlp_analyser.
- progress: Progress tracking object
"""
tic = time.perf_counter()
if isinstance(all_line_level_ocr_results_df, pd.DataFrame):
all_line_level_ocr_results_list = [all_line_level_ocr_results_df]
if isinstance(all_pages_decision_process_table, pd.DataFrame):
# Convert decision outputs to list of dataframes:
all_pages_decision_process_list = [all_pages_decision_process_table]
if pii_identification_method == "AWS Comprehend" and comprehend_client == "":
out_message = "Connection to AWS Comprehend service not found."
raise Exception(out_message)
# Try updating the supported languages for the spacy analyser
try:
nlp_analyser = create_nlp_analyser(language, existing_nlp_analyser=nlp_analyser)
# Check list of nlp_analyser recognisers and languages
if language != "en":
gr.Info(
f"Language: {language} only supports the following entity detection: {str(nlp_analyser.registry.get_supported_entities(languages=[language]))}"
)
except Exception as e:
print(f"Error creating nlp_analyser for {language}: {e}")
raise Exception(f"Error creating nlp_analyser for {language}: {e}")
# Update custom word list analyser object with any new words that have been added to the custom deny list
if in_deny_list:
nlp_analyser.registry.remove_recognizer("CUSTOM")
new_custom_recogniser = custom_word_list_recogniser(in_deny_list)
nlp_analyser.registry.add_recognizer(new_custom_recogniser)
nlp_analyser.registry.remove_recognizer("CustomWordFuzzyRecognizer")
new_custom_fuzzy_recogniser = CustomWordFuzzyRecognizer(
supported_entities=["CUSTOM_FUZZY"],
custom_list=in_deny_list,
spelling_mistakes_max=max_fuzzy_spelling_mistakes_num,
search_whole_phrase=match_fuzzy_whole_phrase_bool,
)
nlp_analyser.registry.add_recognizer(new_custom_fuzzy_recogniser)
# Open with Pikepdf to get text lines
pikepdf_pdf = Pdf.open(file_path)
number_of_pages = len(pikepdf_pdf.pages)
# file_name = get_file_name_without_type(file_path)
if not all_page_line_level_ocr_results_with_words:
all_page_line_level_ocr_results_with_words = list()
# Check that page_min and page_max are within expected ranges
if page_max > number_of_pages or page_max == 0:
page_max = number_of_pages
if page_min <= 0:
page_min = 0
else:
page_min = page_min - 1
print("Page range is", str(page_min + 1), "to", str(page_max))
# Run through each page in document to 1. Extract text and then 2. Create redaction boxes
progress_bar = tqdm(
range(current_loop_page, number_of_pages),
unit="pages remaining",
desc="Redacting pages",
)
for page_no in progress_bar:
reported_page_number = str(page_no + 1)
# Create annotations for every page, even if blank.
# Try to find image path location
try:
image_path = page_sizes_df.loc[
page_sizes_df["page"] == int(reported_page_number), "image_path"
].iloc[0]
except Exception as e:
print("Image path not found:", e)
image_path = ""
page_image_annotations = {"image": image_path, "boxes": []} # image
pymupdf_page = pymupdf_doc.load_page(page_no)
pymupdf_page.set_cropbox(pymupdf_page.mediabox) # Set CropBox to MediaBox
if page_min <= page_no < page_max:
# Go page by page
for page_layout in extract_pages(
file_path, page_numbers=[page_no], maxpages=1
):
all_page_line_text_extraction_characters = list()
all_page_line_level_text_extraction_results_list = list()
page_analyser_results = list()
page_redaction_bounding_boxes = list()
characters = list()
pikepdf_redaction_annotations_on_page = list()
page_decision_process_table = pd.DataFrame(
columns=[
"image_path",
"page",
"label",
"xmin",
"xmax",
"ymin",
"ymax",
"text",
"id",
]
)
page_text_ocr_outputs = pd.DataFrame(
columns=["page", "text", "left", "top", "width", "height", "line"]
)
page_text_ocr_outputs_list = list()
text_line_no = 1
for n, text_container in enumerate(page_layout):
characters = list()
if isinstance(text_container, LTTextContainer) or isinstance(
text_container, LTAnno
):
characters = get_text_container_characters(text_container)
# text_line_no += 1
# Create dataframe for all the text on the page
# line_level_text_results_list, line_characters = create_line_level_ocr_results_from_characters(characters)
# line_level_ocr_results_with_words = generate_word_level_ocr(characters, page_number=int(reported_page_number), text_line_number=text_line_no)
(
line_level_ocr_results_with_words,
line_level_text_results_list,
line_characters,
) = process_page_to_structured_ocr(
characters,
page_number=int(reported_page_number),
text_line_number=text_line_no,
)
text_line_no += len(line_level_text_results_list)
### Create page_text_ocr_outputs (OCR format outputs)
if line_level_text_results_list:
# Convert to DataFrame and add to ongoing logging table
line_level_text_results_df = pd.DataFrame(
[
{
"page": page_no + 1,
"text": (result.text).strip(),
"left": result.left,
"top": result.top,
"width": result.width,
"height": result.height,
"line": result.line,
}
for result in line_level_text_results_list
]
)
page_text_ocr_outputs_list.append(line_level_text_results_df)
all_page_line_level_text_extraction_results_list.extend(
line_level_text_results_list
)
all_page_line_text_extraction_characters.extend(line_characters)
all_page_line_level_ocr_results_with_words.append(
line_level_ocr_results_with_words
)
if page_text_ocr_outputs_list:
page_text_ocr_outputs = pd.concat(page_text_ocr_outputs_list)
else:
page_text_ocr_outputs = pd.DataFrame(
columns=[
"page",
"text",
"left",
"top",
"width",
"height",
"line",
]
)
### REDACTION
if pii_identification_method != NO_REDACTION_PII_OPTION:
if chosen_redact_entities or chosen_redact_comprehend_entities:
page_redaction_bounding_boxes = run_page_text_redaction(
language,
chosen_redact_entities,
chosen_redact_comprehend_entities,
all_page_line_level_text_extraction_results_list,
all_page_line_text_extraction_characters,
page_analyser_results,
page_redaction_bounding_boxes,
comprehend_client,
allow_list,
pii_identification_method,
nlp_analyser,
score_threshold,
custom_entities,
comprehend_query_number,
)
# Annotate redactions on page
pikepdf_redaction_annotations_on_page = (
create_pikepdf_annotations_for_bounding_boxes(
page_redaction_bounding_boxes
)
)
else:
pikepdf_redaction_annotations_on_page = list()
# Make pymupdf page redactions
if redact_whole_page_list:
int_reported_page_number = int(reported_page_number)
if int_reported_page_number in redact_whole_page_list:
redact_whole_page = True
else:
redact_whole_page = False
else:
redact_whole_page = False
pymupdf_page, page_image_annotations = redact_page_with_pymupdf(
pymupdf_page,
pikepdf_redaction_annotations_on_page,
image_path,
redact_whole_page=redact_whole_page,
convert_pikepdf_to_pymupdf_coords=True,
original_cropbox=original_cropboxes[page_no],
page_sizes_df=page_sizes_df,
)
# Create decision process table
page_decision_process_table = create_text_redaction_process_results(
page_analyser_results,
page_redaction_bounding_boxes,
current_loop_page,
)
if not page_decision_process_table.empty:
all_pages_decision_process_list.append(
page_decision_process_table
)
# Else, user chose not to run redaction
else:
pass
# print("Not redacting page:", page_no)
# Join extracted text outputs for all lines together
if not page_text_ocr_outputs.empty:
page_text_ocr_outputs = page_text_ocr_outputs.sort_values(
["line"]
).reset_index(drop=True)
page_text_ocr_outputs = page_text_ocr_outputs.loc[
:, ["page", "text", "left", "top", "width", "height", "line"]
]
all_line_level_ocr_results_list.append(page_text_ocr_outputs)
toc = time.perf_counter()
time_taken = toc - tic
# Break if time taken is greater than max_time seconds
if time_taken > max_time:
print("Processing for", max_time, "seconds, breaking.")
page_break_return = True
progress.close(_tqdm=progress_bar)
tqdm._instances.clear()
# Check if the image already exists in annotations_all_pages
existing_index = next(
(
index
for index, ann in enumerate(annotations_all_pages)
if ann["image"] == page_image_annotations["image"]
),
None,
)
if existing_index is not None:
# Replace the existing annotation
annotations_all_pages[existing_index] = page_image_annotations
else:
# Append new annotation if it doesn't exist
annotations_all_pages.append(page_image_annotations)
# Write logs
all_pages_decision_process_table = pd.concat(
all_pages_decision_process_list
)
all_line_level_ocr_results_df = pd.concat(
all_line_level_ocr_results_list
)
print(
"all_line_level_ocr_results_df:", all_line_level_ocr_results_df
)
current_loop_page += 1
return (
pymupdf_doc,
all_pages_decision_process_table,
all_line_level_ocr_results_df,
annotations_all_pages,
current_loop_page,
page_break_return,
comprehend_query_number,
all_page_line_level_ocr_results_with_words,
)
# Check if the image already exists in annotations_all_pages
existing_index = next(
(
index
for index, ann in enumerate(annotations_all_pages)
if ann["image"] == page_image_annotations["image"]
),
None,
)
if existing_index is not None:
# Replace the existing annotation
annotations_all_pages[existing_index] = page_image_annotations
else:
# Append new annotation if it doesn't exist
annotations_all_pages.append(page_image_annotations)
current_loop_page += 1
# Break if new page is a multiple of page_break_val
if current_loop_page % page_break_val == 0:
page_break_return = True
progress.close(_tqdm=progress_bar)
# Write logs
all_pages_decision_process_table = pd.concat(
all_pages_decision_process_list
)
return (
pymupdf_doc,
all_pages_decision_process_table,
all_line_level_ocr_results_df,
annotations_all_pages,
current_loop_page,
page_break_return,
comprehend_query_number,
all_page_line_level_ocr_results_with_words,
)
# Write all page outputs
all_pages_decision_process_table = pd.concat(all_pages_decision_process_list)
all_line_level_ocr_results_df = pd.concat(all_line_level_ocr_results_list)
# Convert decision table to relative coordinates
all_pages_decision_process_table = divide_coordinates_by_page_sizes(
all_pages_decision_process_table,
page_sizes_df,
xmin="xmin",
xmax="xmax",
ymin="ymin",
ymax="ymax",
)
# Coordinates need to be reversed for ymin and ymax to match with image annotator objects downstream
all_pages_decision_process_table["ymin"] = reverse_y_coords(
all_pages_decision_process_table, "ymin"
)
all_pages_decision_process_table["ymax"] = reverse_y_coords(
all_pages_decision_process_table, "ymax"
)
# Convert decision table to relative coordinates
all_line_level_ocr_results_df = divide_coordinates_by_page_sizes(
all_line_level_ocr_results_df,
page_sizes_df,
xmin="left",
xmax="width",
ymin="top",
ymax="height",
)
# print("all_line_level_ocr_results_df:", all_line_level_ocr_results_df)
# Coordinates need to be reversed for ymin and ymax to match with image annotator objects downstream
if not all_line_level_ocr_results_df.empty:
all_line_level_ocr_results_df["top"] = reverse_y_coords(
all_line_level_ocr_results_df, "top"
)
# Remove empty dictionary items from ocr results with words
all_page_line_level_ocr_results_with_words = [
d for d in all_page_line_level_ocr_results_with_words if d
]
return (
pymupdf_doc,
all_pages_decision_process_table,
all_line_level_ocr_results_df,
annotations_all_pages,
current_loop_page,
page_break_return,
comprehend_query_number,
all_page_line_level_ocr_results_with_words,
)
|