captchakings 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ """
2
+ CaptchaKings Python Library
3
+
4
+ Simple and powerful Python client for CaptchaKings API.
5
+
6
+ Example:
7
+ >>> from captchakings import CaptchaKings
8
+ >>> client = CaptchaKings('ck_your_api_key')
9
+ >>> result = client.solve('captcha.jpg')
10
+ >>> print(result['prediction'])
11
+ """
12
+
13
+ __version__ = '1.0.0'
14
+ __author__ = 'CaptchaKings'
15
+ __license__ = 'MIT'
16
+
17
+ from .client import CaptchaKings
18
+ from .exceptions import (
19
+ CaptchaKingsException,
20
+ APIError,
21
+ AuthenticationError,
22
+ InsufficientCreditsError,
23
+ InvalidImageError,
24
+ TimeoutError,
25
+ NetworkError
26
+ )
27
+
28
+ __all__ = [
29
+ 'CaptchaKings',
30
+ 'CaptchaKingsException',
31
+ 'APIError',
32
+ 'AuthenticationError',
33
+ 'InsufficientCreditsError',
34
+ 'InvalidImageError',
35
+ 'TimeoutError',
36
+ 'NetworkError'
37
+ ]
captchakings/client.py ADDED
@@ -0,0 +1,189 @@
1
+ """
2
+ CaptchaKings API Client
3
+ """
4
+
5
+ import requests
6
+ import os
7
+ import time
8
+ from typing import Dict, Optional, Union
9
+ from .exceptions import (
10
+ APIError,
11
+ AuthenticationError,
12
+ InsufficientCreditsError,
13
+ InvalidImageError,
14
+ TimeoutError as CKTimeoutError,
15
+ NetworkError
16
+ )
17
+
18
+ class CaptchaKings:
19
+ """
20
+ CaptchaKings API Client
21
+
22
+ Simple and powerful Python client for CaptchaKings API.
23
+
24
+ Example:
25
+ >>> from captchakings import CaptchaKings
26
+ >>> client = CaptchaKings('ck_your_api_key')
27
+ >>> result = client.solve('captcha.jpg')
28
+ >>> print(result['prediction'])
29
+ """
30
+
31
+ def __init__(self, api_key: str, base_url: str = 'https://captchakings.com/api/process.php'):
32
+ """
33
+ Initialize CaptchaKings client
34
+
35
+ Args:
36
+ api_key: Your CaptchaKings API key
37
+ base_url: API endpoint URL (default: official API)
38
+ """
39
+ if not api_key:
40
+ raise ValueError("API key is required")
41
+
42
+ self.api_key = api_key
43
+ self.base_url = base_url
44
+ self._session = requests.Session()
45
+ self._session.headers.update({
46
+ 'Authorization': f'Bearer {api_key}'
47
+ })
48
+
49
+ def solve(self, image_path: str, timeout: int = 30) -> Dict:
50
+ """
51
+ Solve CAPTCHA from image file
52
+
53
+ Args:
54
+ image_path: Path to CAPTCHA image file
55
+ timeout: Request timeout in seconds (default: 30)
56
+
57
+ Returns:
58
+ dict: Response with prediction and credits info
59
+
60
+ Raises:
61
+ InvalidImageError: If image file not found or invalid
62
+ AuthenticationError: If API key is invalid
63
+ InsufficientCreditsError: If not enough credits
64
+ APIError: For other API errors
65
+
66
+ Example:
67
+ >>> result = client.solve('captcha.jpg')
68
+ >>> print(f"Solved: {result['prediction']}")
69
+ >>> print(f"Credits: {result['credits_remaining']}")
70
+ """
71
+ if not os.path.exists(image_path):
72
+ raise InvalidImageError(f"Image file not found: {image_path}")
73
+
74
+ try:
75
+ with open(image_path, 'rb') as f:
76
+ files = {
77
+ 'captcha': ('captcha.jpg', f, 'image/jpeg')
78
+ }
79
+
80
+ response = self._session.post(
81
+ self.base_url,
82
+ files=files,
83
+ timeout=timeout
84
+ )
85
+
86
+ data = response.json()
87
+
88
+ if response.status_code == 200 and data.get('success'):
89
+ return {
90
+ 'prediction': data['data']['prediction'],
91
+ 'confidence': data['data']['confidence'],
92
+ 'process_time': data['data']['process_time'],
93
+ 'credits_deducted': data['credits']['credits_deducted'],
94
+ 'credits_remaining': data['credits']['credits_remaining'],
95
+ 'plan': data['credits']['plan']
96
+ }
97
+ else:
98
+ self._handle_error(response.status_code, data)
99
+
100
+ except requests.exceptions.Timeout:
101
+ raise CKTimeoutError(f"Request timeout after {timeout} seconds")
102
+ except requests.exceptions.ConnectionError as e:
103
+ raise NetworkError(f"Connection error: {str(e)}")
104
+ except requests.exceptions.RequestException as e:
105
+ raise APIError(f"Request error: {str(e)}")
106
+ except (ValueError, KeyError) as e:
107
+ raise APIError(f"Invalid response format: {str(e)}")
108
+ except IOError as e:
109
+ raise InvalidImageError(f"Error reading image file: {str(e)}")
110
+
111
+ def solve_with_retry(self, image_path: str, max_retries: int = 3,
112
+ retry_delay: int = 2, timeout: int = 30) -> Dict:
113
+ """
114
+ Solve CAPTCHA with automatic retry on failure
115
+
116
+ Args:
117
+ image_path: Path to CAPTCHA image file
118
+ max_retries: Maximum number of retry attempts (default: 3)
119
+ retry_delay: Delay between retries in seconds (default: 2)
120
+ timeout: Request timeout in seconds (default: 30)
121
+
122
+ Returns:
123
+ dict: Response with prediction and credits info
124
+
125
+ Raises:
126
+ Same as solve() method
127
+
128
+ Example:
129
+ >>> result = client.solve_with_retry('captcha.jpg', max_retries=5)
130
+ """
131
+ last_error = None
132
+
133
+ for attempt in range(max_retries):
134
+ try:
135
+ return self.solve(image_path, timeout)
136
+ except (AuthenticationError, InsufficientCreditsError, InvalidImageError):
137
+ raise
138
+ except Exception as e:
139
+ last_error = e
140
+ if attempt < max_retries - 1:
141
+ time.sleep(retry_delay)
142
+
143
+ raise last_error
144
+
145
+ def get_balance(self) -> Dict:
146
+ """
147
+ Get account balance and plan information
148
+
149
+ Returns:
150
+ dict: Balance information
151
+
152
+ Note:
153
+ This method sends a test request to get balance info
154
+ """
155
+ test_image_path = os.path.join(os.path.dirname(__file__), 'test.jpg')
156
+
157
+ try:
158
+ result = self.solve(test_image_path)
159
+ return {
160
+ 'credits_remaining': result['credits_remaining'],
161
+ 'plan': result['plan']
162
+ }
163
+ except Exception:
164
+ raise APIError("Could not retrieve balance information")
165
+
166
+ def _handle_error(self, status_code: int, data: Dict):
167
+ """Handle API error responses"""
168
+ error_msg = data.get('error', 'Unknown error')
169
+
170
+ if status_code == 401 or 'Invalid API key' in error_msg:
171
+ raise AuthenticationError(error_msg)
172
+ elif status_code == 402 or 'Insufficient credits' in error_msg:
173
+ raise InsufficientCreditsError(error_msg)
174
+ elif status_code == 400 or 'Invalid image' in error_msg:
175
+ raise InvalidImageError(error_msg)
176
+ else:
177
+ raise APIError(f"API error: {error_msg}")
178
+
179
+ def close(self):
180
+ """Close the session"""
181
+ self._session.close()
182
+
183
+ def __enter__(self):
184
+ """Context manager entry"""
185
+ return self
186
+
187
+ def __exit__(self, exc_type, exc_val, exc_tb):
188
+ """Context manager exit"""
189
+ self.close()
@@ -0,0 +1,31 @@
1
+ """
2
+ CaptchaKings API Exceptions
3
+ """
4
+
5
+ class CaptchaKingsException(Exception):
6
+ """Base exception for CaptchaKings API"""
7
+ pass
8
+
9
+ class APIError(CaptchaKingsException):
10
+ """API request error"""
11
+ pass
12
+
13
+ class AuthenticationError(CaptchaKingsException):
14
+ """Invalid API key or authentication failed"""
15
+ pass
16
+
17
+ class InsufficientCreditsError(CaptchaKingsException):
18
+ """Not enough credits to process request"""
19
+ pass
20
+
21
+ class InvalidImageError(CaptchaKingsException):
22
+ """Invalid or corrupted image file"""
23
+ pass
24
+
25
+ class TimeoutError(CaptchaKingsException):
26
+ """Request timeout"""
27
+ pass
28
+
29
+ class NetworkError(CaptchaKingsException):
30
+ """Network connection error"""
31
+ pass
@@ -0,0 +1,294 @@
1
+ Metadata-Version: 2.4
2
+ Name: captchakings
3
+ Version: 1.0.0
4
+ Summary: Official Python client for CaptchaKings API
5
+ Home-page: https://captchakings.com
6
+ Author: CaptchaKings
7
+ Author-email: support@captchakings.com
8
+ Project-URL: Documentation, https://captchakings.com?section=documentation
9
+ Project-URL: Source, https://captchakings.com
10
+ Project-URL: Bug Reports, https://captchakings.com
11
+ Keywords: captcha,ocr,captcha-solver,captchakings,api-client
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.6
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Requires-Python: >=3.6
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: requests>=2.25.0
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: description
31
+ Dynamic: description-content-type
32
+ Dynamic: home-page
33
+ Dynamic: keywords
34
+ Dynamic: license-file
35
+ Dynamic: project-url
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # CaptchaKings Python Library
41
+
42
+ [![Python Version](https://img.shields.io/badge/python-3.6+-blue.svg)](https://www.python.org/downloads/)
43
+ [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
44
+
45
+ Official Python client library for [CaptchaKings API](https://captchakings.com) - Fast, accurate, and affordable CAPTCHA solving service.
46
+
47
+ ## ✨ Features
48
+
49
+ - 🚀 **Simple & Clean API** - Just 2 lines of code to solve CAPTCHAs
50
+ - 🔄 **Automatic Retry** - Built-in retry logic for failed requests
51
+ - 🛡️ **Type Hints** - Full type annotations for better IDE support
52
+ - ⚡ **Fast & Reliable** - Optimized for performance
53
+ - 🎯 **Error Handling** - Custom exceptions for different error types
54
+ - 📦 **Zero Configuration** - Works out of the box
55
+
56
+ ## 📦 Installation
57
+
58
+ ### From Source (Local Development)
59
+
60
+ ```bash
61
+ cd captchakings-python
62
+ pip install -e .
63
+ ```
64
+
65
+ ### Requirements
66
+
67
+ - Python 3.6 or higher
68
+ - `requests` library (automatically installed)
69
+
70
+ ## 🚀 Quick Start
71
+
72
+ ```python
73
+ from captchakings import CaptchaKings
74
+
75
+ # Initialize client
76
+ client = CaptchaKings('ck_your_api_key_here')
77
+
78
+ # Solve CAPTCHA
79
+ result = client.solve('captcha.jpg')
80
+
81
+ print(f"Solved: {result['prediction']}")
82
+ print(f"Confidence: {result['confidence']}")
83
+ print(f"Credits Remaining: {result['credits_remaining']}")
84
+ ```
85
+
86
+ That's it! Just 3 lines of code. 🎉
87
+
88
+ ## 📖 Usage Examples
89
+
90
+ ### Basic Usage
91
+
92
+ ```python
93
+ from captchakings import CaptchaKings
94
+
95
+ client = CaptchaKings('ck_your_api_key')
96
+ result = client.solve('path/to/captcha.jpg')
97
+
98
+ if result:
99
+ print(f"✅ CAPTCHA Solved: {result['prediction']}")
100
+ print(f"Confidence: {result['confidence']}")
101
+ print(f"Credits Remaining: {result['credits_remaining']}")
102
+ ```
103
+
104
+ ### With Automatic Retry
105
+
106
+ ```python
107
+ from captchakings import CaptchaKings
108
+
109
+ client = CaptchaKings('ck_your_api_key')
110
+
111
+ # Automatically retry up to 5 times with 2 second delay
112
+ result = client.solve_with_retry(
113
+ 'captcha.jpg',
114
+ max_retries=5,
115
+ retry_delay=2
116
+ )
117
+
118
+ print(f"Solved: {result['prediction']}")
119
+ ```
120
+
121
+ ### Error Handling
122
+
123
+ ```python
124
+ from captchakings import CaptchaKings
125
+ from captchakings.exceptions import (
126
+ AuthenticationError,
127
+ InsufficientCreditsError,
128
+ InvalidImageError,
129
+ APIError
130
+ )
131
+
132
+ client = CaptchaKings('ck_your_api_key')
133
+
134
+ try:
135
+ result = client.solve('captcha.jpg')
136
+ print(f"Solved: {result['prediction']}")
137
+
138
+ except AuthenticationError:
139
+ print("❌ Invalid API key")
140
+ except InsufficientCreditsError:
141
+ print("❌ Not enough credits")
142
+ except InvalidImageError:
143
+ print("❌ Invalid image file")
144
+ except APIError as e:
145
+ print(f"❌ API Error: {e}")
146
+ ```
147
+
148
+ ### Using Context Manager
149
+
150
+ ```python
151
+ from captchakings import CaptchaKings
152
+
153
+ # Automatically closes session after use
154
+ with CaptchaKings('ck_your_api_key') as client:
155
+ result = client.solve('captcha.jpg')
156
+ print(f"Solved: {result['prediction']}")
157
+ ```
158
+
159
+ ### Processing Multiple CAPTCHAs
160
+
161
+ ```python
162
+ from captchakings import CaptchaKings
163
+ import os
164
+
165
+ client = CaptchaKings('ck_your_api_key')
166
+
167
+ captcha_folder = 'captchas/'
168
+ for filename in os.listdir(captcha_folder):
169
+ if filename.endswith(('.jpg', '.png', '.jpeg')):
170
+ filepath = os.path.join(captcha_folder, filename)
171
+
172
+ try:
173
+ result = client.solve(filepath)
174
+ print(f"{filename}: {result['prediction']}")
175
+ except Exception as e:
176
+ print(f"{filename}: Error - {e}")
177
+ ```
178
+
179
+ ## 🎯 API Reference
180
+
181
+ ### CaptchaKings Class
182
+
183
+ #### `__init__(api_key, base_url='https://captchakings.com/api/process.php')`
184
+
185
+ Initialize the client.
186
+
187
+ **Parameters:**
188
+ - `api_key` (str): Your CaptchaKings API key
189
+ - `base_url` (str, optional): API endpoint URL
190
+
191
+ #### `solve(image_path, timeout=30)`
192
+
193
+ Solve a CAPTCHA from an image file.
194
+
195
+ **Parameters:**
196
+ - `image_path` (str): Path to CAPTCHA image file
197
+ - `timeout` (int, optional): Request timeout in seconds (default: 30)
198
+
199
+ **Returns:**
200
+ - `dict`: Response containing:
201
+ - `prediction` (str): Solved CAPTCHA text
202
+ - `confidence` (float): Prediction confidence score
203
+ - `process_time` (float): Processing time in seconds
204
+ - `credits_deducted` (int): Credits used for this request
205
+ - `credits_remaining` (int): Remaining credits in account
206
+ - `plan` (str): Your current plan name
207
+
208
+ **Raises:**
209
+ - `InvalidImageError`: Image file not found or invalid
210
+ - `AuthenticationError`: Invalid API key
211
+ - `InsufficientCreditsError`: Not enough credits
212
+ - `TimeoutError`: Request timeout
213
+ - `NetworkError`: Connection error
214
+ - `APIError`: Other API errors
215
+
216
+ #### `solve_with_retry(image_path, max_retries=3, retry_delay=2, timeout=30)`
217
+
218
+ Solve CAPTCHA with automatic retry on transient failures.
219
+
220
+ **Parameters:**
221
+ - `image_path` (str): Path to CAPTCHA image file
222
+ - `max_retries` (int, optional): Maximum retry attempts (default: 3)
223
+ - `retry_delay` (int, optional): Delay between retries in seconds (default: 2)
224
+ - `timeout` (int, optional): Request timeout in seconds (default: 30)
225
+
226
+ **Returns:**
227
+ - Same as `solve()` method
228
+
229
+ ## 🎨 Response Format
230
+
231
+ ```python
232
+ {
233
+ 'prediction': 'ABC123', # Solved CAPTCHA text
234
+ 'confidence': 0.98, # Confidence score (0-1)
235
+ 'process_time': 0.234, # Processing time in seconds
236
+ 'credits_deducted': 1, # Credits used
237
+ 'credits_remaining': 9999, # Remaining credits
238
+ 'plan': 'Professional' # Your plan name
239
+ }
240
+ ```
241
+
242
+ ## ⚠️ Exception Types
243
+
244
+ - `CaptchaKingsException` - Base exception class
245
+ - `APIError` - General API errors
246
+ - `AuthenticationError` - Invalid API key
247
+ - `InsufficientCreditsError` - Not enough credits
248
+ - `InvalidImageError` - Invalid or missing image file
249
+ - `TimeoutError` - Request timeout
250
+ - `NetworkError` - Network connection error
251
+
252
+ ## 🔑 Getting API Key
253
+
254
+ 1. Visit [CaptchaKings.com](https://captchakings.com)
255
+ 2. Register for an account
256
+ 3. Go to Dashboard
257
+ 4. Copy your API key (starts with `ck_`)
258
+
259
+ ## 💡 Tips
260
+
261
+ 1. **Use context manager** - Ensures proper session cleanup
262
+ 2. **Enable retry logic** - For better reliability
263
+ 3. **Handle exceptions** - For robust error handling
264
+ 4. **Batch processing** - Reuse the same client instance
265
+
266
+ ## 📚 More Examples
267
+
268
+ Check the `examples/` folder for more usage examples:
269
+
270
+ - `basic_usage.py` - Simple CAPTCHA solving
271
+ - `advanced_usage.py` - Advanced features and error handling
272
+ - `batch_processing.py` - Process multiple CAPTCHAs
273
+
274
+ ## 🤝 Support
275
+
276
+ - **Website**: [captchakings.com](https://captchakings.com)
277
+ - **Documentation**: [captchakings.com/docs](https://captchakings.com?section=documentation)
278
+ - **Email**: support@captchakings.com
279
+
280
+ ## 📄 License
281
+
282
+ MIT License - see LICENSE file for details
283
+
284
+ ## 🌟 Why CaptchaKings?
285
+
286
+ - ✅ **High Accuracy** - 99%+ success rate
287
+ - ✅ **Fast Processing** - < 1 second average response time
288
+ - ✅ **Affordable Pricing** - Starting from $1/1000 solves
289
+ - ✅ **24/7 Support** - Always here to help
290
+ - ✅ **No Setup Required** - Start in seconds
291
+
292
+ ---
293
+
294
+ Made with ❤️ by [CaptchaKings](https://captchakings.com)
@@ -0,0 +1,8 @@
1
+ captchakings/__init__.py,sha256=mgXzghjPRmVra9ZBE4cm15zUkbszFAK-m9Kfkp4RK4c,769
2
+ captchakings/client.py,sha256=FXBQDPmEO9Kd9LvTjaEFuFKpZr92E4po47uFqBo2f9A,6491
3
+ captchakings/exceptions.py,sha256=gEg2YyZdWhBoWaPS4GPnJHDlKaDgeV6lfE1XCdp5JlY,700
4
+ captchakings-1.0.0.dist-info/licenses/LICENSE,sha256=pbtrBRDwqQPp3x4iWRUI070lnIOuaGTvt0_ldws_aS8,1069
5
+ captchakings-1.0.0.dist-info/METADATA,sha256=a21ftJTv5oGDMD-UzLBEMRYMgPj5CRxTocmjMy5nee0,8614
6
+ captchakings-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ captchakings-1.0.0.dist-info/top_level.txt,sha256=IkIvMDQ-vA_9dcJjzymjeDYs8XObiVLGRTiGL6m_-fc,13
8
+ captchakings-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 CaptchaKings
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ captchakings