File size: 6,898 Bytes
719e71f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Quick test script to verify the colorspace demo setup
"""

import sys

def test_imports():
    """Test that all required packages can be imported."""
    print("πŸ§ͺ Testing package imports...")
    
    packages = [
        ('numpy', 'NumPy'),
        ('cv2', 'OpenCV'),
        ('streamlit', 'Streamlit'),
        ('PIL', 'Pillow'),
        ('matplotlib', 'Matplotlib'),
        ('colorsys', 'colorsys'),
    ]
    
    failed = []
    for module, name in packages:
        try:
            __import__(module)
            print(f"  βœ… {name}")
        except ImportError as e:
            print(f"  ❌ {name}: {e}")
            failed.append(name)
    
    return len(failed) == 0, failed


def test_app_structure():
    """Test that app.py has the expected structure."""
    print("\nπŸ“ Testing app structure...")
    
    try:
        import app
        
        # Check for key functions
        functions = [
            'load_image',
            'get_available_images',
            'tab_rgb',
            'tab_hsv',
            'tab_lab',
            'tab_cmyk',
            'tab_ycbcr',
            'tab_gamma_wb',
            'tab_colorblind',
            'simulate_colorblindness',
            'main',
        ]
        
        failed = []
        for func in functions:
            if hasattr(app, func):
                print(f"  βœ… Function '{func}' found")
            else:
                print(f"  ❌ Function '{func}' missing")
                failed.append(func)
        
        return len(failed) == 0, failed
    
    except Exception as e:
        print(f"  ❌ Error loading app: {e}")
        import traceback
        traceback.print_exc()
        return False, [str(e)]


def test_colorspace_conversions():
    """Test basic colorspace conversion functions."""
    print("\n🌈 Testing colorspace conversions...")
    
    try:
        import numpy as np
        import cv2
        
        # Create a simple RGB image
        test_img = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], dtype=np.uint8)
        
        # Test RGB to HSV
        hsv_img = cv2.cvtColor(test_img, cv2.COLOR_RGB2HSV)
        print(f"  βœ… RGB to HSV conversion works")
        
        # Test RGB to LAB
        lab_img = cv2.cvtColor(test_img, cv2.COLOR_RGB2LAB)
        print(f"  βœ… RGB to LAB conversion works")
        
        # Test RGB to YCrCb
        ycrcb_img = cv2.cvtColor(test_img, cv2.COLOR_RGB2YCrCb)
        print(f"  βœ… RGB to YCrCb conversion works")
        
        # Test gamma correction
        img_float = test_img.astype(np.float32) / 255.0
        gamma = 2.2
        img_gamma = np.power(img_float, gamma)
        img_gamma = (img_gamma * 255).astype(np.uint8)
        print(f"  βœ… Gamma correction works")
        
        return True, []
    
    except Exception as e:
        print(f"  ❌ Error: {e}")
        import traceback
        traceback.print_exc()
        return False, [str(e)]


def test_colorblindness_simulation():
    """Test color blindness simulation."""
    print("\nπŸ‘οΈ  Testing color blindness simulation...")
    
    try:
        import app
        import numpy as np
        
        # Create a simple test image
        test_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)
        
        # Test different types
        types = [
            "Normal Vision",
            "Protanopia (No Red)",
            "Deuteranopia (No Green)",
            "Tritanopia (No Blue)",
            "Monochromacy (Grayscale)"
        ]
        
        for cb_type in types:
            result = app.simulate_colorblindness(test_img, cb_type)
            assert result.shape == test_img.shape, f"Shape mismatch for {cb_type}"
            print(f"  βœ… {cb_type}")
        
        return True, []
    
    except Exception as e:
        print(f"  ❌ Error: {e}")
        import traceback
        traceback.print_exc()
        return False, [str(e)]


def test_image_loading():
    """Test that images can be loaded from the images folder."""
    print("\nπŸ–ΌοΈ  Testing image loading...")
    
    try:
        from pathlib import Path
        import app
        
        # Check if images folder exists
        images_dir = Path("images")
        if not images_dir.exists():
            print("  ⚠️  images/ folder not found (this is OK for fresh setup)")
            return True, []
        
        # Get available images
        images = app.get_available_images()
        if images:
            print(f"  βœ… Found {len(images)} images in images/ folder")
            
            # Try to load one
            img = app.load_image(images[0])
            if img is not None:
                print(f"  βœ… Successfully loaded '{images[0]}'")
            else:
                print(f"  ⚠️  Could not load '{images[0]}' (may be corrupted)")
        else:
            print("  ⚠️  No images found in images/ folder (this is OK for fresh setup)")
        
        return True, []
    
    except Exception as e:
        print(f"  ❌ Error: {e}")
        import traceback
        traceback.print_exc()
        return False, [str(e)]


def main():
    """Run all tests."""
    print("=" * 60)
    print("🎨 Colorspace Explorer - Test Suite")
    print("=" * 60)
    
    all_passed = True
    
    # Test 1: Imports
    passed, failed = test_imports()
    if not passed:
        print(f"\n❌ Import test failed. Missing packages: {', '.join(failed)}")
        print("\nπŸ’‘ Run: pip install -r requirements.txt")
        all_passed = False
    
    # Test 2: App structure
    if passed:  # Only run if imports work
        passed, failed = test_app_structure()
        if not passed:
            print(f"\n❌ App structure test failed.")
            all_passed = False
    
    # Test 3: Colorspace conversions
    if passed:
        passed, failed = test_colorspace_conversions()
        if not passed:
            print(f"\n❌ Colorspace conversion test failed.")
            all_passed = False
    
    # Test 4: Color blindness simulation
    if passed:
        passed, failed = test_colorblindness_simulation()
        if not passed:
            print(f"\n❌ Color blindness simulation test failed.")
            all_passed = False
    
    # Test 5: Image loading
    if passed:
        passed, failed = test_image_loading()
        if not passed:
            print(f"\n❌ Image loading test failed.")
            all_passed = False
    
    # Summary
    print("\n" + "=" * 60)
    if all_passed:
        print("βœ… All tests passed! Ready to run the demo.")
        print("\nπŸš€ Start with:")
        print("   ./run.sh")
        print("   Or: make run")
        print("   Or: streamlit run app.py")
        return 0
    else:
        print("❌ Some tests failed. Please fix the issues above.")
        return 1


if __name__ == "__main__":
    sys.exit(main())