File size: 9,579 Bytes
b0cc1ff
8999815
 
 
 
b0cc1ff
760fccf
 
 
8999815
760fccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8999815
760fccf
 
8999815
 
760fccf
 
 
8999815
760fccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8999815
760fccf
 
 
8999815
 
760fccf
 
 
8999815
760fccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8999815
760fccf
8999815
760fccf
 
 
 
 
 
8999815
760fccf
 
 
 
 
 
8999815
760fccf
 
 
 
 
 
8999815
 
760fccf
 
 
8999815
760fccf
8999815
760fccf
 
8999815
760fccf
 
 
8999815
760fccf
 
 
 
 
 
 
8999815
760fccf
 
 
 
 
 
 
8999815
760fccf
 
8999815
 
760fccf
 
 
8999815
760fccf
 
 
 
 
 
 
 
 
 
8999815
760fccf
8999815
760fccf
 
 
 
 
 
8999815
760fccf
 
 
 
8999815
760fccf
 
8999815
 
760fccf
 
 
8999815
760fccf
 
8999815
760fccf
 
 
 
 
8999815
760fccf
 
8999815
760fccf
 
8999815
760fccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from gradio_client import Client, handle_file
from PIL import Image
import base64
import io
import os

# def test_base64_api(client_url="http://localhost:7860"):
#     """Test the base64 API endpoint"""
#     print("πŸ§ͺ Testing Base64 API Endpoint...")
    
#     try:
#         # Initialize the client
#         client = Client(client_url)
        
#         # Check if temp_drawing.png exists, if not create a simple test image
#         if not os.path.exists("temp_drawing.png"):
#             print("Creating a test image...")
#             # Create a simple test image (white background with black circle)
#             img = Image.new('RGB', (400, 400), 'white')
#             from PIL import ImageDraw
#             draw = ImageDraw.Draw(img)
#             draw.ellipse([150, 150, 250, 250], fill='black')
#             img.save("temp_drawing.png")
        
#         # Load the image
#         image = Image.open("temp_drawing.png")
#         print(f"βœ“ Loaded image: {image.size}")
        
#         # Convert image to base64
#         buffered = io.BytesIO()
#         image.save(buffered, format="PNG")
#         img_str = base64.b64encode(buffered.getvalue()).decode()
#         print(f"βœ“ Converted to base64 (length: {len(img_str)})")
        
#         # Call the API endpoint with correct parameter names
#         result = client.predict(
#             image_data=img_str,
#             top_k=5,
#             api_name="/classify_image_api"
#         )
        
#         print("βœ“ API Response:")
#         print(f"  Success: {result.get('success', False)}")
#         if result.get('success'):
#             print("  Predictions:")
#             for i, pred in enumerate(result.get('predictions', []), 1):
#                 print(f"    {i}. {pred['category']} - {pred['confidence']:.3f}")
#         else:
#             print(f"  Error: {result.get('error', 'Unknown error')}")
            
#     except Exception as e:
#         print(f"❌ Base64 API test failed: {str(e)}")


# def test_main_interface(client_url="http://localhost:7860"):
#     """Test the main drawing interface"""
#     print("\nπŸ§ͺ Testing Main Drawing Interface...")
    
#     try:
#         # Initialize the client
#         client = Client(client_url)
        
#         # Check if temp_drawing.png exists
#         if not os.path.exists("temp_drawing.png"):
#             print("Creating a test image...")
#             # Create a simple test image (white background with black circle)
#             img = Image.new('RGB', (400, 400), 'white')
#             from PIL import ImageDraw
#             draw = ImageDraw.Draw(img)
#             draw.ellipse([150, 150, 250, 250], fill='black')
#             img.save("temp_drawing.png")
        
#         # Load and convert image to the format expected by Sketchpad
#         image = Image.open("temp_drawing.png")
        
#         # Create a mock sketchpad data structure
#         sketchpad_data = {
#             "background": image,
#             "layers": [image],
#             "composite": image
#         }
        
#         # Test the main gradio_classify function
#         result = client.predict(
#             canvas=sketchpad_data,
#             api_name="/gradio_classify"
#         )
        
#         print("βœ“ Main Interface Response:")
#         print(result)
            
#     except Exception as e:
#         print(f"❌ Main interface test failed: {str(e)}")
#         print("πŸ’‘ Try using the web interface directly instead")


# def test_huggingface_space():
#     """Test the deployed Hugging Face space"""
#     print("\nπŸ§ͺ Testing Hugging Face Space...")
    
#     try:
#         # Test your deployed space
#         client = Client("souvikg544/quickdraw-classifier")
        
#         # Check if temp_drawing.png exists
#         if not os.path.exists("temp_drawing.png"):
#             print("Creating a test image...")
#             img = Image.new('RGB', (400, 400), 'white')
#             from PIL import ImageDraw
#             draw = ImageDraw.Draw(img)
#             draw.ellipse([150, 150, 250, 250], fill='black')
#             img.save("temp_drawing.png")
        
#         # Load and convert image to the format expected by Sketchpad
#         image = Image.open("temp_drawing.png")
        
#         # Create a mock sketchpad data structure
#         sketchpad_data = {
#             "background": image,
#             "layers": [image], 
#             "composite": image
#         }
        
#         # Test with sketchpad format
#         result = client.predict(
#             canvas=sketchpad_data,
#             api_name="/gradio_classify"
#         )
        
#         print("βœ“ Hugging Face Space Response:")
#         print(result)
        
#     except Exception as e:
#         print(f"❌ Hugging Face space test failed: {str(e)}")


# def create_test_drawings():
#     """Create various test drawings for testing"""
#     print("\n🎨 Creating test drawings...")
    
#     from PIL import ImageDraw
    
#     # Test drawing 1: Circle (might be classified as sun, moon, etc.)
#     img1 = Image.new('RGB', (400, 400), 'white')
#     draw1 = ImageDraw.Draw(img1)
#     draw1.ellipse([150, 150, 250, 250], fill='black')
#     img1.save("test_circle.png")
#     print("βœ“ Created test_circle.png")
    
#     # Test drawing 2: Rectangle (might be classified as house, car, etc.)
#     img2 = Image.new('RGB', (400, 400), 'white')
#     draw2 = ImageDraw.Draw(img2)
#     draw2.rectangle([100, 150, 300, 250], fill='black')
#     img2.save("test_rectangle.png")
#     print("βœ“ Created test_rectangle.png")
    
#     # Test drawing 3: Triangle (might be classified as tree, mountain, etc.)
#     img3 = Image.new('RGB', (400, 400), 'white')
#     draw3 = ImageDraw.Draw(img3)
#     draw3.polygon([(200, 100), (150, 200), (250, 200)], fill='black')
#     img3.save("test_triangle.png")
#     print("βœ“ Created test_triangle.png")


# def test_multiple_drawings():
#     """Test classification with multiple different drawings"""
#     print("\nπŸ§ͺ Testing Multiple Drawings...")
    
#     test_files = ["test_circle.png", "test_rectangle.png", "test_triangle.png"]
    
#     try:
#         client = Client("http://localhost:7860")
        
#         for test_file in test_files:
#             if os.path.exists(test_file):
#                 print(f"\n--- Testing {test_file} ---")
                
#                 # Load image and create sketchpad format
#                 image = Image.open(test_file)
#                 sketchpad_data = {
#                     "background": image,
#                     "layers": [image],
#                     "composite": image
#                 }
                
#                 result = client.predict(
#                     canvas=sketchpad_data,
#                     api_name="/gradio_classify"
#                 )
#                 print(result)
#             else:
#                 print(f"❌ {test_file} not found")
                
#     except Exception as e:
#         print(f"❌ Multiple drawings test failed: {str(e)}")


# def test_base64_with_file():
#     """Test base64 API with actual file conversion"""
#     print("\nπŸ§ͺ Testing Base64 API with File Conversion...")
    
#     try:
#         client = Client("http://localhost:7860")
        
#         # Use one of our test files
#         test_file = "test_circle.png"
#         if os.path.exists(test_file):
#             # Load and convert to base64
#             with open(test_file, "rb") as f:
#                 img_bytes = f.read()
#                 img_b64 = base64.b64encode(img_bytes).decode()
            
#             print(f"βœ“ Converted {test_file} to base64")
            
#             # Test the base64 API with correct parameter names
#             result = client.predict(
#                 image_data=img_b64,
#                 top_k=5,
#                 api_name="/classify_image_api"
#             )
            
#             print("βœ“ Base64 API Response:")
#             print(result)
#         else:
#             print("❌ No test file found for base64 testing")
            
#     except Exception as e:
#         print(f"❌ Base64 file test failed: {str(e)}")


# if __name__ == "__main__":
#     print("πŸš€ QuickDraw Classifier API Test Suite")
#     print("=" * 50)
    
#     # Create test drawings first
#     create_test_drawings()
    
#     # Test local server (make sure your app is running on localhost:7860)
#     print("\nπŸ“ Testing Local Server...")
#     test_base64_api("http://localhost:7860")
#     test_main_interface("http://localhost:7860")
#     test_multiple_drawings()
    
#     # Test Hugging Face deployment
#     test_huggingface_space()
    
#     # Test base64 API with file conversion
#     test_base64_with_file()
    
#     print("\nβœ… Test suite completed!")
#     print("\nπŸ’‘ Tips:")
#     print("- Make sure your local server is running: python app.py")
#     print("- For HF Space testing, ensure your space is public and running")
#     print("- Check the generated test images: test_circle.png, test_rectangle.png, test_triangle.png")


from gradio_client import Client

image = Image.open("temp_drawing.png")
buffered = io.BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()

# client = Client("souvikg544/quickdraw-classifier")
client = Client("https://6820c804655322f295.gradio.live/")
result = client.predict(
		image_data=img_str,
		top_k=5,
        word="broom",
		api_name="/classify_image_api"
)
print(result)