-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmart_ic_authenticator.py
More file actions
1683 lines (1408 loc) · 76.2 KB
/
smart_ic_authenticator.py
File metadata and controls
1683 lines (1408 loc) · 76.2 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
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
"""
Smart IC Authenticator - Production System
Uses Intelligent OCR with Multi-Orientation Detection + Datasheet Verification
No YOLO dependency - Direct OCR is faster and more reliable
"""
import cv2
import numpy as np
import easyocr
import requests
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import re
import logging
from bs4 import BeautifulSoup
import PyPDF2
import io
import torch
from smart_datasheet_finder import SmartDatasheetFinder
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SmartICAuthenticator:
"""Production-ready IC authentication system with intelligent OCR and datasheet verification"""
def __init__(self):
"""Initialize OCR and datasheet systems"""
# Check GPU availability
gpu_available = torch.cuda.is_available()
if gpu_available:
logger.info(f"✓ GPU Available: {torch.cuda.get_device_name(0)}")
logger.info(f" CUDA Version: {torch.version.cuda}")
else:
logger.warning("⚠ GPU not available - using CPU mode")
# Load OCR with GPU support for fast processing
logger.info("Loading EasyOCR with GPU support...")
self.ocr_reader = easyocr.Reader(['en'], gpu=gpu_available, verbose=False)
if gpu_available:
logger.info("✓ EasyOCR loaded with GPU acceleration")
else:
logger.info("✓ EasyOCR loaded in CPU mode")
# Initialize smart datasheet finder
self.datasheet_cache = Path("datasheet_cache")
self.datasheet_cache.mkdir(exist_ok=True)
self.datasheet_finder = SmartDatasheetFinder(self.datasheet_cache)
# HTTP session for datasheet downloads
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
# Configure session with aggressive timeouts
adapter = requests.adapters.HTTPAdapter(
pool_connections=5, # Reduced from 10
pool_maxsize=10, # Reduced from 20
max_retries=0, # No retries - fail fast
pool_block=False
)
self.session.mount('http://', adapter)
self.session.mount('https://', adapter)
# Datasheet cache
self.datasheet_cache = Path('datasheet_cache')
self.datasheet_cache.mkdir(exist_ok=True)
# IC part number patterns (comprehensive)
self.ic_patterns = {
'ATMEGA': r'AT\s*[MT]?EGA\s*\d+[A-Z]*\d*', # More lenient: AT MEGA, ATMEGA, AMEGA
'ATTINY': r'AT\s*TINY\s*\d+[A-Z]*',
'ATMEL': r'AT\s*MEL\s*\d+[A-Z]*\d*', # ATMEL general
'AT': r'AT\s*\d{3,4}[A-Z]*\d*[A-Z]*', # Generic Atmel parts (AT89, AT90, AT24, etc.)
'PIC': r'PIC\s*\d+[A-Z]\s*\d+[A-Z]*\d*', # Allow spaces in PIC18F45K22
'STM32': r'STM32[A-Z]\d+[A-Z]*\d*[A-Z]*',
'LM': r'[IL]M\s*\d+[A-Z]*\d*[A-Z]*', # Allow I→L confusion
'LM556': r'[IL]M\s*556[A-Z]*', # Specific pattern for LM556 (dual 555)
'TL': r'[TI][LI]\s*\d+[A-Z]*\d*', # Texas Instruments TL series with OCR errors
'TLC': r'TLC\s*\d+[A-Z]*', # TI TLC series
'TPS': r'TPS\s*\d+[A-Z]*\d*', # TI TPS power series
'SN74': r'SN74[A-Z]+\d+[A-Z]*',
'SN': r'[S5]N\s*\d+[A-Z]*\d*', # General SN series (5→S confusion)
'CY8C': r'CY8C\d+[A-Z]*-?\d*[A-Z]*', # Optional dash
'CY7C': r'CY7C\d+[A-Z]*-?\d*[A-Z]*',
'MC': r'[MN]C\d+[A-Z]*\d*[A-Z]*', # M→N confusion
'MCP': r'MCP\s*\d+[A-Z]*\d*', # Microchip MCP series
'ADC': r'ADC\s*\d+[A-Z]+\d*', # ADC followed by number and letters
'DAC': r'DAC\s*\d+[A-Z]*\d*',
'LT': r'[IL]T\s*\d+[A-Z]*\d*', # I→L confusion
'AD': r'A[D0O]\s*\d+[A-Z]*\d*', # D→0/O confusion
'MAX': r'[MNW]AX\s*\d+[A-Z]*\d*', # M→N/W confusion
'NE': r'[NW]E\s*\d+[A-Z]*\d*', # N→W confusion
'SE': r'[S5]E\s*\d+[A-Z]*', # Signetics/TI SE series
'LMC': r'LMC\s*\d+[A-Z]*', # TI LMC series
'TMP': r'T[MN]P\s*\d+[A-Z]*', # TI temperature sensors
'INA': r'INA\s*\d+[A-Z]*', # TI current sense
'OPA': r'[O0]PA\s*\d+[A-Z]*', # TI op-amps (O→0 confusion)
'AUCH': r'AUCH\d+[A-Z]*\d*[A-Z]*', # TI AUCH series
'M74HC': r'M74HC\d+[A-Z]\d', # STM 74HC series
'74HC': r'74H[CO]\d+[A-Z]*', # Generic 74HC (C→O confusion)
'74LS': r'74[IL]S\d+[A-Z]*', # 74LS series (L→I confusion)
'CD': r'CD\s*\d+[A-Z]*\d*', # CD4xxx series
'ULN': r'ULN\s*\d+[A-Z]*', # ULN2xxx driver series
'2N': r'2N\s*\d+[A-Z]*', # Transistors (2N2222, etc.)
'L293': r'L\s*293[A-Z]*', # Motor driver
}
# Manufacturer mappings
self.mfg_map = {
'ATMEGA': 'Microchip',
'ATTINY': 'Microchip',
'ATMEL': 'Microchip',
'AT': 'Microchip', # Generic Atmel (now part of Microchip)
'PIC': 'Microchip',
'MCP': 'Microchip',
'STM32': 'STMicroelectronics',
'M74HC': 'STMicroelectronics',
'LM': 'Texas Instruments',
'LM556': 'Texas Instruments', # Dual 555 timer
'LMC': 'Texas Instruments',
'TL': 'Texas Instruments',
'TLC': 'Texas Instruments',
'TPS': 'Texas Instruments',
'TMP': 'Texas Instruments',
'INA': 'Texas Instruments',
'OPA': 'Texas Instruments',
'SN74': 'Texas Instruments',
'SN': 'Texas Instruments',
'ADC': 'Texas Instruments',
'DAC': 'Texas Instruments',
'NE': 'Various', # NE555 made by many (TI, ST, Fairchild, etc.)
'SE': 'Texas Instruments',
'AUCH': 'Texas Instruments',
'CY8C': 'Infineon',
'CY7C': 'Infineon',
'MC': 'NXP',
'LT': 'Analog Devices',
'AD': 'Analog Devices',
'MAX': 'Analog Devices',
'74HC': 'Various',
'74LS': 'Various',
'CD': 'Texas Instruments',
'ULN': 'STMicroelectronics',
'2N': 'Various',
'L293': 'Texas Instruments',
}
def authenticate(self, image_path: str) -> Dict:
"""Main authentication pipeline"""
logger.info(f"\n{'='*70}")
logger.info(f"Authenticating: {Path(image_path).name}")
logger.info(f"{'='*70}")
try:
# Load image
image = cv2.imread(image_path)
if image is None:
logger.error(" ✗ Could not load image")
return self._create_error_result(image_path, 'Could not load image file')
# Step 1: OCR extraction with automatic orientation detection
logger.info("Step 1: OCR text extraction...")
ocr_results = self._extract_text_ocr(image)
# Step 2: Parse and identify part number
logger.info("Step 2: Part number identification...")
part_info = self._identify_part_number(ocr_results)
if not part_info['part_number']:
logger.error(" ✗ No IC part number detected")
return self._create_error_result(image_path, 'No IC part number detected in image',
ocr_results.get('full_text', ''))
logger.info(f" ✓ Part Number: {part_info['part_number']}")
logger.info(f" ✓ Manufacturer: {part_info['manufacturer']}")
# Step 3: Find datasheet
logger.info("Step 3: Finding datasheet...")
datasheet = self._find_datasheet(part_info['part_number'], part_info['manufacturer'])
if datasheet['found']:
logger.info(f" ✓ Datasheet found: {datasheet['url']}")
else:
logger.info(f" ✗ Datasheet not found")
# Step 4: Verify marking
logger.info("Step 4: Marking verification...")
marking_valid = False
if datasheet['found'] and datasheet.get('marking_info'):
marking_valid = self._verify_marking(ocr_results, datasheet['marking_info'], part_info['part_number'])
# Step 5: Counterfeit detection (pass marking_info for validation)
logger.info("Step 5: Counterfeit detection...")
counterfeit_check = self._check_for_counterfeits(ocr_results, part_info['part_number'],
part_info['manufacturer'],
datasheet_found=datasheet['found'],
marking_info=datasheet.get('marking_info', {}))
if counterfeit_check['flags']:
logger.warning(" ⚠️ Suspicious indicators detected:")
for flag in counterfeit_check['flags']:
logger.warning(f" - {flag}")
else:
logger.info(" ✓ No suspicious indicators found")
# Calculate verdict
confidence = self._calculate_confidence(part_info, datasheet, marking_valid, counterfeit_check)
# Adjusted thresholds for more balanced verdicts
if confidence >= 80:
verdict = "AUTHENTIC"
elif confidence >= 60:
verdict = "LIKELY AUTHENTIC"
elif confidence >= 35:
verdict = "SUSPICIOUS"
else:
verdict = "LIKELY COUNTERFEIT"
logger.info(f"\nVerdict: {verdict} ({confidence}%)")
# Generate debug images for GUI
img = cv2.imread(image_path)
debug_ocr_image = None
debug_variants = []
# Create OCR debug image with bounding boxes
if img is not None and ocr_results.get('details'):
debug_ocr_image = img.copy()
img_height, img_width = debug_ocr_image.shape[:2]
for detail in ocr_results['details']:
bbox = detail['bbox']
text = detail['text']
conf = detail['confidence']
# Convert bbox to integer points and clip to image bounds
points = np.array(bbox, dtype=np.int32)
points[:, 0] = np.clip(points[:, 0], 0, img_width - 1)
points[:, 1] = np.clip(points[:, 1], 0, img_height - 1)
# Draw bounding box
cv2.polylines(debug_ocr_image, [points], True, (0, 255, 255), 2)
# Draw text label with background (with bounds checking)
text_label = f"{text} ({conf:.2f})"
(w, h), _ = cv2.getTextSize(text_label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
# Calculate label position with bounds checking
label_x = max(0, min(points[0][0], img_width - w))
label_y = max(h + 5, points[0][1]) # Ensure label is within image
cv2.rectangle(debug_ocr_image,
(label_x, label_y - h - 5),
(min(label_x + w, img_width - 1), label_y),
(0, 255, 255), -1)
cv2.putText(debug_ocr_image, text_label, (label_x, label_y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
# Get preprocessing variants
if ocr_results.get('preprocessing_images'):
debug_variants = [(p['name'], p['image']) for p in ocr_results['preprocessing_images']]
# MEMORY CLEANUP: Delete large objects before returning
result = {
'success': True,
'part_number': part_info['part_number'],
'normalized_part_number': part_info['part_number'],
'manufacturer': part_info['manufacturer'],
'datasheet_found': datasheet['found'],
'datasheet_url': datasheet.get('url'), # Original manufacturer URL (can be None)
'datasheet_local_file': datasheet.get('local_file'), # Local cached PDF for viewer
'datasheet_source': datasheet.get('source'),
'marking_verified': marking_valid,
'marking_validation': {
'validation_passed': marking_valid,
'manufacturer': part_info['manufacturer'],
'issues': counterfeit_check.get('marking_issues', [])
},
'counterfeit_flags': counterfeit_check['flags'],
'suspicion_score': counterfeit_check['suspicion_score'],
'confidence': confidence,
'verdict': verdict,
'counterfeit_reasons': self._generate_counterfeit_explanation(
verdict, counterfeit_check, part_info, datasheet, marking_valid
),
'is_authentic': confidence >= 65,
'full_text': ocr_results['full_text'],
'ocr_details': ocr_results.get('details', []),
'ocr_confidence': ocr_results.get('ocr_confidence', 0.0), # Add OCR confidence
'preprocessing_images': ocr_results.get('preprocessing_images', []), # Add preprocessing
'debug_ocr_image': debug_ocr_image, # Add debug OCR image
'debug_variants': debug_variants, # Add debug preprocessing variants
'image_path': image_path,
'date_codes': [],
'reasons': []
}
# Delete large numpy arrays from ocr_results to free memory
if 'preprocessing_images' in ocr_results:
del ocr_results['preprocessing_images']
del ocr_results, img
return result
except Exception as e:
import traceback
error_msg = f"Authentication error: {str(e)}"
logger.error(f" ✗ {error_msg}")
logger.debug(traceback.format_exc())
return self._create_error_result(image_path, error_msg)
finally:
# Memory cleanup
import gc
gc.collect()
def _create_error_result(self, image_path: str, error_msg: str, extracted_text: str = '') -> Dict:
"""Create a standardized error result"""
return {
'success': False,
'error': error_msg,
'part_number': 'N/A',
'normalized_part_number': 'N/A',
'manufacturer': 'Unknown',
'datasheet_found': False,
'datasheet_url': None,
'marking_verified': False,
'counterfeit_flags': [],
'suspicion_score': 0,
'confidence': 0,
'verdict': 'ERROR',
'is_authentic': False,
'full_text': extracted_text,
'ocr_details': [],
'image_path': image_path,
'date_codes': [],
'reasons': [f'Error: {error_msg}']
}
def _try_all_orientations(self, image: np.ndarray) -> Tuple[np.ndarray, int]:
"""Try all 4 cardinal orientations and return the best one for OCR"""
try:
best_image = image.copy()
best_angle = 0
best_score = 0
best_results = []
# Try 4 cardinal rotations: 0°, 90°, 180°, 270°
for angle in [0, 90, 180, 270]:
# Rotate image
if angle == 0:
rotated = image.copy()
elif angle == 90:
rotated = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
elif angle == 180:
rotated = cv2.rotate(image, cv2.ROTATE_180)
elif angle == 270:
rotated = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
# Enhance image for OCR test
gray = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
enhanced = clahe.apply(gray)
enhanced_bgr = cv2.cvtColor(enhanced, cv2.COLOR_GRAY2BGR)
# Quick OCR test with LOW confidence threshold to detect any text
results = self.ocr_reader.readtext(enhanced_bgr, detail=1, paragraph=False,
min_size=5, text_threshold=0.5,
low_text=0.3, link_threshold=0.3)
# Score based on number of alphanumeric characters found
score = 0
for bbox, text, conf in results:
# Count alphanumeric characters (indicates real text vs noise)
alnum_count = sum(c.isalnum() for c in text)
if alnum_count >= 2: # At least 2 alphanumeric chars
score += alnum_count * conf
logger.debug(f" Angle {angle:3d}°: {len(results)} detections, score={score:.2f}")
if score > best_score:
best_score = score
best_image = rotated
best_angle = angle
best_results = results
if best_angle != 0:
logger.info(f" Auto-rotation: Best orientation is {best_angle}° (score: {best_score:.2f})")
else:
logger.info(f" No rotation needed (original best, score: {best_score:.2f})")
return best_image, best_angle
except Exception as e:
logger.debug(f"Orientation detection failed: {e}, using original image")
return image, 0
def _extract_text_ocr(self, image: np.ndarray) -> Dict:
"""Extract text using OCR with automatic orientation detection and optimized preprocessing"""
all_text = []
ocr_details = [] # Store bbox and text for drawing
preprocessing_images = [] # Store preprocessing variants for debugging
# STEP 1: Try all 4 cardinal orientations automatically (0°, 90°, 180°, 270°)
image, rotation_angle = self._try_all_orientations(image)
# STEP 2: Resize image if too large (speeds up OCR significantly)
h, w = image.shape[:2]
max_dim = 1200 # Maximum dimension
if max(h, w) > max_dim:
scale = max_dim / max(h, w)
new_w, new_h = int(w * scale), int(h * scale)
image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
logger.info(f" Resized image from {w}x{h} to {new_w}x{new_h} for faster OCR")
# Preprocess full image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply CLAHE for better contrast
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
enhanced = clahe.apply(gray)
# Convert back to BGR for EasyOCR
enhanced_bgr = cv2.cvtColor(enhanced, cv2.COLOR_GRAY2BGR)
# STEP 3: Use multiple preprocessing variants for robust text extraction
# (No YOLO - direct full-image OCR is faster and more reliable)
# Variant 1: Bilateral filter (preserves edges while reducing noise)
bilateral = cv2.bilateralFilter(gray, 9, 75, 75)
bilateral_bgr = cv2.cvtColor(bilateral, cv2.COLOR_GRAY2BGR)
# Variant 2: Adaptive threshold
thresh_adaptive = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
thresh_adaptive_bgr = cv2.cvtColor(thresh_adaptive, cv2.COLOR_GRAY2BGR)
# Variant 3: Unsharp masking (enhances edges/text)
gaussian = cv2.GaussianBlur(enhanced, (0, 0), 2.0)
unsharp = cv2.addWeighted(enhanced, 1.5, gaussian, -0.5, 0)
unsharp_bgr = cv2.cvtColor(unsharp, cv2.COLOR_GRAY2BGR)
# Variant 4: OTSU threshold
_, thresh_otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
thresh_otsu_bgr = cv2.cvtColor(thresh_otsu, cv2.COLOR_GRAY2BGR)
# Try variants in order of effectiveness (REDUCED from 9 to 5 variants for SPEED)
variants = [enhanced_bgr, bilateral_bgr, thresh_adaptive_bgr, unsharp_bgr, thresh_otsu_bgr]
variant_names = ['CLAHE Enhanced', 'Bilateral Filter', 'Adaptive Threshold', 'Unsharp Mask', 'OTSU Binary']
# Store only first 3 preprocessing images for debug (save memory)
for name, var_img in zip(variant_names[:3], variants[:3]):
preprocessing_images.append({
'name': name,
'image': var_img.copy()
})
best_text_count = 0
best_results = []
best_variant_name = 'Unknown'
best_confidence = 0.0
for idx, img_variant in enumerate(variants):
try:
results = self.ocr_reader.readtext(img_variant, paragraph=False)
variant_text = []
variant_details = []
total_conf = 0.0
conf_count = 0
for (bbox, text, conf) in results:
if conf > 0.08: # Low threshold to catch more text
# Fix common OCR errors
text = self._fix_ocr_errors(text)
if text and len(text) > 1:
variant_text.append(text)
total_conf += conf
conf_count += 1
# Store for visualization
if conf > 0.15: # Lower threshold for drawing (capture more text)
variant_details.append({
'bbox': bbox,
'text': text,
'confidence': conf
})
# Calculate average confidence for this variant
avg_conf = (total_conf / conf_count * 100) if conf_count > 0 else 0.0
# Use the variant that extracted the most text
if len(variant_text) > best_text_count:
best_text_count = len(variant_text)
all_text = variant_text
ocr_details = variant_details
best_variant_name = variant_names[idx]
best_confidence = avg_conf
# EARLY TERMINATION: If we got good results, stop immediately
# REDUCED threshold to handle low-confidence but valid detections
if best_text_count >= 3 and avg_conf > 25:
logger.info(f" ✓ Good OCR results, early stop at: {best_variant_name}")
break
except Exception as e:
logger.debug(f"OCR variant failed: {e}")
continue
logger.info(f" Best OCR: {best_variant_name} ({best_text_count} items, {best_confidence:.1f}% conf)")
full_text = ' '.join(all_text)
logger.info(f" Extracted text: {full_text[:100]}...")
return {
'lines': all_text,
'full_text': full_text,
'details': ocr_details,
'preprocessing_images': preprocessing_images, # Add preprocessing images to result
'ocr_confidence': best_confidence # Add OCR confidence
}
def _fix_ocr_errors(self, text: str) -> str:
"""Fix common OCR mistakes"""
# Fix "ALMEL" → "ATMEL", "AImel" → "ATMEL", "Anel" → "ATMEL", "A?MEL" → "ATMEL"
text = re.sub(r'[Aa][IlLn\?][Mm]?[Ee][Ll]', 'ATMEL', text, flags=re.IGNORECASE)
# Fix "A?" → "AT" (common OCR error)
text = re.sub(r'A\?', 'AT', text)
text = re.sub(r'A\s+\?', 'AT', text)
# Fix ATMEGA variations: AtMEGAS2BP → ATMEGA328P, ATMEGA3282 → ATMEGA328P
text = re.sub(r'At?MEGA[Ss]?2[B8]P?', 'ATMEGA328P', text, flags=re.IGNORECASE)
text = re.sub(r'ATMEGA3282', 'ATMEGA328P', text, flags=re.IGNORECASE)
# Fix M?4HC → M74HC (? → 7 confusion)
text = re.sub(r'M\?4HC', 'M74HC', text)
# Fix LK → LM (common OCR error where M is read as K)
text = re.sub(r'\bLK\b', 'LM', text) # Word boundary to avoid changing other text
text = re.sub(r'\bLK(\d)', r'LM\1', text) # LK358 → LM358
# Fix NE555 SSS→555 OCR error: NESSSP → NE555P, NE5SSP → NE555P
text = re.sub(r'([NW]E)\s*S+([PST])', r'\g<1>555\2', text, flags=re.IGNORECASE) # NESSSP → NE555P
text = re.sub(r'([NW]E)\s*5+S+([PST])', r'\g<1>555\2', text, flags=re.IGNORECASE) # NE5SSP → NE555P
text = re.sub(r'([NW]E)\s*[S5]{3,4}([PST])', r'\g<1>555\2', text, flags=re.IGNORECASE) # NE555P with S/5 mix
# Fix LM556 SSS→556 OCR error: LMSSS → LM556, LM5S6 → LM556
text = re.sub(r'([IL]M)\s*[S5]{3}([A-Z])', r'\g<1>556\2', text, flags=re.IGNORECASE) # LMSSS → LM556
text = re.sub(r'([IL]M)\s*[S5][S5][6G]([A-Z])', r'\g<1>556\2', text, flags=re.IGNORECASE) # LM5S6 → LM556
# Fix SN74HC595 OCR errors: S→5, O→0 confusions
text = re.sub(r'([S5]N)74HC[S5]9[S5]', r'\g<1>74HC595', text, flags=re.IGNORECASE) # SN74HCS9S → SN74HC595
text = re.sub(r'([S5]N)74H[CO][S5]9[S5]', r'\g<1>74HC595', text, flags=re.IGNORECASE) # SN74HOS9S → SN74HC595
# Fix common digit/letter confusions
# O → 0 in numbers
text = re.sub(r'([A-Z])O(\d)', r'\g<1>0\2', text) # LO → L0
# J → 3 at start of numbers
text = re.sub(r'J(\d)', r'3\1', text)
text = re.sub(r'^J([s58])', r'3\1', text) # Js8m → 3s8m → 358m
# s → 5 in numbers
text = re.sub(r'(\d)s(\d)', r'\g<1>5\g<2>', text) # 3s8 → 358
# lowercase 'm' or 'rn' at end of numbers often should be 'N'
text = re.sub(r'(\d+)m\b', r'\1N', text, flags=re.IGNORECASE)
text = re.sub(r'(\d+)rn\b', r'\1N', text, flags=re.IGNORECASE)
return text.strip()
def _identify_part_number(self, ocr_results: Dict) -> Dict:
"""Intelligently identify the IC part number with improved prefix combining"""
text = ocr_results['full_text'].upper() # Convert to uppercase
text = re.sub(r'\s+', ' ', text) # Normalize spaces
# IMPROVED: Handle common OCR case errors like "AtMEGA" → "ATMEGA"
text = text.replace('ATMEGA', 'ATMEGA') # Already uppercase
text = text.replace('ATTINY', 'ATTINY') # Already uppercase
# IMPROVED: Try to combine separated prefixes with numbers
# Example: "LM 358N" or "LM" + "358N" or even "LK" + "358N" should become "LM358N"
lines = [line.upper() for line in ocr_results.get('lines', [])] # Ensure all lines uppercase
# Check if we have a prefix and number on separate OCR lines
combined_attempts = []
for i, line1 in enumerate(lines):
line1_upper = line1.upper().strip()
# Check if this is a known prefix OR OCR error version (LK → LM, TI → TL, etc.)
prefix_map = {
'LM': ['LM', 'LK', 'LN', 'IM', 'IK'], # Common OCR errors for LM
'TL': ['TL', 'TI', 'TJ', 'IL'],
'AD': ['AD', 'A0', 'AO'],
'SN': ['SN', 'SM', '5N'],
'MC': ['MC', 'MO', 'NC'],
'LT': ['LT', 'IT', 'LJ'],
'MAX': ['MAX', 'NAX', 'WAX'],
'NE': ['NE', 'NF', 'WE'],
}
for real_prefix, possible_prefixes in prefix_map.items():
for poss_prefix in possible_prefixes:
if line1_upper == poss_prefix or line1_upper.startswith(poss_prefix + ' '):
# Look for numbers in nearby lines
for j in range(max(0, i-2), min(len(lines), i+3)): # Check nearby lines
if i != j:
line2 = lines[j].upper().strip()
# Check if line2 starts with digits
if line2 and line2[0].isdigit():
combined = real_prefix + line2.replace(' ', '')
combined_attempts.append(combined)
logger.info(f" Trying combined: {line1_upper} ({poss_prefix}→{real_prefix}) + {line2} = {combined}")
# Add combined attempts to the text for pattern matching
if combined_attempts:
text = text + ' ' + ' '.join(combined_attempts)
# Try each pattern
best_match = None
best_score = 0
for prefix, pattern in self.ic_patterns.items():
matches = re.findall(pattern, text)
for match in matches:
# Remove spaces from match
match_clean = match.replace(' ', '')
# Score based on length and completeness
score = len(match_clean)
if score > best_score and score >= 2: # LOWERED to 2 - catch very short ICs like "NE555"
best_score = score
best_match = (match_clean, prefix)
if best_match:
part_number = best_match[0]
prefix = best_match[1]
manufacturer = self.mfg_map.get(prefix, 'Unknown')
logger.info(f" ✓ Identified: {part_number} ({manufacturer})")
return {
'part_number': part_number,
'manufacturer': manufacturer,
'prefix': prefix,
'ocr_confidence': ocr_results.get('ocr_confidence', 0)
}
logger.warning(f" ✗ No IC part number found in text: {text[:100]}")
return {
'part_number': None,
'manufacturer': None,
'prefix': None,
'ocr_confidence': ocr_results.get('ocr_confidence', 0)
}
def _validate_url(self, url: str, expect_pdf: bool = False) -> bool:
"""Validate that a URL is accessible and returns valid content (not 404)
Args:
url: URL to validate
expect_pdf: If True, also check that content-type is PDF
Returns:
True if URL is valid and accessible, False otherwise
"""
try:
# Use longer timeout for PDFs (5s) vs product pages (2s)
timeout = 5 if expect_pdf or url.endswith('.pdf') else 2
response = self.session.head(url, timeout=timeout, allow_redirects=True)
# Check status code
if response.status_code != 200:
logger.debug(f" URL validation failed: {response.status_code} - {url}")
return False
# If expecting PDF, check content type
if expect_pdf:
content_type = response.headers.get('Content-Type', '').lower()
if 'pdf' not in content_type and not url.endswith('.pdf'):
logger.debug(f" Not a PDF: {content_type} - {url}")
return False
logger.debug(f" ✓ Valid URL: {url}")
return True
except Exception as e:
logger.debug(f" URL validation error: {e}")
return False
def _find_datasheet(self, part_number: str, manufacturer: str) -> Dict:
"""Use SmartDatasheetFinder to download PDFs and extract marking schemes"""
return self.datasheet_finder.find_datasheet(part_number, manufacturer)
def _extract_marking_from_pdf(self, pdf_path: str) -> Optional[str]:
"""Generic search across multiple manufacturers"""
# Try common patterns
searches = [
self._search_ti,
self._search_microchip,
self._search_infineon,
self._search_analog,
self._search_nxp,
self._search_stm
]
for search_func in searches:
try:
result = search_func(part)
if result and result.get('found'):
return result
except:
continue
return {'found': False}
def _search_microchip(self, part: str) -> Dict:
"""Search Microchip/Atmel datasheets with comprehensive validation
Microchip uses pattern: www.microchip.com/en-us/product/{part-number}
Direct PDF: ww1.microchip.com/downloads/en/DeviceDoc/{part-number}.pdf
"""
base = re.sub(r'[^A-Z0-9-]', '', part).upper()
logger.debug(f" Searching Microchip for: {base}")
# Common Microchip URL patterns to try
urls_to_try = []
# Pattern 1: Direct product page (most reliable)
urls_to_try.append(f"https://www.microchip.com/en-us/product/{base}")
# Pattern 2: For PIC parts specifically
if base.startswith('PIC'):
# PIC16F877A → try PIC16F877A, PIC16F877
urls_to_try.extend([
f"https://www.microchip.com/en-us/product/{base}",
f"https://www.microchip.com/en-us/product/{base[:-1]}" if len(base) > 8 else None,
])
# Pattern 3: For ATMEGA/ATTINY parts
if base.startswith(('ATMEGA', 'ATTINY')):
# ATMEGA328P → atmega328p
urls_to_try.extend([
f"https://www.microchip.com/en-us/product/{base.lower()}",
f"https://www.microchip.com/en-us/product/at{base[2:].lower()}", # ATMEGA328P → atmega328p
])
# Remove None values
urls_to_try = [url for url in urls_to_try if url]
# Try each URL with validation
for url in urls_to_try:
if self._validate_url(url):
logger.debug(f" ✓ Found Microchip datasheet: {url}")
return {'found': True, 'url': url}
# Fallback: Try Digikey/Octopart aggregators
fallback_urls = [
f"https://www.digikey.com/en/products/detail/{base}",
f"https://octopart.com/search?q={base}",
]
for url in fallback_urls:
if self._validate_url(url):
logger.debug(f" ✓ Found via aggregator: {url}")
return {'found': True, 'url': url}
logger.debug(f" ✗ Microchip datasheet not found for {base}")
return {'found': False}
def _search_ti(self, part: str) -> Dict:
"""Search Texas Instruments datasheets with comprehensive validation
TI uses patterns:
- Direct PDF: www.ti.com/lit/ds/symlink/{part}.pdf
- Product page: www.ti.com/product/{part}
"""
base = re.sub(r'[^A-Z0-9]', '', part).upper()
logger.debug(f" Searching TI for: {base}")
# Normalize part number - remove package suffixes
clean = base
if len(base) > 4 and base[-1] in 'NPDMX':
clean = base[:-1]
# Remove multi-letter package suffixes
for suffix in ['CCN', 'CN', 'PW', 'PWR', 'DW', 'DR', 'DGK', 'DBV', 'DCK', 'DGV']:
if clean.endswith(suffix) and len(clean) - len(suffix) >= 3:
clean = clean[:-len(suffix)]
break
urls_to_try = []
# Pattern 1: Direct PDF symlinks (most reliable for TI)
for part_variant in [clean, base]:
urls_to_try.extend([
f"https://www.ti.com/lit/ds/symlink/{part_variant.lower()}.pdf",
f"https://www.ti.com/lit/gpn/{part_variant.lower()}", # General product page
])
# Pattern 2: Product pages
for part_variant in [clean, base]:
urls_to_try.append(f"https://www.ti.com/product/{part_variant.lower()}")
# Pattern 3: For specific TI families
if base.startswith('LM'):
# LM358 → lm358, lm358n
urls_to_try.extend([
f"https://www.ti.com/lit/ds/symlink/{clean.lower()}.pdf",
f"https://www.ti.com/product/{clean}",
])
if base.startswith('SN74'):
# SN74HC595N → sn74hc595
urls_to_try.extend([
f"https://www.ti.com/lit/ds/symlink/{clean.lower()}.pdf",
f"https://www.ti.com/product/{clean}",
])
if base.startswith(('NE', 'SE')):
# NE555 → ne555
urls_to_try.extend([
f"https://www.ti.com/lit/ds/symlink/{base.lower()}.pdf",
f"https://www.ti.com/product/{base}",
])
# For ADC/DAC parts
if base.startswith(('ADC', 'DAC')):
# ADC0831 → adc0831
urls_to_try.extend([
f"https://www.ti.com/lit/ds/symlink/{base.lower()}.pdf",
f"https://www.ti.com/product/{base}",
f"https://www.ti.com/lit/gpn/{base.lower()}",
])
# Try each URL with validation
for url in urls_to_try:
if self._validate_url(url):
logger.debug(f" ✓ Found TI datasheet: {url}")
return {'found': True, 'url': url}
# Fallback: Try aggregators
fallback_urls = [
f"https://www.ti.com/product/{clean}", # Try one more time with clean part
f"https://www.digikey.com/en/products/detail/{base}",
f"https://octopart.com/search?q={base}",
]
for url in fallback_urls:
if self._validate_url(url):
logger.debug(f" ✓ Found via aggregator: {url}")
return {'found': True, 'url': url}
logger.debug(f" ✗ TI datasheet not found for {base}")
return {'found': False}
def _search_infineon(self, part: str) -> Dict:
"""Search Infineon/Cypress datasheets with comprehensive validation
Infineon uses pattern: www.infineon.com/cms/en/product/{part}/
Cypress (now Infineon) parts need special handling
"""
base = re.sub(r'[^A-Z0-9-]', '', part).upper()
logger.debug(f" Searching Infineon for: {base}")
urls_to_try = []
# For CY8C/CY7C (Cypress PSoC chips)
if base.startswith(('CY8C', 'CY7C')):
# Remove package suffix (CY8C29666-24PVXI → CY8C29666)
base_clean = re.sub(r'-\d+[A-Z]+$', '', base)
urls_to_try.extend([
f"https://www.infineon.com/cms/en/product/{base_clean.lower()}/",
f"https://www.infineon.com/cms/en/product/{base.lower()}/",
f"https://www.infineon.com/dgdl/Infineon-{base_clean}-DataSheet-v01_00-EN.pdf",
])
else:
# Standard Infineon parts
urls_to_try.extend([
f"https://www.infineon.com/cms/en/product/{base.lower()}/",
f"https://www.infineon.com/cms/en/product/{base}/",
])
# Try each URL with validation
for url in urls_to_try:
if self._validate_url(url):
logger.debug(f" ✓ Found Infineon datasheet: {url}")
return {'found': True, 'url': url}
# Fallback: Try aggregators
fallback_urls = [
f"https://www.digikey.com/en/products/detail/{base}",
f"https://octopart.com/search?q={base}",
]
for url in fallback_urls:
if self._validate_url(url):
logger.debug(f" ✓ Found via aggregator: {url}")
return {'found': True, 'url': url}
logger.debug(f" ✗ Infineon datasheet not found for {base}")
return {'found': False}
def _search_stm(self, part: str) -> Dict:
"""Search STMicroelectronics datasheets with comprehensive validation
STM parts include STM32 microcontrollers and M74HC logic ICs
"""
base = re.sub(r'[^A-Z0-9]', '', part).upper()
logger.debug(f" Searching STM for: {base}")
urls_to_try = []
# For STM32 parts
if base.startswith('STM32'):
urls_to_try.extend([
f"https://www.st.com/en/microcontrollers-microprocessors/stm32-32-bit-arm-cortex-mcus.html#{base.lower()}",
f"https://www.st.com/en/microcontrollers/{base.lower()}.html",
])
# For M74HC series (logic ICs)
if base.startswith(('M74HC', 'M74HCT')):
# Remove package suffix
clean = base
for suffix in ['B1', 'TTR', 'M1', 'N', 'RM13TR']:
if clean.endswith(suffix):
clean = clean[:-len(suffix)]
break
urls_to_try.extend([
f"https://www.st.com/en/logic-comparators/{base.lower()}.html",
f"https://www.st.com/en/logic-comparators/{clean.lower()}.html",
])
# Try each URL with validation
for url in urls_to_try:
if self._validate_url(url):
logger.debug(f" ✓ Found STM datasheet: {url}")
return {'found': True, 'url': url}
# Fallback: Try aggregators
fallback_urls = [
f"https://www.digikey.com/en/products/detail/{base}",
f"https://octopart.com/search?q={base}",
]
for url in fallback_urls:
if self._validate_url(url):
logger.debug(f" ✓ Found via aggregator: {url}")
return {'found': True, 'url': url}
logger.debug(f" ✗ STM datasheet not found for {base}")
return {'found': False}
def _search_nxp(self, part: str) -> Dict:
"""Search NXP datasheets with comprehensive validation"""
base = re.sub(r'[^A-Z0-9]', '', part).upper()
logger.debug(f" Searching NXP for: {base}")
urls_to_try = [
f"https://www.nxp.com/products/{base.lower()}",
f"https://www.nxp.com/docs/en/data-sheet/{base}.pdf",
]
# Try each URL with validation
for url in urls_to_try:
if self._validate_url(url):
logger.debug(f" ✓ Found NXP datasheet: {url}")
return {'found': True, 'url': url}
# Fallback: Try aggregators
fallback_urls = [
f"https://www.digikey.com/en/products/detail/{base}",
f"https://octopart.com/search?q={base}",
]
for url in fallback_urls:
if self._validate_url(url):
logger.debug(f" ✓ Found via aggregator: {url}")
return {'found': True, 'url': url}
logger.debug(f" ✗ NXP datasheet not found for {base}")
return {'found': False}
def _search_analog(self, part: str) -> Dict:
"""Search Analog Devices datasheets with comprehensive validation
Note: analog.com is often very slow (5s+ response times), so we prioritize
fast aggregators like Octopart first, then try analog.com if needed.
"""
base = re.sub(r'[^A-Z0-9-]', '', part).upper()
logger.debug(f" Searching Analog Devices for: {base}")
# Try fast aggregators first (analog.com is extremely slow)
fast_urls = [
f"https://octopart.com/search?q={base}",
f"https://www.digikey.com/en/products/detail/{base}",
]