-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.py
More file actions
957 lines (761 loc) · 33.7 KB
/
Copy pathhelpers.py
File metadata and controls
957 lines (761 loc) · 33.7 KB
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
import os
import tempfile
import pytesseract
import json
import csv
import logging
import cv2
import matplotlib.pyplot as plt
from numpy import array
import seaborn as sns
import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import PatternFill
import all_parts as bgi
import os
import shutil
from collections import Counter
import re
import numpy as np
import trimesh
import pyrender
from PIL import Image
# from get_mesh import render_and_crop
# Set path to Tesseract (Update this if necessary)
# Update to make this program work with WSL
if os.name == 'nt':
pytesseract.pytesseract.tesseract_cmd = (
r"C:\Program Files\Tesseract-OCR\tesseract.exe"
)
# Suppress Flask's HTTP request logs
log = logging.getLogger("werkzeug")
log.setLevel(logging.ERROR)
'''STEP 1: extract image from STL'''
def clear_folder(folder_path):
"""Clear all files and subfolders in the specified folder."""
if os.path.exists(folder_path):
# Iterate through all files and subfolders in the folder
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isdir(file_path):
# Recursively remove subdirectories
shutil.rmtree(file_path)
else:
# Remove files
os.remove(file_path)
except Exception as e:
print(f"Error clearing {file_path}: {e}")
print(f"✅ {folder_path} cleared.")
else:
print(f"⚠️ {folder_path} does not exist, skipping clearance.")
def save_stl_files(files):
stl_files_folder = tempfile.mkdtemp() # Create a temporary directory for STL files
for file in files:
# Sanitize the filename by removing slashes and spaces
sanitized_filename = file.filename.replace(" ", "_").replace("/", "_")
file_path = os.path.join(stl_files_folder, sanitized_filename)
file.save(file_path)
return stl_files_folder
def save_stl_folders(folder_path):
stl_files_folder = tempfile.mkdtemp()
for dirpath, _, filenames in os.walk(folder_path):
for file in sorted(filenames):
sanitized = file.filename.replace(" ", "_").replace("/", "_")
src = os.path.join(dirpath, file)
dst = os.path.join(stl_files_folder, sanitized)
shutil.copy2(src, dst)
return stl_files_folder
def get_images(stl_files_folder,output_folder_filled):
# Define the input and output folders
input_stl, load_data, language = bgi.process_files_vtk(stl_files_folder, output_folder_filled)
return input_stl, load_data, language
'''STEP 2: Get text'''
def correct_label(label, batch_number):
"""Auto-corrects a label from OCR to ensure consistent formatting."""
label = label.strip().upper()
if len(label) < 4:
label = label.ljust(4, "0")
elif len(label) > 4:
label = label[:4]
first, second = label[0], label[1]
# Extract the last two characters from batch_number
# batch_number = batch_number.strip().upper()[-2:] # Ensure we get exactly two characters
# Corrections based on expected format
if first == "O":
first = "0"
if first == "S":
first = "5"
if first == "I":
first = "1"
if not first.isdigit() or int(first) > 5:
first = "0"
if not (second.isdigit() or "A" <= second <= "Z"):
second = "0"
return first + second + batch_number # Append batch number as last two characters
def extract_text_from_image(image_path, lang):
try:
# print(f"Processing: {image_path}...")
image = cv2.imread(image_path)
if image is None:
print(f"Warning: Unable to load {image_path}")
return "NOT RECOGNIZED"
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# Extract text using Tesseract OCR
extracted_text = pytesseract.image_to_string(
thresh, lang=lang, config="--psm 6 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
) or ""
extracted_text = extracted_text.strip().upper()
if not extracted_text:
# print(f"⚠️ Warning: No text extracted from {image_path}")
return "NOT RECOGNIZED"
# print(f"Extracted Text (Before Correction): {extracted_text}")
return extracted_text # Return raw extracted text (no correction yet)
except Exception as e:
print(f"❌ Error processing {image_path}: {e}")
return "NOT RECOGNIZED"
def get_batch_number(extracted_texts):
"""
Determines the most common batch number based on the last two characters
in the extracted text.
"""
batch_counts = Counter()
for text in extracted_texts:
if len(text) >= 2:
batch_suffix = text[-2:] # Last 2 characters
batch_counts[batch_suffix] += 1
if not batch_counts:
return "XX" # No valid batch numbers found
batch_number, _ = batch_counts.most_common(1)[0] # Get most frequent
return batch_number
#Validate function
def validate_and_correct(text, batch_number) -> str:
"""Validates and corrects OCR extracted text."""
corrected_text = correct_label(text, batch_number)
# print(f"Extracted Text (after Correction): {corrected_text}")
# Extract the first two characters of the corrected text
first_two_chars = corrected_text[:2]
# Check if the first two characters are in the base36 list
if first_two_chars not in base36_numbers or corrected_text == "00":
return corrected_text, "red" # Highlight in red if the code is invalid
return corrected_text, "normal" # Otherwise, normal color
def resize_image(image_path):
# Load the image (BGR format)
img = image_path
if img is None:
raise ValueError(f"Could not read image: {image_path}")
scale_factor = 0.5
h, w = img.shape[:2]
new_width = w
new_height = int(h * scale_factor)
# Resize only height (keep width the same)
resized = cv2.resize(
img,
(new_width, new_height),
interpolation=cv2.INTER_CUBIC
)
return resized
def base10_to_base36(number: int) -> str:
'''Converts numbers in base10 to base36'''
if number < 0:
raise ValueError("Only non-negative integers are supported.")
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if number == 0:
return "0"
result = ""
while number:
number, remainder = divmod(number, 36)
result = digits[remainder] + result
return result if len(result)>1 else "0"+result
def write_ground_truth(folder_path:str):
'''Creates a text file with the filename and the corresponding base36 conversions for ground truth'''
# List to store the ground truth lines
ground_truth_lines = []
# Define the pattern to match filenames like "CT001.jpg"
pattern = re.compile(r'CT(\d{3})\.jpg')
for dirpath, _, filenames in os.walk(folder_path):
ground_truth_lines = []
for filename in sorted(filenames):
match = pattern.match(filename)
if match:
number = int(match.group(1).lstrip('0') or '0')
final_number = base10_to_base36(number)
if len(final_number) == 1:
final_number = "0" + final_number
ground_truth_lines.append(f'"{filename}", "{final_number}"')
if ground_truth_lines:
ground_truth_path = os.path.join(dirpath, 'ground_truth.txt')
with open(ground_truth_path, 'w', encoding='utf-8') as f:
for line in ground_truth_lines:
f.write(line + '\n')
# Generate valid base36 numbers from 1 to 200
base36_numbers = [base10_to_base36(i).zfill(2) for i in range(1, 201)]
def write_unordered_gt(folder_path:str, output_path:str) -> list[str]:
written_files = []
for root, _, files in os.walk(folder_path):
gt_lines = []
for f in sorted(files):
if f.lower().endswith(".txt") and "mapping_file_" in f: # To differentiate from other .txt files if they exist
ip_file = os.path.join(root, f)
with open(ip_file, "r") as f:
lines = f.readlines()
for line in lines[1:]:
line = line.strip()
if not line: continue
parts = line.split(",", 1)
if len(parts) < 2: continue # Ignore malflormed lines
id_part, num_part = parts[0].strip(), parts[1].strip()
id_part = id_part + ".jpg"
m = re.search(r"\d+", num_part)
if not m:
continue
num = int(m.group())
num_part_to_base36 = base10_to_base36(num)
gt_lines.append(f'"{id_part}", "{num_part_to_base36}"')
if gt_lines:
rel = os.path.relpath(root, folder_path)
target_dir = os.path.join(output_path, rel)
os.makedirs(target_dir, exist_ok=True)
ground_truth_path = os.path.join(target_dir, 'ground_truth.txt')
with open(ground_truth_path, 'w', encoding='utf-8') as f:
for line in gt_lines:
f.write(line + '\n')
written_files.append(ground_truth_path)
return written_files
import os
def process_images(folder):
"""Processes all images in the given folder and returns extracted data."""
extracted_data = []
seen_labels = set()
# print(f"🔍 Looking for images in: {folder}") # Debugging
for filename in os.listdir(folder):
if filename.lower().endswith((".jpg")):
image_path = os.path.join(folder, filename)
raw_text = extract_text_from_image(image_path, lang='eng')
corrected_text, color = validate_and_correct(raw_text)
is_duplicate = corrected_text in seen_labels
if is_duplicate:
color = "yellow"
seen_labels.add(corrected_text)
extracted_data.append({
"filename": filename,
"image_path": f"/static/uploads/{filename}",
"text": corrected_text,
"color": color,
"is_duplicate": is_duplicate
})
save_to_json_and_csv(extracted_data)
return extracted_data
'''STEP 2b: Correct Text'''
def save_to_json_and_csv(data, json_filename="data.json", csv_filename="data.csv"):
"""Ensures that JSON and CSV files are fully updated with the latest data."""
try:
# Save updated data to JSON (overwrite the entire file)
with open(json_filename, "w") as json_file:
json.dump(data, json_file, indent=4)
# print(f"✅ JSON successfully updated: {json_filename}")
# Save to CSV
with open("mapping_file.csv", "w", newline="") as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=["filename", "cavity_number"])
csv_writer.writeheader()
for row in data:
# Use `.get()` to provide a default value if 'cavity_number' is missing
csv_writer.writerow({
"filename": row["filename"],
"cavity_number": row.get("cavity_number", "N/A") # Default to "N/A" if missing
})
# print(f"✅ CSV successfully updated: {csv_filename}")
except Exception as e:
print(f"⚠️ Error updating JSON/CSV: {e}")
def update_corrected_text(corrected_data, json_filename="data.json", csv_filename="data.csv"):
"""Updates the JSON and CSV files with corrected values."""
try:
with open(json_filename, "r") as json_file:
existing_data = json.load(json_file)
except FileNotFoundError:
existing_data = []
# Update corrected values in the data
filename_to_corrected_text = {item["filename"]: item["corrected_text"] for item in corrected_data}
for entry in existing_data:
if entry["filename"] in filename_to_corrected_text:
entry["text"] = filename_to_corrected_text[entry["filename"]]
# Save updated JSON
with open(json_filename, "w") as json_file:
json.dump(existing_data, json_file, indent=4)
print(f"📂 Updated data saved to {json_filename}")
# Save updated CSV
with open(csv_filename, "w", newline="") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=["filename", "text", "color", "is_duplicate"])
writer.writeheader()
for row in existing_data:
writer.writerow(row)
print(f"📂 Updated data saved to {csv_filename}")
save_to_json_and_csv(corrected_data)
'''STEP 3: Export files to folders'''
def save_mapping_file(file_type, data, job_ID, printer):
"""Saves the mapping file in the correct printer folder."""
printer_folder = find_printer_folder(file_type, printer)
if not printer_folder:
return None
output_folder = os.path.join(printer_folder, "4_CT Mapping files")
os.makedirs(output_folder, exist_ok=True)
num_printer = convert_printerStr_to_printerNum(printer)
short_printer = get_short_printer(str(num_printer)) # Convert before passing
output_filename = f"mapping_file_ID{job_ID}_{short_printer}.txt"
output_path = os.path.join(output_folder, output_filename)
try:
with open(output_path, mode="w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Filename", "Cavity Number (Base-10)"])
for item in data:
filename = os.path.basename(item.get("filename", ""))
cavity_number = item.get("cavity_number", "")
if not filename or not cavity_number:
print(f"⚠️ Skipping invalid row: {item}")
continue
match = re.search(r"(CT\d+)", filename, re.IGNORECASE)
filename = match.group(1) if match else "UNKNOWN"
writer.writerow([filename, cavity_number])
print(f"📂 Mapping file saved: {output_path}")
return output_path
except Exception as e:
print(f"⚠️ Error saving mapping file: {e}")
return None
def update_merged_data(file_type, mcs_file_path, job_ID, printer):
"""Updates merged data and saves it in the correct printer folder."""
printer_folder = find_printer_folder(file_type, printer)
num_printer = convert_printerStr_to_printerNum(printer)
if not printer_folder:
return None
mapping_file = os.path.join(printer_folder, "4_CT Mapping files", f"mapping_file_ID{job_ID}_{get_short_printer(num_printer)}.txt")
if not os.path.exists(mapping_file):
print(f"⚠️ Error: Expected mapping file not found: {mapping_file}")
return None
mapping_df = pd.read_csv(mapping_file, dtype={'Filename': str})
mapping_df['Filename'] = mapping_df['Filename'].str.replace("CT", "")
ct_to_cavity = dict(zip(mapping_df['Filename'], mapping_df['Cavity Number (Base-10)']))
if not os.path.exists(mcs_file_path):
print(f"⚠️ Error: MCS file not found at {mcs_file_path}")
return None
merged_df = pd.read_csv(mcs_file_path, header=None, dtype={0: str}, encoding='utf-8')
merged_df[0] = merged_df[0].str.zfill(3)
merged_df[0] = merged_df[0].map(ct_to_cavity).fillna(merged_df[0])
output_folder = os.path.join(printer_folder, "1_Combined Job Data")
os.makedirs(output_folder, exist_ok=True)
short_printer = get_short_printer(num_printer)
sorted_filename = f"ID{job_ID}_{short_printer}_Sorted.txt"
sorted_file_path = os.path.join(output_folder, sorted_filename)
merged_df.to_csv(sorted_file_path, index=False, header=False, encoding='utf-8')
print(f"✅ Sorted file saved: {sorted_file_path}")
return sorted_file_path
def get_short_printer(printer):
"""If printer number is 6 characters, return the last 3 digits. Otherwise, return as is."""
return printer[-3:] if len(printer) == 6 else printer
def find_02_CT_Data(file_type):
"""
Tries to find the '02_CT Data' folder by:
1. Searching upwards from the CWD (for most use cases).
2. Handling the GitHub folder case where '02_CT Data' is outside the current directory structure.
"""
import os
# Get the current working directory (CWD)
current_dir = os.path.abspath(os.getcwd())
# Step 1: Search upwards from the CWD for '02_CT Data' (standard behavior)
while current_dir:
potential_path = os.path.join(current_dir, "02_CT Data")
if os.path.exists(potential_path):
# print(f"✅ Found '02_CT Data' folder at: {potential_path}")
return potential_path
# Stop if we reach the root directory
parent_dir = os.path.dirname(current_dir)
if parent_dir == current_dir:
break
current_dir = parent_dir
# Step 2: Handle GitHub folder case: Look for '02_CT Data' relative to the repo
if "GitHub" in current_dir: # We are inside a GitHub folder
print(f"⚠️ Detected working within a GitHub folder: {current_dir}")
# If we are in a GitHub project, look for '02_CT Data' in a specific known relative location
user_home_dir = os.path.expanduser("~")
github_base = os.path.join(user_home_dir, "GitHub", "AM-Label_Reader_App")
# Check if '02_CT Data' is in a known relative location
potential_path = os.path.join(github_base, "02_CT Data")
if os.path.exists(potential_path):
# print(f"⚠️ Found '02_CT Data' above GitHub repo folder: {potential_path}")
return potential_path
# Step 3: Fallback to OneDrive path if nothing works
user_home_dir = os.path.expanduser("~")
fallback_path = os.path.join(
user_home_dir, "LEGO", "EM - AD&M Element Maturing - General",
"09_CT Data", "DigitalSorting_APP", "02_CT Data", file_type
)
print(fallback_path)
if os.path.exists(fallback_path):
# print(f"⚠️ Using fallback path (OneDrive): {fallback_path}")
return fallback_path
print("❌ Error: '02_CT Data' folder not found.")
return None
def find_MCS_Data():
"""Finds the most recent MCS .txt file in the 'static/uploads' folder relative to this script."""
import os
import glob
# Get base folder of this script (i.e., where helpers.py lives)
try:
base_dir = os.path.abspath(os.path.dirname(__file__))
except NameError:
base_dir = os.getcwd()
uploads_path = os.path.join(base_dir, "static", "uploads")
if not os.path.exists(uploads_path):
print(f"❌ Error: Uploads folder not found at {uploads_path}")
return None
# Look for all .txt files
txt_files = glob.glob(os.path.join(uploads_path, "*.txt"))
if not txt_files:
print(f"❌ Error: No .txt files found in {uploads_path}")
return None
# Sort by most recent modification time
txt_files.sort(key=os.path.getmtime, reverse=True)
most_recent_file = txt_files[0]
# print(f"✅ Found MCS file: {most_recent_file}")
return most_recent_file
def convert_printerStr_to_printerNum(printer):
with open("static/printer_lookup.json", "r") as f: # Keep this program and static in the same folder, else change accordingly
p = json.load(f)
if isinstance(printer, str) and printer in p["PRINTER_ID_MAP"]:
return p["PRINTER_ID_MAP"][printer]
else: return None
def find_printer_folder(file_type, printer):
"""Finds the printer-specific folder inside '02_CT Data'."""
ct_data_path = find_02_CT_Data(file_type)
if not ct_data_path:
return None
num_printer = convert_printerStr_to_printerNum(printer)
short_printer = get_short_printer(str(num_printer)) # Convert before passing
for folder in os.listdir(ct_data_path):
if folder.startswith(short_printer):
return os.path.join(ct_data_path, folder)
print(f"⚠️ Error: Printer folder for {short_printer} not found in '02_CT Data'!")
return None
def collect_image_gt_pairs(root_folder):
"""
Recursively collects image-ground truth pairs from all subfolders within the root folder.
Each folder is expected to contain a 'ground_truth.txt' file with lines formatted as:
"image_filename","ground_truth_text"
Args:
root_folder (str): Path to the root directory containing STL folders and subfolders.
Returns:
List[Tuple[str, str]]: A list of tuples where each tuple contains the image path and its ground truth text.
"""
print("Finding images and ground truth...")
image_gt_pairs = []
for dirpath, _, filenames in os.walk(root_folder):
if "ground_truth.txt" in filenames:
gt_path = os.path.join(dirpath, "ground_truth.txt")
with open(gt_path, "r", encoding="utf-8") as f:
for line in f:
parts = line.strip().split(',')
if len(parts) == 2:
img_file = parts[0].strip().strip('"')
gt_text = parts[1].strip().strip('"')
img_path = os.path.join(dirpath, img_file)
if os.path.exists(img_path):
image_gt_pairs.append((img_path, gt_text))
if len(image_gt_pairs) == 0:
print("No ground-truth pairs. Try again")
return -1
else:
print(f"Found {len(image_gt_pairs)} image-ground truth pairs.")
print("Finished getting images, now going to train test and split")
return image_gt_pairs
# Build table in mlflow
def confusion_dataframe(char_summary):
conf = char_summary.get("confusion")
if not conf: return None
rows = []
for gt_char, pred in conf.items():
for pred_char, cnt in pred.items():
rows.append({"gt_char": gt_char, "pred_char": pred_char, "count": cnt})
return pd.DataFrame(rows).sort_values(["gt_char", "count"], ascending=[True, False])
# Per character accuracy
def char_accuracy_dataframe(char_summary):
rows = []
per_char = char_summary["per_character"]
tot_seen = sum(m["seen"] for m in per_char.values())
for ch, m in per_char.items():
seen = int(m["seen"])
rows.append({
"char": ch,
"seen": seen,
"correct": int(m["correct"]),
"accuracy": float(m["accuracy"]) if m["accuracy"] is not None else None,
# Compute relative character error rate
"cer": 1.0 - float(m["accuracy"]) if m["accuracy"] is not None else None,
"weight": 0.0 if tot_seen == 0 else (seen/tot_seen)
})
return pd.DataFrame(rows).sort_values("char").reset_index(drop=True)
CHARACTERS = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
# Plot correlation matrix for individual characters
def plot_heatmap(df_err, style='seaborn-v0_8', plot_size = (10,8), path = "cer_heatmap.png",
show_char_labels = True):
if 'char' not in df_err.columns: raise KeyError("Expected 'char' column in df")
df_err = df_err.set_index('char') # This works well for building a heatmap
# Build a 6x6 heatmap
values = []
labels = []
for r in range(6):
row_vals = []
row_labs = []
for c in range(6):
idx = r*6 + c
ch = CHARACTERS[idx]
val = df_err.loc[ch, "cer"]
row_vals.append(val)
row_labs.append(ch)
values.append(row_vals)
labels.append(row_labs)
matrix = array(values, dtype=float)
with plt.style.context(style = style):
fig, ax = plt.subplots(figsize=plot_size)
hm = sns.heatmap(
matrix,
ax=ax,
cmap="coolwarm",
annot=labels if show_char_labels else False,
fmt="",
square=True,
linewidths=0.5,
linecolor="white",
cbar_kws={"label": "CER (1-accuracy)"},
)
ax.set_title("Per-character CER")
ax.set_xticks([])
ax.set_yticks([])
plt.tight_layout()
fig.savefig(path, dpi=300)
plt.close(fig)
return path
# FUNCTIONS TO GET SCREENSHOTS OF THE PARTS FROM
# -------------------------------------------------------------
# AUTO-ROTATION: Rotate engraving vector so it faces +X
# -------------------------------------------------------------
def rotation_to_align_with_x(vec):
"""
Compute rotation matrix that rotates arbitrary vector 'vec' onto +X axis.
"""
target = np.array([1.0, 0.0, 0.0]) # +X is our camera direction
v = vec / np.linalg.norm(vec)
# Axis = cross product
axis = np.cross(v, target)
axis_len = np.linalg.norm(axis)
if axis_len < 1e-8: # already aligned
return np.eye(3)
axis /= axis_len
angle = np.arccos(np.clip(np.dot(v, target), -1.0, 1.0))
# Rodrigues rotation formula
K = np.array([
[0, -axis[2], axis[1]],
[axis[2], 0, -axis[0]],
[-axis[1], axis[0], 0]
])
R = np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * (K @ K)
return R
# -------------------------------------------------------------
# PROJECT 3D → PIXELS USING PYRENDER PROJECTION MATRIX
# -------------------------------------------------------------
def project_to_pixels(points, projection_matrix, width, height):
pts_h = np.hstack([points, np.ones((points.shape[0], 1))])
clip = pts_h @ projection_matrix.T
ndc = clip[:, :3] / clip[:, 3][:, None]
px = ((ndc[:, 0] + 1) * 0.5) * width
py = ((1 - ndc[:, 1]) * 0.5) * height
return px, py
# -------------------------------------------------------------
# MAIN FUNCTION: RENDER ENGRAVING + CROP
# -------------------------------------------------------------
def render_and_crop(stl_path, bbox, out_path, zoom=0.6):
xmin, xmax, ymin, ymax, zmin, zmax = bbox
engr_min = np.array([xmin, ymin, zmin])
engr_max = np.array([xmax, ymax, zmax])
# --------------------------------------------------
# Load mesh
# --------------------------------------------------
mesh = trimesh.load(stl_path)
pm = pyrender.Mesh.from_trimesh(mesh, smooth=False)
# --------------------------------------------------
# Camera setup
# --------------------------------------------------
bounds = mesh.bounds
forward = np.array([1.0, 0.0, 0.0])
xmag = (bounds[1][1] - bounds[0][1]) / 2 * zoom
ymag = (bounds[1][2] - bounds[0][2]) / 2 * zoom
cam = pyrender.OrthographicCamera(xmag=xmag, ymag=ymag)
engr_center = (engr_min + engr_max) / 2
distance = 4
cam_pose_render = np.eye(4) # create identity matrix
# Define up (keep consistent)
world_up = np.array([0, 1, 0])
# Build orthonormal basis
right = np.cross(world_up, forward)
right /= np.linalg.norm(right)
up = np.cross(forward, right)
# Build camera matrix
cam_pose_render[:3, 0] = right
cam_pose_render[:3, 1] = up
cam_pose_render[:3, 2] = forward
cam_pose_render[:3, 3] = (engr_center + np.array([0, 0, distance]))
# --------------------------------------------------
# Prepare engraving bbox
# --------------------------------------------------
xs = [engr_min[0], engr_max[0]]
ys = [engr_min[1], engr_max[1]]
zs = [engr_min[2], engr_max[2]]
corners = np.array([[x, y, z] for x in xs for y in ys for z in zs])
corners_h = np.hstack([corners, np.ones((8, 1))])
# --------------------------------------------------
# Iterative auto-centering
# --------------------------------------------------
w = h = 1024
for _ in range(2): # 2 iterations is enough
# ----- Build scene -----
right = cam_pose_render[:3, 0]
up = cam_pose_render[:3, 1]
scene = pyrender.Scene(
bg_color=[1, 1, 1, 1],
ambient_light=[0.3, 0.3, 0.3]
)
scene.add(pm)
scene.add(cam, pose=cam_pose_render)
light = pyrender.DirectionalLight(color=np.ones(3), intensity=5.0)
scene.add(light, pose=cam_pose_render)
# ----- Render -----
renderer = pyrender.OffscreenRenderer(w, h)
color, _ = renderer.render(scene)
renderer.delete()
# ----- Project bbox -----
bbox_cam = (cam_pose_render @ corners_h.T).T[:, :3]
proj = cam.get_projection_matrix(w / h)
px, py = project_to_pixels(bbox_cam, proj, w, h)
x_min = min(px)
x_max = max(px)
y_min = min(py)
y_max = max(py)
# ----- Compute center offset -----
cx_img = (x_min + x_max) / 2
cy_img = (y_min + y_max) / 2
img_cx = w / 2
img_cy = h / 2
dx_pix = cx_img - img_cx
dy_pix = cy_img - img_cy
# Convert pixel shift → world shift
dx_world = (dx_pix / w) * (2 * cam.xmag)
dy_world = (dy_pix / h) * (2 * cam.ymag)
# --------------------------------------------------
# Final render (centered)
# --------------------------------------------------
scene = pyrender.Scene(
bg_color=[1, 1, 1, 1],
ambient_light=[0.3, 0.3, 0.3]
)
scene.add(pm)
scene.add(cam, pose=cam_pose_render)
light = pyrender.DirectionalLight(color=np.ones(3), intensity=5.0)
scene.add(light, pose=cam_pose_render)
renderer = pyrender.OffscreenRenderer(w, h)
color, _ = renderer.render(scene)
renderer.delete()
# Save final image
img = Image.fromarray(color)
img = img.rotate(270, expand = True) # Roteting clockwise
img.save(out_path)
return out_path
def render_cylinder_region_with_center(
stl_path,
cylinder_center, # (cx0, cy0, cz0)
radius,
angle_min_deg,
angle_max_deg,
bbox, # [xmin,xmax, ymin,ymax, zmin,zmax]
out_path,
resolution=1024
):
xmin, xmax, ymin, ymax, zmin, zmax = bbox
# -----------------------------------------
# 1. Engraving center
# -----------------------------------------
ex = 0.5 * (xmin + xmax)
ey = 0.5 * (ymin + ymax)
ez = 0.5 * (zmin + zmax)
# -----------------------------------------
# 2. Angle midpoint
# -----------------------------------------
# ADD OR SUBTRACT ANGLES DEPENDING ON WHICH SIDE YOUR ENGRAVING LEANS IN
theta = np.deg2rad(0.5 * (angle_min_deg + angle_max_deg + 15))
cx0, cy0, cz0 = cylinder_center
# -----------------------------------------
# 3. Camera position (your working logic)
# -----------------------------------------
inward_offset = 1.5
effective_r = radius + inward_offset
cam_x = cx0 + (effective_r - 5) * np.cos(theta)
cam_z = cz0 + effective_r * np.sin(theta)
cam_y = ey
cam_pos = np.array([cam_x, cam_y, cam_z])
# -----------------------------------------
# ✅ 4. CORRECT CAMERA ORIENTATION (KEY FIX)
# -----------------------------------------
# Forward = radial direction (towards cylinder)
forward = np.array([
cx0 - cam_x,
0,
cz0 - cam_z
])
forward /= np.linalg.norm(forward)
# Up = cylinder axis (stable and correct)
up = np.array([0, 1, 0])
# Right = perpendicular
right = np.cross(up, forward)
right /= np.linalg.norm(right)
# Recompute orthogonal up
up = np.cross(forward, right)
# Build camera pose
cam_pose = np.eye(4)
cam_pose[:3, 0] = right
cam_pose[:3, 1] = up
cam_pose[:3, 2] = forward
cam_pose[:3, 3] = cam_pos
# -----------------------------------------
# 5. Load mesh
# -----------------------------------------
mesh = trimesh.load(stl_path)
pm = pyrender.Mesh.from_trimesh(mesh, smooth=False)
scene = pyrender.Scene(
bg_color=[1, 1, 1, 1],
ambient_light=[0.4, 0.4, 0.4]
)
scene.add(pm)
# -----------------------------------------
# 6. Camera zoom (your working logic)
# -----------------------------------------
width = max((xmax - xmin), (zmax - zmin))
height = ymax - ymin
cam = pyrender.OrthographicCamera(
xmag=width * 0.7,
ymag=height * 0.7
)
scene.add(cam, pose=cam_pose)
# -----------------------------------------
# 7. Lighting
# -----------------------------------------
light = pyrender.DirectionalLight(
color=np.ones(3),
intensity=5.0
)
scene.add(light, pose=cam_pose)
# -----------------------------------------
# 8. Render
# -----------------------------------------
renderer = pyrender.OffscreenRenderer(resolution, resolution)
color, _ = renderer.render(scene)
renderer.delete()
Image.fromarray(color).save(out_path)
return out_path