Runs OCR (TrOCR) and ensures only meaningful text is considered.
(image)
| 736 | |
| 737 | |
| 738 | def detect_text(image): |
| 739 | """Runs OCR (TrOCR) and ensures only meaningful text is considered.""" |
| 740 | # Preprocess image for better OCR accuracy |
| 741 | preprocessed_img = enhance_image_for_ocr(image) |
| 742 | |
| 743 | # Convert to PIL Image for TrOCR processing |
| 744 | pil_image = Image.fromarray(preprocessed_img).convert("RGB") |
| 745 | |
| 746 | # Get pixel values for model input |
| 747 | pixel_values = processor_handwritten(images=pil_image, return_tensors="pt").pixel_values.to(device) |
| 748 | |
| 749 | # Perform OCR prediction |
| 750 | generated_ids = model_handwritten.generate(pixel_values) |
| 751 | transcription = processor_handwritten.decode(generated_ids[0], skip_special_tokens=True).strip() |
| 752 | |
| 753 | # Apply filtering: Ignore results if text length is too short or contains mostly non-alphanumeric characters |
| 754 | if len(transcription) < 3 or sum(c.isalnum() for c in transcription) / len(transcription) < 0.5: |
| 755 | return False, "" # Ignore if it's too short or mostly symbols |
| 756 | |
| 757 | return True, transcription |
| 758 | |
| 759 | |
| 760 | # I think the above line is making it to where there is going to save all the file variations |
no test coverage detected