-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcertificate_factory.py
2039 lines (1896 loc) · 94.7 KB
/
certificate_factory.py
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
from typing import List, Dict, Tuple, Optional
from abc import abstractmethod
from certificate_verifier import CertificateVerifier, LongTengCertificateVerifier, BaoSteelCertificateVerifier
from common import PdfFile, Specification, Thickness, SerialNumbers, SteelPlate, ChemicalElementName, \
DeliveryCondition, Mass, ChemicalElementValue, YieldStrength, TensileStrength, Elongation, \
PositionDirectionImpact, Temperature, ImpactEnergy, PlateNo, BatchNo, Quantity, CertificateFile, DocxFile, \
SerialNumber, CommonUtils, TableSearchType, Certificate, SingletonABCMeta, Direction, SteelMakingType
from dataclasses import dataclass
# from certificate_verification import BaoSteelRuleMaker, RuleMaker
from certificate_verification import RuleMaker, BaoSteelRuleMaker, LongTengRuleMaker
# In order to unify the standards between the different steel plants, we have already moved specification and
# thickness to the SteelPlate object. However, for BAOSHAN we still keep them in the certificate (duplication in effect)
# object because the forms BAOSHAN deliver have them in the certificate level, so at first we read them and put them in
# the certificate object, and then copy them to each SteelPlate object (in a way like broadcasting) the certificate
# contains.
from output_utilities.output_excel import write_multiple_certificates_to_excel
@dataclass
class BaoSteelCertificate(Certificate):
specification: Specification
thickness: Thickness
# Delivery Condition (Condition of Supply in LongTeng form) is duplicated in certificate object, because the value is
# provided in the certificate level, we will read it and put it in the certificate object, and then copy it to each
# SteelPlate object (in a way like broadcasting) the certificate contains.
@dataclass
class LongTengCertificate(Certificate):
delivery_condition: Optional[DeliveryCondition]
# Here the term of factory is not related to the steel plant, it is purely the concept of Factory Method design pattern.
# The pattern improves the code loosely coupled for better maintainability and extensibility.
# This class contains the factory method act as the creator of the certificates, and it must be instantiated by
# subclasses dedicated for each steel plant respectively.
class CertificateFactory(metaclass=SingletonABCMeta):
@abstractmethod
def read(self, file: CertificateFile) -> List[Certificate]:
pass
@abstractmethod
def get_rule_maker(self) -> RuleMaker:
pass
@abstractmethod
def get_verifier(self) -> CertificateVerifier:
pass
class LongTengCertificateFactory(CertificateFactory):
def get_rule_maker(self) -> LongTengRuleMaker:
return LongTengRuleMaker()
def get_verifier(self) -> LongTengCertificateVerifier:
return LongTengCertificateVerifier()
def read(self, file: DocxFile) -> List[LongTengCertificate]:
certificate_list = []
for cert_index, table in enumerate(file.tables):
certificate_no = self.extract_certificate_no(file.file_path, cert_index, table)
delivery_condition = self.extract_delivery_condition(file.file_path, cert_index, table)
serial_numbers = self.extract_serial_numbers(file.file_path, cert_index, table)
chemical_elements = self.extract_chemical_elements(file.file_path, cert_index, table)
steel_plates = self.extract_steel_plates(file.file_path, cert_index, table, serial_numbers,
delivery_condition, chemical_elements)
certificate_list.append(
LongTengCertificate(
file_path=file.file_path,
steel_plant=file.steel_plant,
certificate_no=certificate_no,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
chemical_elements=chemical_elements,
delivery_condition=delivery_condition
)
)
return certificate_list
@staticmethod
def extract_certificate_no(file_path: str, cert_index: int, table: List[List[str]]):
# 遍历这张表格
coordinates = CommonUtils.search_table(table, '质保书编号', TableSearchType.REMOVE_LINE_BREAK_CONTAIN)
if coordinates is None:
raise ValueError(
f"Could not find text '质保书编号' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx "
f"file {file_path}."
)
x_coordinate = coordinates[0]
y_coordinate = coordinates[1]
certificate_no_value = table[x_coordinate][y_coordinate]
if certificate_no_value is None:
raise ValueError(
f"The value of '质保书编号' could not be found in the {CommonUtils.ordinal(cert_index + 1)} table in the "
f"given docx file {file_path}"
)
return certificate_no_value.replace('质保书编号:', '').replace('Certificate No.', '').strip()
@staticmethod
def extract_delivery_condition(file_path: str, cert_index: int, table: List[List[str]]):
coordinates = CommonUtils.search_table(table, "交货状态:热轧\nCondition of Supply: As Rolled",
TableSearchType.EXACT_MATCH)
if coordinates is None:
raise ValueError(
f"Could not find 'Condition of Supply' in the {CommonUtils.ordinal(cert_index + 1)} table in the given "
f"docx file {file_path}"
)
x_coordinate = coordinates[0]
y_coordinate = coordinates[1]
# If no exception here, the delivery condition value (Condition of Supply) is hardcoded in all the certificates
# as "As Rolled", corresponding to the "AR".
delivery_condition = 'AR'
return DeliveryCondition(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
index=None,
message=None,
valid_flag=True,
value=delivery_condition
)
@staticmethod
def extract_serial_numbers(file_path: str, cert_index: int, table: List[List[str]]):
coordinates = CommonUtils.search_table(table, '冶炼炉号', TableSearchType.REMOVE_LINE_BREAK_CONTAIN,
confirmed_col=0)
if coordinates is None:
raise ValueError(
f"Could not find '冶炼炉号' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
start_row_index = coordinates[0]
coordinates = CommonUtils.search_table(table, '冶炼炉号', TableSearchType.REMOVE_LINE_BREAK_CONTAIN,
confirmed_row=start_row_index + 2, confirmed_col=0)
if coordinates is None:
raise ValueError(
f"The cell of '冶炼炉号' doesn't span three rows, this might be caused by the table layout being "
f"changed by the steel plant provider Long Teng."
)
# print(f"start row index == {start_row_index}")
coordinates = CommonUtils.search_table(table, '验船师签字:', TableSearchType.SPLIT_LINE_BREAK_START)
if coordinates is None:
raise ValueError(
f"Could not find '验船师签字:' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
end_row_index = coordinates[0]
# print(f"end row index == {end_row_index}")
serial_number_list = []
row_cursor = start_row_index + 2 # This is the last row contains '冶炼炉号', this cell spans three row.
current_index = 0
while (row_cursor := row_cursor + 1) < end_row_index:
# print(f"current cursor = {row_cursor}")
if len(table[row_cursor][0].strip()) > 0:
serial_number_list.append(SerialNumber(
table_index=cert_index,
x_coordinate=row_cursor,
y_coordinate=0,
value=(current_index := current_index + 1)
))
# print(f"cell content is {table[row_cursor][0]}")
# print(f"got serial number {current_index}")
return SerialNumbers(
table_index=cert_index,
x_coordinate=start_row_index + 1,
y_coordinate=0,
value=serial_number_list
)
@staticmethod
def extract_chemical_elements(file_path: str, cert_index: int, table: List[List[str]]):
# To locate the chemical element area
# the row index of the line is the next to the line contains "Chemical Composition"
# and the column index span from the first catch "Chemical Composition" until "Mechanical Properties"
coordinates = CommonUtils.search_table(table, 'Chemical Composition', TableSearchType.SPLIT_LINE_BREAK_END)
if coordinates is None:
raise ValueError(
f"Could not find 'Chemical Composition' in the {CommonUtils.ordinal(cert_index + 1)} table in the "
f"given docx file {file_path}"
)
chemical_elements_row_index = coordinates[0] + 1
chemical_elements_column_start_index = coordinates[1]
coordinates = CommonUtils.search_table(table, 'Mechanical Properties', TableSearchType.SPLIT_LINE_BREAK_END)
if coordinates is None:
raise ValueError(
f"Could not find 'Mechanical Properties' in the {CommonUtils.ordinal(cert_index + 1)} table in the "
f"given docx file {file_path}"
)
chemical_elements_column_end_index = coordinates[1]
column_cursor = chemical_elements_column_start_index - 1
chemical_elements = dict()
while (column_cursor := column_cursor + 1) < chemical_elements_column_end_index:
cell = table[chemical_elements_row_index][column_cursor].strip()
if cell in CommonUtils.chemical_elements_table:
if cell not in chemical_elements:
chemical_elements[cell] = ChemicalElementName(
table_index=cert_index,
x_coordinate=chemical_elements_row_index,
y_coordinate=column_cursor,
value=cell,
row_index=chemical_elements_row_index,
precision=0 # No precision setting in LongTeng certificate
)
return chemical_elements
@staticmethod
def extract_steel_plates(file_path: str, cert_index: int, table: List[List[str]], serial_numbers: SerialNumbers,
delivery_condition: DeliveryCondition, chemical_elements: Dict[str, ChemicalElementName]):
steel_plate_list = []
for serial_number in serial_numbers:
plate = SteelPlate(serial_number)
plate.delivery_condition = delivery_condition
steel_plate_list.append(plate)
LongTengCertificateFactory.extract_batch_no(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_plate_no(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_specification(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_thickness(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_quantity(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_mass(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_chemical_compositions(file_path, cert_index, table, steel_plate_list,
chemical_elements)
LongTengCertificateFactory.extract_yield_strength(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_tensile_strength(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_elongation(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_position_direction_impact(cert_index, steel_plate_list)
LongTengCertificateFactory.extract_temperature(file_path, cert_index, table, steel_plate_list)
LongTengCertificateFactory.extract_impact_energy_list(file_path, cert_index, table, steel_plate_list)
return steel_plate_list
# Steel Making Type value is embedded in the batch-no value:
# D1 D2 代表电炉冶炼 EAF (Electric arc furnace) EAF B1 B2代表转炉冶炼 BOC (Basic oxygen converter)
@staticmethod
def extract_batch_no(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the Batch No. cell
coordinates = CommonUtils.search_table(table, 'Batch No.', TableSearchType.SPLIT_LINE_BREAK_END)
if coordinates is None:
raise ValueError(
f"Could not find 'Batch No.' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
batch_no_value = table[x_coordinate][y_coordinate].strip()
if len(batch_no_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for 'Batch No.' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.batch_no = BatchNo(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=batch_no_value,
index=plate_index
)
# set the steel making type value here. (this is a bit special since the value is embedded in batch-no)
if batch_no_value.startswith('D1') or batch_no_value.startswith('D2'):
plate.steel_making_type = SteelMakingType(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value='EAF, CC',
index=plate_index
)
elif batch_no_value.startswith('B1') or batch_no_value.startswith('B2'):
plate.steel_making_type = SteelMakingType(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value='BOC, CC',
index=plate_index
)
else:
raise ValueError(
f"The batch no. value {batch_no_value} is invalid "
f"in the {CommonUtils.ordinal(plate.serial_number.value)} plate in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}, "
f"the expected value should start with 'D1', 'D2', 'B1' and 'B2'."
)
@staticmethod
def extract_plate_no(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the Roll No. cell
coordinates = CommonUtils.search_table(table, 'Roll No.', TableSearchType.SPLIT_LINE_BREAK_END)
if coordinates is None:
raise ValueError(
f"Could not find 'Roll No.' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
roll_no_value = table[x_coordinate][y_coordinate].strip()
if len(roll_no_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for 'Roll No.' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.plate_no = PlateNo(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=roll_no_value,
index=plate_index
)
@staticmethod
def extract_specification(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the Grade cell
coordinates = CommonUtils.search_table(table, 'Grade', TableSearchType.SPLIT_LINE_BREAK_END)
if coordinates is None:
raise ValueError(
f"Could not find 'Grade' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
grade_value = table[x_coordinate][y_coordinate].strip()
if len(grade_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for 'Grade' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.specification = Specification(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=grade_value,
index=plate_index,
message=None,
valid_flag=True
)
@staticmethod
def extract_thickness(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the Dimensions cell
coordinates = CommonUtils.search_table(table, 'Dimensions', TableSearchType.SPLIT_LINE_BREAK_END)
if coordinates is None:
raise ValueError(
f"Could not find 'Dimensions' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file"
f" {file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
dimensions_value = table[x_coordinate][y_coordinate].strip()
if len(dimensions_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for 'Dimensions' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
thickness_value = dimensions_value.split('×')[-1].strip()
if thickness_value.isdigit():
thickness_value = float(thickness_value)
else:
raise ValueError(
f"The last dimension value {thickness_value} in the Dimensions value {dimensions_value} isn't a "
f"digit in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.thickness = Thickness(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=thickness_value,
index=plate_index,
message=None,
valid_flag=True
)
@staticmethod
def extract_quantity(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the PCS cell
coordinates = CommonUtils.search_table(table, 'PCS', TableSearchType.SPLIT_LINE_BREAK_END)
if coordinates is None:
raise ValueError(
f"Could not find 'PCS' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
pcs_value = table[x_coordinate][y_coordinate].strip()
if len(pcs_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for 'PCS' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
if pcs_value.isdigit():
pcs_value = int(pcs_value)
else:
raise ValueError(
f"The PCS value {pcs_value} isn't a "
f"digit in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.quantity = Quantity(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=pcs_value,
index=plate_index
)
@staticmethod
def extract_mass(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the Weight cell
coordinates = CommonUtils.search_table(table, '重量Weight(t)', TableSearchType.REMOVE_LINE_BREAK_CONTAIN)
if coordinates is None:
raise ValueError(
f"Could not find 'Weight' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
weight_value = table[x_coordinate][y_coordinate].strip()
if len(weight_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for 'Weight' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
try:
weight_value = float(weight_value)
except ValueError:
raise ValueError(
f"The Weight value {weight_value} isn't a "
f"float in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.mass = Mass(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=weight_value,
index=plate_index
)
@staticmethod
def extract_chemical_compositions(file_path: str, cert_index: int, table: List[List[str]],
steel_plates: List[SteelPlate],
chemical_elements: Dict[str, ChemicalElementName]):
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
chemical_compositions = dict()
for element in chemical_elements:
y_coordinate = chemical_elements[element].y_coordinate
element_value = table[x_coordinate][y_coordinate].strip()
if len(element_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the "
f"{CommonUtils.ordinal(plate.serial_number.value)} plate has no value for chemical element "
f"{element} in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
try:
element_value = float(element_value.replace('≤', ''))
except ValueError:
raise ValueError(
f"The value of chemical element {element} {element_value} isn't a "
f"float in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
chemical_compositions[element] = ChemicalElementValue(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=element_value,
index=plate_index,
valid_flag=True,
message=None,
element=element,
precision=chemical_elements[element].precision
)
###################################################
# Temporary solution hardcode Mo and Ti
chemical_compositions['Mo'] = ChemicalElementValue(
table_index=cert_index,
x_coordinate=None,
y_coordinate=None,
value=0.02,
index=plate_index,
valid_flag=True,
message=None,
element='Mo',
precision=0
)
chemical_compositions['Ti'] = ChemicalElementValue(
table_index=cert_index,
x_coordinate=None,
y_coordinate=None,
value=0.02,
index=plate_index,
valid_flag=True,
message=None,
element='Ti',
precision=0
)
###########################################################
plate.chemical_compositions = chemical_compositions
# print(
# f"{{'C': {chemical_compositions['C'].calculated_value}, "
# f"'Si': {chemical_compositions['Si'].calculated_value}, "
# f"'Mn': {chemical_compositions['Mn'].calculated_value}, "
# f"'P': {chemical_compositions['P'].calculated_value}, "
# f"'S': {chemical_compositions['S'].calculated_value}, "
# f"'Ni': {chemical_compositions['Ni'].calculated_value}, "
# f"'Cr': {chemical_compositions['Cr'].calculated_value}, "
# f"'Cu': {chemical_compositions['Cu'].calculated_value}, "
# f"'V': {chemical_compositions['V'].calculated_value}, "
# f"'Al': {chemical_compositions['Al'].calculated_value}, "
# f"'Nb': {chemical_compositions['Nb'].calculated_value}, "
# f"'Ceq': {chemical_compositions['Ceq'].calculated_value}}},"
# )
@staticmethod
def extract_yield_strength(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the 屈服强度 cell
coordinates = CommonUtils.search_table(table, '屈服强度', TableSearchType.SPLIT_LINE_BREAK_START)
if coordinates is None:
raise ValueError(
f"Could not find '屈服强度' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx "
f"file {file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
yield_strength_value = table[x_coordinate][y_coordinate].strip()
if len(yield_strength_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for '屈服强度' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
try:
yield_strength_value = int(yield_strength_value)
except ValueError:
raise ValueError(
f"The 屈服强度 value {yield_strength_value} isn't an "
f"integer in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.yield_strength = YieldStrength(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=yield_strength_value,
index=plate_index,
valid_flag=True,
message=None
)
@staticmethod
def extract_tensile_strength(file_path: str, cert_index: int, table: List[List[str]],
steel_plates: List[SteelPlate]):
# To get the column index of the 抗拉强度 cell
coordinates = CommonUtils.search_table(table, '抗拉强度', TableSearchType.SPLIT_LINE_BREAK_START)
if coordinates is None:
raise ValueError(
f"Could not find '抗拉强度' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx "
f"file {file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
tensile_strength_value = table[x_coordinate][y_coordinate].strip()
if len(tensile_strength_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for '抗拉强度' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
try:
tensile_strength_value = int(tensile_strength_value)
except ValueError:
raise ValueError(
f"The 抗拉强度 value {tensile_strength_value} isn't an "
f"integer in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.tensile_strength = TensileStrength(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=tensile_strength_value,
index=plate_index,
valid_flag=True,
message=None
)
@staticmethod
def extract_elongation(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# To get the column index of the 抗拉强度 cell
coordinates = CommonUtils.search_table(table, '伸长率', TableSearchType.SPLIT_LINE_BREAK_START)
if coordinates is None:
raise ValueError(
f"Could not find '伸长率' in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx "
f"file {file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
elongation_value = table[x_coordinate][y_coordinate].strip()
if len(elongation_value) == 0:
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for '伸长率' in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
try:
elongation_value = int(elongation_value)
except ValueError:
raise ValueError(
f"The 伸长率 value {elongation_value} isn't an "
f"integer in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
plate.elongation = Elongation(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=elongation_value,
index=plate_index,
valid_flag=True,
message=None
)
@staticmethod
def extract_position_direction_impact(cert_index: int, steel_plates: List[SteelPlate]):
# Longteng's steel plates are all longitudinal by default
for plate_index, plate in enumerate(steel_plates):
plate.position_direction_impact = PositionDirectionImpact(
table_index=cert_index,
x_coordinate=None,
y_coordinate=None,
value=Direction.LONGITUDINAL,
index=plate_index
)
@staticmethod
def extract_temperature(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate]):
# Temperature is hardcoded as 0 degree in the impact title in longteng certificate
coordinates = CommonUtils.search_table(table, 'V型冲击功 (J, 0℃)\nCharpy V-notch Impact',
TableSearchType.EXACT_MATCH)
if coordinates is None:
raise ValueError(
f"Could not find 'V型冲击功 (J, 0℃)' in the {CommonUtils.ordinal(cert_index + 1)} table in the given "
f"docx file {file_path}"
)
y_coordinate = coordinates[1]
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
temperature_value = 0 # hardcode value as described in the form title.
plate.temperature = Temperature(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=temperature_value,
index=plate_index,
valid_flag=True,
message=None
)
@staticmethod
def extract_impact_energy_list(file_path: str, cert_index: int, table: List[List[str]],
steel_plates: List[SteelPlate]):
# Get the coordinates of the Impact title cell
coordinates = CommonUtils.search_table(table, 'V型冲击功 (J, 0℃)\nCharpy V-notch Impact',
TableSearchType.EXACT_MATCH)
if coordinates is None:
raise ValueError(
f"Could not find 'V型冲击功 (J, 0℃)' in the {CommonUtils.ordinal(cert_index + 1)} table in the given "
f"docx file {file_path}"
)
x_coordinate = coordinates[0] + 1
y_coordinate = coordinates[1]
expected_title_values = ['1', '2', '3', 'Avg']
for title_index, title_value in enumerate(expected_title_values):
LongTengCertificateFactory.extract_impact_energy(file_path, cert_index, table, steel_plates, title_value,
x_coordinate, y_coordinate + title_index)
# print(
# [[impact_energy.value for impact_energy in plate.impact_energy_list] for plate in steel_plates]
# )
@staticmethod
def extract_impact_energy(file_path: str, cert_index: int, table: List[List[str]], steel_plates: List[SteelPlate],
expected_title_value: str, expected_title_x_coordinate: int,
expected_title_y_coordinate: int):
# To confirm the existence of the expected title cell
coordinates = CommonUtils.search_table(table, expected_title_value, TableSearchType.EXACT_MATCH,
confirmed_row=expected_title_x_coordinate,
confirmed_col=expected_title_y_coordinate)
if coordinates is None:
raise ValueError(
f"Could not find sub title '{expected_title_value}' of the impact energy section in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
y_coordinate = expected_title_y_coordinate
for plate_index, plate in enumerate(steel_plates):
x_coordinate = plate.serial_number.x_coordinate
impact_energy_value = table[x_coordinate][y_coordinate].strip()
if len(impact_energy_value) == 0:
########################################################
# under below conditions, impact energy values are not required
if plate.specification.value == 'VL A':
if plate.thickness.value <= 50:
continue
elif plate.delivery_condition.value == 'N':
continue
if plate.specification.value == 'VL B':
if plate.thickness.value <= 25:
continue
#########################################################
raise ValueError(
f"The cell [{x_coordinate}, {y_coordinate}] in the {CommonUtils.ordinal(plate.serial_number.value)}"
f" plate has no value for impact energy {expected_title_value} in the "
f"{CommonUtils.ordinal(cert_index + 1)} table in the given docx file {file_path}"
)
try:
impact_energy_value = int(impact_energy_value)
except ValueError:
raise ValueError(
f"The impact energy value {impact_energy_value} (in the cell [{x_coordinate}, {y_coordinate}] ) "
f"isn't an integer in the {CommonUtils.ordinal(cert_index + 1)} table in the given docx file "
f"{file_path}"
)
plate.impact_energy_list.append(
ImpactEnergy(
table_index=cert_index,
x_coordinate=x_coordinate,
y_coordinate=y_coordinate,
value=impact_energy_value,
index=plate_index,
test_number=expected_title_value,
valid_flag=True,
message=None
)
)
class BaoSteelCertificateFactory(CertificateFactory):
# ################################ Singleton ################################ #
# _singleton = None
#
# @classmethod
# def get_singleton(cls):
# if not isinstance(cls._singleton, cls):
# cls._singleton = cls()
# return cls._singleton
# ################################ Singleton ################################ #
def get_rule_maker(self) -> BaoSteelRuleMaker:
return BaoSteelRuleMaker()
def get_verifier(self) -> BaoSteelCertificateVerifier:
return BaoSteelCertificateVerifier()
def read(self, file: PdfFile) -> List[Certificate]:
certificate_no = BaoSteelCertificateFactory.extract_certificate_no(file)
specification = BaoSteelCertificateFactory.extract_specification(file)
thickness = BaoSteelCertificateFactory.extract_thickness(file)
serial_numbers = BaoSteelCertificateFactory.extract_serial_numbers(file)
chemical_elements, chemical_col_counter = BaoSteelCertificateFactory.extract_chemical_elements(file)
non_test_lot_no_map = BaoSteelCertificateFactory.generate_non_test_lot_no_map(file, serial_numbers)
# "Test Lot No" is something interrupting the extraction of position direction value, we need a mapping to help
# skipping the Test Lot No values.
steel_plates = BaoSteelCertificateFactory.extract_steel_plates(
pdf_file=file,
specification=specification,
thickness=thickness,
serial_numbers=serial_numbers,
chemical_elements=chemical_elements,
chemical_col_counter=chemical_col_counter,
non_test_lot_no_map=non_test_lot_no_map
)
certificate = BaoSteelCertificate(
file_path=file.file_path,
steel_plant=file.steel_plant,
certificate_no=certificate_no,
specification=specification,
thickness=thickness,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
chemical_elements=chemical_elements
)
return [certificate]
@staticmethod
def generate_non_test_lot_no_map(pdf_file: PdfFile, serial_numbers: SerialNumbers) -> Dict[int, int]:
# The number is always in the second table
_, data_table = pdf_file.tables
# The title "Test Lot No" is listed in the "PLATE NO." column, it's neighboring the Serial Numbers cell.
x_coordinate = serial_numbers.x_coordinate
y_coordinate = serial_numbers.y_coordinate + 1
matching_index_gen = (index for index, item in enumerate(data_table[x_coordinate][y_coordinate].split('\n')) if
'Test Lot No:' not in item)
non_test_lot_no_map: Dict[int, int] = dict()
for steel_plate_index in range(len(serial_numbers)):
try:
matching_index = next(matching_index_gen)
non_test_lot_no_map[steel_plate_index] = matching_index
except StopIteration as e:
print(f"Cannot match index {steel_plate_index} in 'NO.' with the index in 'PLATE NO.'.")
raise e
return non_test_lot_no_map
@staticmethod
def extract_steel_plates(
pdf_file: PdfFile,
specification: Specification,
thickness: Thickness,
serial_numbers: SerialNumbers,
chemical_elements: Dict[str, ChemicalElementName],
chemical_col_counter: Dict[int, int],
non_test_lot_no_map: Dict[int, int]
) -> List[SteelPlate]:
steel_plates = []
for serial_number in serial_numbers:
plate = SteelPlate(serial_number)
plate.specification = specification
plate.thickness = thickness
steel_plates.append(plate)
BaoSteelCertificateFactory.extract_quantity(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates
)
BaoSteelCertificateFactory.extract_mass(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates
)
BaoSteelCertificateFactory.extract_chemical_composition(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
chemical_elements=chemical_elements,
chemical_col_counter=chemical_col_counter
)
BaoSteelCertificateFactory.extract_delivery_condition(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates
)
BaoSteelCertificateFactory.extract_batch_no(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map
)
BaoSteelCertificateFactory.extract_plate_no(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map
)
BaoSteelCertificateFactory.extract_yield_strength(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map
)
BaoSteelCertificateFactory.extract_tensile_strength(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map
)
BaoSteelCertificateFactory.extract_elongation(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map
)
impact_test_count, impact_test_map = BaoSteelCertificateFactory.impact_test_check(
specification=specification,
thickness=thickness,
serial_numbers=serial_numbers,
steel_plates=steel_plates
)
if impact_test_count > 0:
BaoSteelCertificateFactory.extract_position_direction_impact(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map,
# impact_test_count=impact_test_count,
impact_test_map=impact_test_map
)
BaoSteelCertificateFactory.extract_temperature(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map,
# impact_test_count=impact_test_count,
impact_test_map=impact_test_map
)
BaoSteelCertificateFactory.extract_impact_energy(
pdf_file=pdf_file,
serial_numbers=serial_numbers,
steel_plates=steel_plates,
non_test_lot_no_map=non_test_lot_no_map,
# impact_test_count=impact_test_count,
impact_test_map=impact_test_map
)
return steel_plates
@staticmethod
def translate_to_vl_direction(position_direction_value: str) -> Direction:
map_to_vl_direction = {
'C': Direction.TRANSVERSE,
'L': Direction.LONGITUDINAL
}
c_flag = 'C' in position_direction_value
l_flag = 'L' in position_direction_value
if c_flag and not l_flag:
return map_to_vl_direction['C']
if l_flag and not c_flag:
return map_to_vl_direction['L']
if c_flag and l_flag:
raise ValueError(
f"The position direction value {position_direction_value} contains both C (Transverse) and "
f"L (Longitudinal), it is invalid."
)
if not c_flag and not l_flag:
raise ValueError(
f"The position direction value {position_direction_value} contains neither C (Transverse) nor "
f"L (Longitudinal), it is invalid."
)
@staticmethod
def extract_position_direction_impact(
pdf_file: PdfFile,
serial_numbers: SerialNumbers,
steel_plates: List[SteelPlate],
non_test_lot_no_map: Dict[int, int],
# impact_test_count: int,
impact_test_map: Dict[int, bool]
):
# tensile strength data is always in the second table
table_index = 1
table = pdf_file.tables[table_index]
# Search the title IMPACTTEST to locate the y coordinate
coordinates = CommonUtils.search_table(table, 'IMPACTTEST',
search_type=TableSearchType.REMOVE_LINE_BREAK_CONTAIN)
if coordinates is None:
raise ValueError(
f"Could not find IMPACT TEST title in the given PDF {pdf_file.file_path}."
)
y_coordinate = coordinates[1]
# x coordinate is the same of the serial numbers
x_coordinate = serial_numbers.x_coordinate
cell = table[x_coordinate][y_coordinate]
cell_line_count = len(cell.split('\n'))
if cell_line_count >= len(serial_numbers):
pass
else:
raise ValueError(
f"There are {cell_line_count} lines in the position direction (impact test) cell, less than "
f"the serial numbers count {len(serial_numbers)} plates in the given PDF {pdf_file.file_path}"
)
position_direction_cell_lines = cell.split('\n')
for plate_index in range(len(serial_numbers)):
if not impact_test_map[plate_index]:
position_direction_cell_lines.insert(non_test_lot_no_map[plate_index], 'None')
# Start extracting the elongation value for each plate
for plate_index in range(len(serial_numbers)):
if len(position_direction_cell_lines) > len(serial_numbers):
position_direction_value = position_direction_cell_lines[non_test_lot_no_map[plate_index]]
else:
position_direction_value = position_direction_cell_lines[plate_index]
if position_direction_value is not None and len(position_direction_value.strip()) > 0:
position_direction_value = position_direction_value.strip()
else:
raise ValueError(
f"Could not find the position direction (impact test) value for plate No. "
f"{serial_numbers[plate_index]} in the given PDF {pdf_file.file_path}"
)
if position_direction_value == 'None':
continue
elif position_direction_value.isalnum():
pass
else: