""" Lemontropia Suite - OCR Backend Test Script Tests all OCR backends and reports on availability. Run this to verify the OCR system works without PyTorch DLL errors. """ import sys import logging from pathlib import Path # Setup logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def test_hardware_detection(): """Test hardware detection.""" print("\n" + "=" * 60) print("HARDWARE DETECTION TEST") print("=" * 60) try: from modules.hardware_detection import ( HardwareDetector, print_hardware_summary, recommend_ocr_backend ) # Print summary print_hardware_summary() # Get detailed info info = HardwareDetector.detect_all() # Check for Windows Store Python if info.is_windows_store_python: print("\n⚠️ WARNING: Windows Store Python detected!") print(" This may cause DLL compatibility issues with PyTorch.") # Check for PyTorch DLL errors if info.pytorch_dll_error: print("\n❌ PyTorch DLL Error detected!") print(f" Error: {info.pytorch_error}") print("\n This is expected with Windows Store Python.") print(" The system will automatically use alternative OCR backends.") elif not info.pytorch_available: print("\n⚠️ PyTorch not installed.") else: print(f"\n✅ PyTorch {info.pytorch_version} available") # Recommendation recommended = recommend_ocr_backend() print(f"\n📋 Recommended OCR backend: {recommended}") return True except Exception as e: print(f"❌ Hardware detection failed: {e}") import traceback traceback.print_exc() return False def test_ocr_backends(): """Test all OCR backends.""" print("\n" + "=" * 60) print("OCR BACKEND TESTS") print("=" * 60) try: from modules.ocr_backends import OCRBackendFactory # Check all backends backends = OCRBackendFactory.check_all_backends(use_gpu=True) available_count = 0 for info in backends: status = "✅ Available" if info.available else "❌ Not Available" gpu_status = "🚀 GPU" if info.gpu_accelerated else "💻 CPU" print(f"\n{info.name.upper()}:") print(f" Status: {status}") print(f" GPU: {gpu_status}") if info.version: print(f" Version: {info.version}") if info.error_message: print(f" Error: {info.error_message}") if info.available: available_count += 1 print(f"\n📊 Summary: {available_count}/{len(backends)} backends available") return available_count > 0 except Exception as e: print(f"❌ OCR backend test failed: {e}") import traceback traceback.print_exc() return False def test_opencv_east(): """Test OpenCV EAST backend specifically (should always work).""" print("\n" + "=" * 60) print("OPENCV EAST BACKEND TEST") print("=" * 60) try: import numpy as np from modules.ocr_backends import OCRBackendFactory # Create test image with text-like regions print("\nCreating test image...") test_image = np.ones((400, 600, 3), dtype=np.uint8) * 255 # Draw some rectangles that look like text regions import cv2 cv2.rectangle(test_image, (50, 50), (200, 80), (0, 0, 0), -1) cv2.rectangle(test_image, (50, 100), (250, 130), (0, 0, 0), -1) cv2.rectangle(test_image, (300, 50), (500, 90), (0, 0, 0), -1) # Create backend print("Creating OpenCV EAST backend...") backend = OCRBackendFactory.create_backend('opencv_east', use_gpu=False) if backend is None: print("❌ Failed to create OpenCV EAST backend") return False print(f"✅ Backend created: {backend.get_info().name}") print(f" Available: {backend.is_available()}") print(f" GPU: {backend.get_info().gpu_accelerated}") # Test detection print("\nRunning text detection...") regions = backend.extract_text(test_image) print(f"✅ Detection complete: {len(regions)} regions found") for i, region in enumerate(regions[:5]): # Show first 5 x, y, w, h = region.bbox print(f" Region {i+1}: bbox=({x},{y},{w},{h}), conf={region.confidence:.2f}") return True except Exception as e: print(f"❌ OpenCV EAST test failed: {e}") import traceback traceback.print_exc() return False def test_unified_ocr(): """Test unified OCR processor.""" print("\n" + "=" * 60) print("UNIFIED OCR PROCESSOR TEST") print("=" * 60) try: import numpy as np import cv2 from modules.game_vision_ai import UnifiedOCRProcessor # Create processor (auto-selects best backend) print("\nInitializing Unified OCR Processor...") processor = UnifiedOCRProcessor(use_gpu=True, auto_select=True) backend_name = processor.get_current_backend() print(f"✅ Processor initialized with backend: {backend_name}") # Get backend info info = processor.get_backend_info() print(f" Info: {info}") # Create test image print("\nCreating test image...") test_image = np.ones((400, 600, 3), dtype=np.uint8) * 255 cv2.rectangle(test_image, (50, 50), (200, 80), (0, 0, 0), -1) cv2.rectangle(test_image, (50, 100), (250, 130), (0, 0, 0), -1) # Test extraction print("\nRunning text extraction...") regions = processor.extract_text(test_image) print(f"✅ Extraction complete: {len(regions)} regions found") # List all available backends print("\n📋 All OCR backends:") for backend_info in processor.get_available_backends(): status = "✅" if backend_info.available else "❌" print(f" {status} {backend_info.name}") return True except Exception as e: print(f"❌ Unified OCR test failed: {e}") import traceback traceback.print_exc() return False def test_game_vision_ai(): """Test GameVisionAI class.""" print("\n" + "=" * 60) print("GAME VISION AI TEST") print("=" * 60) try: from modules.game_vision_ai import GameVisionAI print("\nInitializing GameVisionAI...") vision = GameVisionAI(use_gpu=True) print(f"✅ GameVisionAI initialized") print(f" OCR Backend: {vision.ocr.get_current_backend()}") print(f" GPU Backend: {vision.backend.value}") # Get diagnostic info print("\nRunning diagnostics...") diag = GameVisionAI.diagnose() print(f" Hardware: {diag['hardware']['gpu']['backend']}") print(f" Recommended OCR: {diag['recommendations']['ocr_backend']}") # Test available backends backends = vision.get_ocr_backends() available = [b['name'] for b in backends if b['available']] print(f" Available backends: {', '.join(available) if available else 'None'}") return True except Exception as e: print(f"❌ GameVisionAI test failed: {e}") import traceback traceback.print_exc() return False def test_pytorch_dll_handling(): """Test that PyTorch DLL errors are handled gracefully.""" print("\n" + "=" * 60) print("PYTORCH DLL ERROR HANDLING TEST") print("=" * 60) try: from modules.hardware_detection import HardwareDetector info = HardwareDetector.detect_all() if info.pytorch_dll_error: print("\n⚠️ PyTorch DLL error detected (as expected with Windows Store Python)") print("✅ System correctly detected the DLL error") print("✅ System will use fallback OCR backends") # Verify fallback recommendation recommended = HardwareDetector.recommend_ocr_backend() if recommended in ['opencv_east', 'tesseract']: print(f"✅ Recommended safe backend: {recommended}") return True else: print(f"⚠️ Unexpected recommendation: {recommended}") return False else: print("\n✅ No PyTorch DLL error detected") print(" PyTorch is working correctly!") if info.pytorch_available: print(f" Version: {info.pytorch_version}") return True except Exception as e: print(f"❌ DLL handling test failed: {e}") import traceback traceback.print_exc() return False def main(): """Run all tests.""" print("\n" + "=" * 60) print("LEMONTROPIA SUITE - OCR SYSTEM TEST") print("=" * 60) print("\nPython:", sys.version) print("Platform:", sys.platform) results = {} # Run tests results['hardware'] = test_hardware_detection() results['backends'] = test_ocr_backends() results['opencv_east'] = test_opencv_east() results['unified_ocr'] = test_unified_ocr() results['game_vision'] = test_game_vision_ai() results['dll_handling'] = test_pytorch_dll_handling() # Summary print("\n" + "=" * 60) print("TEST SUMMARY") print("=" * 60) for name, passed in results.items(): status = "✅ PASS" if passed else "❌ FAIL" print(f" {status}: {name}") total = len(results) passed = sum(results.values()) print(f"\n Total: {passed}/{total} tests passed") if passed == total: print("\n🎉 All tests passed! OCR system is working correctly.") return 0 else: print("\n⚠️ Some tests failed. Check the output above for details.") return 1 if __name__ == "__main__": sys.exit(main())