├── MANIFEST.in ├── src └── capsolver │ ├── __main__.py │ ├── __init__.py │ ├── error.py │ ├── capsolver.py │ ├── capsolver_object.py │ ├── check.py │ └── api_requestor.py ├── test ├── balance.py ├── image_text.py └── task.py ├── .gitignore ├── pyproject.toml ├── setup.cfg ├── setup.py ├── LICENSE.rst ├── LICENSE ├── README.md └── .pylintrc /MANIFEST.in: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/capsolver/__main__.py: -------------------------------------------------------------------------------- 1 | import capsolver -------------------------------------------------------------------------------- /test/balance.py: -------------------------------------------------------------------------------- 1 | import capsolver 2 | #capsolver.api_key = "" 3 | balance = capsolver.balance() 4 | print(balance) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.txt 2 | *.Db_Store 3 | __pycache__ 4 | build 5 | *.capsolver 6 | *.egg-info 7 | reinstall.sh 8 | *.jpg 9 | *.png 10 | dist -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | 2 | 3 | [build-system] 4 | requires = [ 5 | "setuptools>=42", 6 | "wheel" 7 | ] 8 | build-backend = "setuptools.build_meta" 9 | -------------------------------------------------------------------------------- /test/image_text.py: -------------------------------------------------------------------------------- 1 | import capsolver 2 | from pathlib import Path 3 | import os 4 | import base64 5 | 6 | img_path = os.path.join(Path(__file__).resolve().parent,"queue-it.jpg") 7 | 8 | with open(img_path,'rb') as f: 9 | img = base64.b64encode(f.read()) .decode("utf8") 10 | solution = capsolver.solve({ 11 | "type":"ImageToTextTask", 12 | "module":"queueit", 13 | "body":img 14 | }) 15 | print(solution) 16 | 17 | solution = capsolver.solve({ 18 | "type":"HCaptchaClassification", 19 | "queries":[img], 20 | "question":"Please click each image containing a truck" 21 | }) 22 | print(solution) -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = capsolver 3 | version = 1.0.3 4 | author = capsolver 5 | author_email = capsolver.com@gmail.com 6 | description = capsolver python libary 7 | long_description = file: README.md 8 | long_description_content_type = text/markdown 9 | url = https://github.com/capsolver/capsolver-python 10 | project_urls = 11 | Bug Tracker = https://github.com/capsolver/capsolver-python/issues 12 | classifiers = 13 | Programming Language :: Python :: 3 14 | License :: OSI Approved :: MIT License 15 | Operating System :: OS Independent 16 | 17 | [options] 18 | package_dir = 19 | = src 20 | packages = find: 21 | python_requires = >=3.6 22 | 23 | [options.packages.find] 24 | where = src -------------------------------------------------------------------------------- /test/task.py: -------------------------------------------------------------------------------- 1 | #pip install --upgrade capsolver 2 | import capsolver 3 | #capsolver.api_key = "" 4 | print("api host",capsolver.api_base) 5 | print("api key",capsolver.api_key) 6 | 7 | solution = capsolver.solve({ 8 | "type": "FunCaptchaTask", 9 | "websiteURL": "https://setup.live.com/register", 10 | "websitePublicKey": "B7D8911C-5CC8-A9A3-35B0-554ACEE604DA", 11 | "proxy": "private.residential.proxyrack.net:10004", 12 | }) 13 | print(solution) 14 | 15 | # solution = capsolver.solve({ 16 | # "type":"ReCaptchaV2TaskProxyLess", 17 | # "websiteKey":"6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-", 18 | # "websiteURL":"https://www.google.com/recaptcha/api2/demo", 19 | # }) 20 | # print(solution) -------------------------------------------------------------------------------- /src/capsolver/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from capsolver.capsolver import Capsolver 4 | from capsolver.error import InvalidRequestError, IncompleteJobError, RateLimitError, AuthenticationError, InsufficientCreditError, UnknownError, Timeout, APIError, ServiceUnavailableError 5 | 6 | api_base = os.environ.get("CAPSOLVER_API_BASE", "https://api.capsolver.com") 7 | api_key = os.environ.get("CAPSOLVER_API_KEY") 8 | solve = Capsolver.solve 9 | balance = Capsolver.balance 10 | proxy = None 11 | 12 | 13 | __all__ = [ 14 | "Capsolver" 15 | "CAPSOLVERError", 16 | "InvalidRequestError", 17 | "IncompleteJobError", 18 | "RateLimitError", 19 | "AuthenticationError", 20 | "InsufficientCreditError", 21 | "UnknownError", 22 | "Timeout", 23 | "APIError", 24 | "ServiceUnavailableError", 25 | 26 | "api_base", 27 | "api_key", 28 | "proxy", 29 | ] 30 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="capsolver", 8 | version="1.0.3", 9 | author="capsolver", 10 | author_email="capsolver.com@gmail.com", 11 | description="capsolver python libary", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/capsolver/capsolver-python", 15 | project_urls={ 16 | "Bug Tracker": "https://github.com/capsovler/capsovler-python/issues", 17 | }, 18 | classifiers=[ 19 | "Programming Language :: Python :: 3", 20 | "License :: OSI Approved :: MIT License", 21 | "Operating System :: OS Independent", 22 | ], 23 | 24 | install_requires=[ 25 | "requests >= 2.26.0", 26 | ], 27 | packages=setuptools.find_packages(where="src"), 28 | package_dir={"": "src"}, 29 | include_package_data=True, 30 | python_requires=">=3.6.8", 31 | 32 | ) -------------------------------------------------------------------------------- /LICENSE.rst: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 The Python Packaging Authority 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | 3 | Copyright (c) 2021 The Python Packaging Authority 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. -------------------------------------------------------------------------------- /src/capsolver/error.py: -------------------------------------------------------------------------------- 1 | class CapsolverError(Exception): 2 | def __init__(self, message=None, http_body=None, http_status=None, json_body=None, headers=None): 3 | super(CapsolverError, self).__init__(message) 4 | 5 | self._message = message 6 | self.http_body = http_body 7 | self.http_status = http_status 8 | self.json_body = json_body 9 | self.headers = headers or {} 10 | 11 | def __str__(self): 12 | return f"{type(self).__name__}: {self._message}" or "" 13 | 14 | 15 | class InvalidRequestError(CapsolverError): 16 | pass 17 | 18 | class IncompleteJobError(CapsolverError): 19 | pass 20 | 21 | 22 | class RateLimitError(CapsolverError): 23 | pass 24 | 25 | 26 | class AuthenticationError(CapsolverError): 27 | pass 28 | 29 | 30 | class InsufficientCreditError(CapsolverError): 31 | pass 32 | 33 | 34 | class UnknownError(CapsolverError): 35 | pass 36 | 37 | 38 | class Timeout(CapsolverError): 39 | pass 40 | 41 | 42 | class APIError(CapsolverError): 43 | pass 44 | 45 | 46 | class ServiceUnavailableError(CapsolverError): 47 | pass 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Capsolver 2 | Capsolver official python library 3 | 4 | ## Supported CAPTCHA types: 5 | - Geetest 6 | - ReCaptchaV2 7 | - ReCaptchav3 8 | - MtCaptcha 9 | - Cloudflare 10 | - Amazon captcha(AWS WAF) 11 | 12 | 13 | ## Installation 14 | 15 | You don't need this source code unless you want to modify the package. If you just 16 | want to use the package, just run: 17 | 18 | ```sh 19 | pip3 install --upgrade capsolver 20 | ``` 21 | 22 | Install from source with: 23 | 24 | ```sh 25 | python setup.py install 26 | ``` 27 | 28 | ## Usage 29 | 30 | ```bash 31 | export CAPSOLVER_API_KEY='...' 32 | ``` 33 | 34 | Or set `capsolver.api_key` to its value: 35 | 36 | ```python 37 | from pathlib import Path 38 | import os 39 | import base64 40 | import capsolver 41 | 42 | # tokenTask 43 | print("api host",capsolver.api_base) 44 | print("api key",capsolver.api_key) 45 | # capsolver.api_key = "..." 46 | solution = capsolver.solve({ 47 | "type":"ReCaptchaV2TaskProxyLess", 48 | "websiteKey":"6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-", 49 | "websiteURL":"https://www.google.com/recaptcha/api2/demo", 50 | }) 51 | 52 | print(solution) 53 | 54 | # RecognitionTask 55 | img_path = os.path.join(Path(__file__).resolve().parent,"queue-it.jpg") 56 | with open(img_path,'rb') as f: 57 | solution = capsolver.solve({ 58 | "type":"ImageToTextTask", 59 | "module":"queueit", 60 | "body":base64.b64encode(f.read()).decode("utf8") 61 | }) 62 | print(solution) 63 | 64 | # get current balance 65 | balance = capsolver.balance() 66 | # print the current balance 67 | print(balance) 68 | ``` 69 | 70 | 71 | -------------------------------------------------------------------------------- /src/capsolver/capsolver.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import capsolver.error 4 | from capsolver.capsolver_object import CapsolverObject 5 | from capsolver.check import _check_params 6 | 7 | _DEFAULT_RETRIES = 60 8 | _DEFAULT_INTERVAL = 1 9 | 10 | 11 | class Capsolver(CapsolverObject): 12 | 13 | def __init__(self, api_key=None, api_base=None, **params): 14 | super().__init__(api_key, api_base, **params) 15 | 16 | 17 | @staticmethod 18 | def check_params(params:dict): 19 | return _check_params(params) 20 | 21 | @classmethod 22 | def postTask(cls, params:dict): 23 | r = cls().check_params(params=params) 24 | if isinstance(r, capsolver.error.CapsolverError): 25 | raise r 26 | return cls().request("post", "/createTask", {"task":params}) 27 | 28 | @classmethod 29 | def getTask(cls, **params): 30 | for _ in range(_DEFAULT_RETRIES): 31 | time.sleep(_DEFAULT_INTERVAL) 32 | r = cls().request("post", "/getTaskResult", params) 33 | if isinstance(r,capsolver.error.CapsolverError): 34 | raise r 35 | if r["status"]=="processing": 36 | continue 37 | return r 38 | raise capsolver.error.Timeout('Failed to get results') 39 | 40 | @classmethod 41 | def solve(cls,params:dict): 42 | r = cls.postTask(params) 43 | if isinstance(r, capsolver.error.CapsolverError): 44 | raise r 45 | if r['status']=="ready": 46 | return r['solution'] 47 | r = cls.getTask(taskId=r['taskId']) 48 | if isinstance(r, capsolver.error.CapsolverError): 49 | raise r 50 | return r['solution'] 51 | 52 | 53 | @classmethod 54 | def balance(cls): 55 | r = cls().request("post", "/getBalance",{}) 56 | return r 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/capsolver/capsolver_object.py: -------------------------------------------------------------------------------- 1 | import json 2 | from copy import deepcopy 3 | 4 | from capsolver import api_requestor 5 | 6 | 7 | class CapsolverObject(dict): 8 | api_base_override = None 9 | 10 | 11 | def __init__(self, api_key=None, api_base=None, **params): 12 | super(CapsolverObject, self).__init__() 13 | self._retrieve_params = params 14 | object.__setattr__(self, "api_key", api_key) 15 | object.__setattr__(self, "api_base_override", api_base) 16 | 17 | def __setattr__(self, k, v): 18 | if k[0] == "_" or k in self.__dict__: 19 | return super(CapsolverObject, self).__setattr__(k, v) 20 | self[k] = v 21 | return None 22 | 23 | def __getattr__(self, k): 24 | if k[0] == "_": 25 | raise AttributeError(k) 26 | try: 27 | return self[k] 28 | except KeyError as err: 29 | raise AttributeError(*err.args) 30 | 31 | def __delattr__(self, k): 32 | if k[0] == "_" or k in self.__dict__: 33 | return super(CapsolverObject, self).__delattr__(k) 34 | else: 35 | del self[k] 36 | 37 | def __setitem__(self, k, v): 38 | if v == "": 39 | raise ValueError(f"You cannot set {k} to an empty string. We interpret empty strings as None in requests. You may set {str(self)}.{k} = None to delete the property") 40 | super(CapsolverObject, self).__setitem__(k, v) 41 | 42 | def __delitem__(self, k): 43 | raise NotImplementedError("del is not supported") 44 | 45 | def __setstate__(self, state): 46 | self.update(state) 47 | 48 | def __reduce__(self): 49 | return (type(self), (self.api_key,), dict(self)) 50 | 51 | @classmethod 52 | def api_base(cls): 53 | return None 54 | 55 | def request(self, method, url, params=None, headers=None, request_timeout=None): 56 | if params is None: 57 | params = self._retrieve_params 58 | requestor = api_requestor.APIRequestor(key=self.api_key, api_base=self.api_base_override or self.api_base()) 59 | return requestor.request(method, url, params=params, headers=headers, request_timeout=request_timeout) 60 | 61 | def __repr__(self): 62 | ident_parts = [type(self).__name__] 63 | obj = self.get("object") 64 | if isinstance(obj, str): 65 | ident_parts.append(obj) 66 | return "<%s at %s> JSON: %s" % ( 67 | " ".join(ident_parts), 68 | hex(id(self)), 69 | str(self), 70 | ) 71 | 72 | def __str__(self): 73 | obj = self.to_dict_recursive() 74 | return json.dumps(obj, sort_keys=True, indent=2) 75 | 76 | def to_dict(self): 77 | return dict(self) 78 | 79 | def to_dict_recursive(self): 80 | d = dict(self) 81 | for k, v in d.items(): 82 | if isinstance(v, CapsolverObject): 83 | d[k] = v.to_dict_recursive() 84 | elif isinstance(v, list): 85 | d[k] = [e.to_dict_recursive() if isinstance(e, CapsolverObject) else e for e in v] 86 | return d 87 | 88 | def __copy__(self): 89 | copied = CapsolverObject(self.api_key) 90 | copied._retrieve_params = self._retrieve_params 91 | for k, v in self.items(): 92 | super(CapsolverObject, copied).__setitem__(k, v) 93 | return copied 94 | 95 | def __deepcopy__(self, memo): 96 | copied = self.__copy__() 97 | memo[id(self)] = copied 98 | for k, v in self.items(): 99 | super(CapsolverObject, copied).__setitem__(k, deepcopy(v, memo)) 100 | return copied 101 | -------------------------------------------------------------------------------- /src/capsolver/check.py: -------------------------------------------------------------------------------- 1 | 2 | from capsolver.error import CapsolverError 3 | 4 | 5 | SUPPORT_TASK_TYPE = [ 6 | "HCaptchaTask", 7 | "HCaptchaTaskProxyLess", 8 | "HCaptchaEnterpriseTask", 9 | "HCaptchaEnterpriseTaskProxyLess", 10 | 11 | "FunCaptchaTask", 12 | "FunCaptchaTaskProxyLess", 13 | 14 | "GeeTestTask", 15 | "GeeTestTaskProxyLess", 16 | 17 | "ReCaptchaV2Task", 18 | "ReCaptchaV2TaskProxyLess", 19 | 20 | "ReCaptchaV2EnterpriseTaskProxyLess", 21 | "ReCaptchaV2EnterpriseTask", 22 | 23 | "ReCaptchaV3Task", 24 | "ReCaptchaV3TaskProxyLess", 25 | 26 | "MtCaptchaTask", 27 | "MtCaptchaTaskProxyLess", 28 | 29 | "DataDomeSliderTask", 30 | 31 | "AntiCloudflareTask", 32 | 33 | "AntiKasadaTask", 34 | 35 | "AntiAkamaiBMPTask", 36 | 37 | "ImageToTextTask", 38 | 39 | "HCaptchaClassification", 40 | 41 | "FunCaptchaClassification", 42 | 43 | "AwsWafClassification", 44 | 45 | ] 46 | 47 | 48 | def captcha_basic_check(params:dict): 49 | params_keys = params.keys() 50 | if "websiteURL" not in params_keys: 51 | return CapsolverError("need websiteURL param") 52 | if "websiteKey" not in params_keys: 53 | return CapsolverError("need websiteKey param") 54 | return None 55 | 56 | def check_recaptcha(params:dict): 57 | 58 | return captcha_basic_check(params) 59 | 60 | 61 | def check_hcaptcha(params): 62 | r = captcha_basic_check(params) 63 | if not r: 64 | return r 65 | return None 66 | 67 | def check_funcaptcha(params:dict): 68 | params_keys = params.keys() 69 | if "websiteURL" not in params_keys: 70 | return CapsolverError("need websiteURL param") 71 | if "websitePublicKey" not in params_keys: 72 | return CapsolverError("need websitePublicKey param") 73 | return None 74 | 75 | def check_mtcaptcha(params:dict): 76 | r = captcha_basic_check(params) 77 | if not r: 78 | return r 79 | return None 80 | 81 | 82 | def _format_all_task_type(): 83 | list_types = [] 84 | for i in range(len(SUPPORT_TASK_TYPE)): 85 | list_types.append(f"{i}. {SUPPORT_TASK_TYPE[i]}") 86 | return "\n".join(list_types) 87 | 88 | 89 | def _check_params(params:dict): 90 | captcha_type:str = params["type"] 91 | if params["type"] not in SUPPORT_TASK_TYPE: 92 | return CapsolverError("unsupport TaskType" +captcha_type+"\n support types as follow \n"+_format_all_task_type()) 93 | captcha_type = captcha_type.lower() 94 | if "recaptcha" in captcha_type: 95 | return check_recaptcha(params) 96 | if "hcaptcha" in captcha_type: 97 | return check_hcaptcha(params) 98 | if "funcaptcha" in captcha_type: 99 | return check_funcaptcha(params) 100 | if "mtcaptcha" in captcha_type: 101 | return captcha_basic_check() 102 | 103 | if "geetesttask" in captcha_type: 104 | if "gt" not in params.keys(): 105 | return CapsolverError(captcha_type+" need gt param") 106 | if "challenge" not in params.keys(): 107 | return CapsolverError(captcha_type+" need challenge param") 108 | 109 | if "datadom" in captcha_type: 110 | if "proxy" not in params.keys(): 111 | return CapsolverError(captcha_type+" need proxy param") 112 | if "userAgent" not in params.keys(): 113 | return CapsolverError(captcha_type+" need userAgent") 114 | 115 | if "anticloudflare" in captcha_type: 116 | if "metadata" not in params.keys(): 117 | return CapsolverError(captcha_type+" need metadata param") 118 | 119 | if "antikasada" in captcha_type: 120 | if "pageURL" not in params.keys(): 121 | return CapsolverError(captcha_type+" need pageURL param") 122 | if "proxy" not in params.keys(): 123 | return CapsolverError(captcha_type+" need proxy param") 124 | 125 | if "antiakamaibmp" in captcha_type: 126 | if "packageName" not in params.keys(): 127 | return CapsolverError(captcha_type+" need packageName param") 128 | 129 | 130 | -------------------------------------------------------------------------------- /src/capsolver/api_requestor.py: -------------------------------------------------------------------------------- 1 | import json 2 | import platform 3 | import threading 4 | from json import JSONDecodeError 5 | from urllib.parse import urlencode, urlsplit, urlunsplit 6 | 7 | import requests 8 | 9 | from capsolver import error 10 | import capsolver 11 | 12 | TIMEOUT_SECS = 600 13 | MAX_CONNECTION_RETRIES = 2 14 | 15 | _thread_context = threading.local() 16 | 17 | 18 | api_key_to_header = (lambda key: {"Authorization": f"Bearer {key}"}) 19 | 20 | 21 | def _build_api_url(url, query): 22 | scheme, netloc, path, base_query, fragment = urlsplit(url) 23 | 24 | if base_query: 25 | query = "%s&%s" % (base_query, query) 26 | 27 | return urlunsplit((scheme, netloc, path, query, fragment)) 28 | 29 | 30 | def _requests_proxies_arg(proxy): 31 | """Returns a value suitable for the 'proxies' argument to 'requests.request.""" 32 | if proxy is None: 33 | return None 34 | elif isinstance(proxy, str): 35 | return {"http": proxy, "https": proxy} 36 | elif isinstance(proxy, dict): 37 | return proxy.copy() 38 | else: 39 | raise ValueError("'capsolver.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys.") 40 | 41 | 42 | def _make_session(): 43 | s = requests.Session() 44 | proxies = _requests_proxies_arg(capsolver.proxy) 45 | if proxies: 46 | s.proxies = proxies 47 | s.mount("https://", requests.adapters.HTTPAdapter(max_retries=MAX_CONNECTION_RETRIES)) 48 | return s 49 | 50 | 51 | class APIRequestor: 52 | def __init__(self, key=None, api_base=None): 53 | self.api_base = api_base or capsolver.api_base 54 | self.api_key = key or capsolver.api_key 55 | 56 | def request(self, method, url, params=None, headers=None, request_timeout=None): 57 | result = self.request_raw(method.lower(), url, params=params, supplied_headers=headers, request_timeout=request_timeout) 58 | resp, rbody, rcode, rheaders = self._interpret_response(result) 59 | if resp["errorId"]!=0: 60 | return self.handle_error_response(rbody, rcode, resp, rheaders) 61 | return resp 62 | 63 | def handle_error_response(self, rbody, rcode, resp, rheaders): 64 | error_data = resp["errorDescription"] 65 | if rcode == 429: 66 | return error.RateLimitError(error_data, rbody, rcode, resp, rheaders) 67 | elif rcode == 400: 68 | return error.InvalidRequestError(error_data, rbody, rcode, resp, rheaders) 69 | elif rcode == 401: 70 | return error.AuthenticationError(error_data, rbody, rcode, resp, rheaders) 71 | elif rcode == 403: 72 | return error.InsufficientCreditError(error_data, rbody, rcode, resp, rheaders) 73 | elif rcode == 409: 74 | return error.IncompleteJobError(error_data, rbody, rcode, resp, rheaders) 75 | else: 76 | return error.UnknownError(error_data, rbody, rcode, resp, rheaders) 77 | 78 | def request_headers(self, extra): 79 | user_agent = "capsolver PythonBindings" 80 | uname_without_node = " ".join(v for k, v in platform.uname()._asdict().items() if k != "node") 81 | ua = { 82 | "httplib": "requests", 83 | "lang": "python", 84 | "lang_version": platform.python_version(), 85 | "platform": platform.platform(), 86 | "publisher": "capsolver", 87 | "uname": uname_without_node, 88 | } 89 | headers = { 90 | "X-capsolver-Client-User-Agent": json.dumps(ua), 91 | "User-Agent": user_agent, 92 | } 93 | headers.update(api_key_to_header(self.api_key)) 94 | headers.update(extra) 95 | return headers 96 | 97 | def _validate_headers(self, supplied_headers): 98 | headers = {} 99 | if supplied_headers is None: 100 | return headers 101 | if not isinstance(supplied_headers, dict): 102 | raise TypeError("Headers must be a dictionary") 103 | for k, v in supplied_headers.items(): 104 | if not isinstance(k, str): 105 | raise TypeError("Header keys must be strings") 106 | if not isinstance(v, str): 107 | raise TypeError("Header values must be strings") 108 | headers[k] = v 109 | return headers 110 | 111 | 112 | def request_raw(self, method, url, *, params=None, supplied_headers=None, request_timeout=None): 113 | abs_url = "%s%s" % (self.api_base, url) 114 | headers = self._validate_headers(supplied_headers) 115 | json_data = { 116 | "clientKey":self.api_key, 117 | } 118 | json_data.update(params) 119 | headers = self.request_headers(headers) 120 | if not hasattr(_thread_context, "session"): 121 | _thread_context.session = _make_session() 122 | try: 123 | result = _thread_context.session.request(method, abs_url, headers=headers, json=json_data, timeout=request_timeout if request_timeout else TIMEOUT_SECS) 124 | except requests.exceptions.Timeout as e: 125 | raise error.Timeout("Request timed out") from e 126 | except requests.exceptions.RequestException as e: 127 | raise error.APIError("Error communicating with capsolver") from e 128 | return result 129 | 130 | def _interpret_response(self, result): 131 | return self._interpret_response_line(result.content, result.status_code, result.headers) 132 | 133 | def _interpret_response_line(self, rbody, rcode, rheaders): 134 | if rcode == 503: 135 | raise error.ServiceUnavailableError("The server is overloaded or not ready yet.", rbody, rcode, headers=rheaders) 136 | try: 137 | if hasattr(rbody, "decode"): 138 | rbody = rbody.decode("utf-8") 139 | resp = json.loads(rbody) 140 | except (JSONDecodeError, UnicodeDecodeError): 141 | raise error.APIError(f"HTTP code {rcode} from API ({rbody})", rbody, rcode, headers=rheaders) 142 | return resp, rbody, rcode, rheaders 143 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # A comma-separated list of package or module names from where C extensions may 4 | # be loaded. Extensions are loading into the active Python interpreter and may 5 | # run arbitrary code. 6 | extension-pkg-whitelist=cv2 7 | 8 | # Add files or directories to the blacklist. They should be base names, not 9 | # paths. 10 | ignore=CVS 11 | 12 | # Add files or directories matching the regex patterns to the blacklist. The 13 | # regex matches against base names, not paths. 14 | ignore-patterns= 15 | 16 | # Python code to execute, usually for sys.path manipulation such as 17 | # pygtk.require(). 18 | #init-hook= 19 | 20 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the 21 | # number of processors available to use. 22 | jobs=1 23 | 24 | # Control the amount of potential inferred values when inferring a single 25 | # object. This can help the performance when dealing with large functions or 26 | # complex, nested conditions. 27 | limit-inference-results=100 28 | 29 | # List of plugins (as comma separated values of python modules names) to load, 30 | # usually to register additional checkers. 31 | load-plugins= 32 | 33 | # Pickle collected data for later comparisons. 34 | persistent=yes 35 | 36 | # Specify a configuration file. 37 | #rcfile= 38 | 39 | # When enabled, pylint would attempt to guess common misconfiguration and emit 40 | # user-friendly hints instead of false-positive error messages. 41 | suggestion-mode=yes 42 | 43 | # Allow loading of arbitrary C extensions. Extensions are imported into the 44 | # active Python interpreter and may run arbitrary code. 45 | unsafe-load-any-extension=no 46 | 47 | 48 | [MESSAGES CONTROL] 49 | 50 | # Only show warnings with the listed confidence levels. Leave empty to show 51 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. 52 | confidence= 53 | 54 | # Disable the message, report, category or checker with the given id(s). You 55 | # can either give multiple identifiers separated by comma (,) or put this 56 | # option multiple times (only on the command line, not in the configuration 57 | # file where it should appear only once). You can also use "--disable=all" to 58 | # disable everything first and then reenable specific checks. For example, if 59 | # you want to run only the similarities checker, you can use "--disable=all 60 | # --enable=similarities". If you want to run only the classes checker, but have 61 | # no Warning level messages displayed, use "--disable=all --enable=classes 62 | # --disable=W". 63 | disable=print-statement, 64 | parameter-unpacking, 65 | unpacking-in-except, 66 | old-raise-syntax, 67 | backtick, 68 | long-suffix, 69 | old-ne-operator, 70 | old-octal-literal, 71 | import-star-module-level, 72 | non-ascii-bytes-literal, 73 | raw-checker-failed, 74 | bad-inline-option, 75 | locally-disabled, 76 | file-ignored, 77 | suppressed-message, 78 | useless-suppression, 79 | deprecated-pragma, 80 | use-symbolic-message-instead, 81 | apply-builtin, 82 | basestring-builtin, 83 | buffer-builtin, 84 | cmp-builtin, 85 | coerce-builtin, 86 | execfile-builtin, 87 | file-builtin, 88 | long-builtin, 89 | raw_input-builtin, 90 | reduce-builtin, 91 | standarderror-builtin, 92 | unicode-builtin, 93 | xrange-builtin, 94 | coerce-method, 95 | delslice-method, 96 | getslice-method, 97 | setslice-method, 98 | no-absolute-import, 99 | old-division, 100 | dict-iter-method, 101 | dict-view-method, 102 | next-method-called, 103 | metaclass-assignment, 104 | indexing-exception, 105 | raising-string, 106 | reload-builtin, 107 | oct-method, 108 | hex-method, 109 | nonzero-method, 110 | cmp-method, 111 | input-builtin, 112 | round-builtin, 113 | intern-builtin, 114 | unichr-builtin, 115 | map-builtin-not-iterating, 116 | zip-builtin-not-iterating, 117 | range-builtin-not-iterating, 118 | filter-builtin-not-iterating, 119 | using-cmp-argument, 120 | eq-without-hash, 121 | div-method, 122 | idiv-method, 123 | rdiv-method, 124 | exception-message-attribute, 125 | invalid-str-codec, 126 | sys-max-int, 127 | bad-python3-import, 128 | deprecated-string-function, 129 | deprecated-str-translate-call, 130 | deprecated-itertools-function, 131 | deprecated-types-field, 132 | next-method-defined, 133 | dict-items-not-iterating, 134 | dict-keys-not-iterating, 135 | dict-values-not-iterating, 136 | deprecated-operator-function, 137 | deprecated-urllib-function, 138 | xreadlines-attribute, 139 | deprecated-sys-function, 140 | exception-escape, 141 | comprehension-escape 142 | 143 | # Enable the message, report, category or checker with the given id(s). You can 144 | # either give multiple identifier separated by comma (,) or put this option 145 | # multiple time (only on the command line, not in the configuration file where 146 | # it should appear only once). See also the "--disable" option for examples. 147 | enable=c-extension-no-member 148 | 149 | 150 | [REPORTS] 151 | 152 | # Python expression which should return a note less than 10 (10 is the highest 153 | # note). You have access to the variables errors warning, statement which 154 | # respectively contain the number of errors / warnings messages and the total 155 | # number of statements analyzed. This is used by the global evaluation report 156 | # (RP0004). 157 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 158 | 159 | # Template used to display messages. This is a python new-style format string 160 | # used to format the message information. See doc for all details. 161 | #msg-template= 162 | 163 | # Set the output format. Available formats are text, parseable, colorized, json 164 | # and msvs (visual studio). You can also give a reporter class, e.g. 165 | # mypackage.mymodule.MyReporterClass. 166 | output-format=text 167 | 168 | # Tells whether to display a full report or only the messages. 169 | reports=no 170 | 171 | # Activate the evaluation score. 172 | score=yes 173 | 174 | 175 | [REFACTORING] 176 | 177 | # Maximum number of nested blocks for function / method body 178 | max-nested-blocks=5 179 | 180 | # Complete name of functions that never returns. When checking for 181 | # inconsistent-return-statements if a never returning function is called then 182 | # it will be considered as an explicit return statement and no message will be 183 | # printed. 184 | never-returning-functions=sys.exit 185 | 186 | 187 | [LOGGING] 188 | 189 | # Format style used to check logging format string. `old` means using % 190 | # formatting, while `new` is for `{}` formatting. 191 | logging-format-style=old 192 | 193 | # Logging modules to check that the string format arguments are in logging 194 | # function parameter format. 195 | logging-modules=logging 196 | 197 | 198 | [SPELLING] 199 | 200 | # Limits count of emitted suggestions for spelling mistakes. 201 | max-spelling-suggestions=4 202 | 203 | # Spelling dictionary name. Available dictionaries: none. To make it working 204 | # install python-enchant package.. 205 | spelling-dict= 206 | 207 | # List of comma separated words that should not be checked. 208 | spelling-ignore-words= 209 | 210 | # A path to a file that contains private dictionary; one word per line. 211 | spelling-private-dict-file= 212 | 213 | # Tells whether to store unknown words to indicated private dictionary in 214 | # --spelling-private-dict-file option instead of raising a message. 215 | spelling-store-unknown-words=no 216 | 217 | 218 | [MISCELLANEOUS] 219 | 220 | # List of note tags to take in consideration, separated by a comma. 221 | notes=FIXME, 222 | XXX, 223 | TODO 224 | 225 | 226 | [TYPECHECK] 227 | 228 | # List of decorators that produce context managers, such as 229 | # contextlib.contextmanager. Add to this list to register other decorators that 230 | # produce valid context managers. 231 | contextmanager-decorators=contextlib.contextmanager 232 | 233 | # List of members which are set dynamically and missed by pylint inference 234 | # system, and so shouldn't trigger E1101 when accessed. Python regular 235 | # expressions are accepted. 236 | generated-members=torch.* 237 | 238 | # Tells whether missing members accessed in mixin class should be ignored. A 239 | # mixin class is detected if its name ends with "mixin" (case insensitive). 240 | ignore-mixin-members=yes 241 | 242 | # Tells whether to warn about missing members when the owner of the attribute 243 | # is inferred to be None. 244 | ignore-none=yes 245 | 246 | # This flag controls whether pylint should warn about no-member and similar 247 | # checks whenever an opaque object is returned when inferring. The inference 248 | # can return multiple potential results while evaluating a Python object, but 249 | # some branches might not be evaluated, which results in partial inference. In 250 | # that case, it might be useful to still emit no-member and other checks for 251 | # the rest of the inferred objects. 252 | ignore-on-opaque-inference=yes 253 | 254 | # List of class names for which member attributes should not be checked (useful 255 | # for classes with dynamically set attributes). This supports the use of 256 | # qualified names. 257 | ignored-classes=optparse.Values,thread._local,_thread._local 258 | 259 | # List of module names for which member attributes should not be checked 260 | # (useful for modules/projects where namespaces are manipulated during runtime 261 | # and thus existing member attributes cannot be deduced by static analysis. It 262 | # supports qualified module names, as well as Unix pattern matching. 263 | ignored-modules=tensorrt,pycuda 264 | 265 | # Show a hint with possible names when a member name was not found. The aspect 266 | # of finding the hint is based on edit distance. 267 | missing-member-hint=yes 268 | 269 | # The minimum edit distance a name should have in order to be considered a 270 | # similar match for a missing member name. 271 | missing-member-hint-distance=1 272 | 273 | # The total number of similar names that should be taken in consideration when 274 | # showing a hint for a missing member. 275 | missing-member-max-choices=1 276 | 277 | 278 | [VARIABLES] 279 | 280 | # List of additional names supposed to be defined in builtins. Remember that 281 | # you should avoid defining new builtins when possible. 282 | additional-builtins= 283 | 284 | # Tells whether unused global variables should be treated as a violation. 285 | allow-global-unused-variables=yes 286 | 287 | # List of strings which can identify a callback function by name. A callback 288 | # name must start or end with one of those strings. 289 | callbacks=cb_, 290 | _cb 291 | 292 | # A regular expression matching the name of dummy variables (i.e. expected to 293 | # not be used). 294 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 295 | 296 | # Argument names that match this expression will be ignored. Default to name 297 | # with leading underscore. 298 | ignored-argument-names=_.*|^ignored_|^unused_ 299 | 300 | # Tells whether we should check for unused import in __init__ files. 301 | init-import=no 302 | 303 | # List of qualified module names which can have objects that can redefine 304 | # builtins. 305 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io 306 | 307 | 308 | [FORMAT] 309 | 310 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 311 | expected-line-ending-format= 312 | 313 | # Regexp for a line that is allowed to be longer than the limit. 314 | ignore-long-lines=^\s*(# )??$ 315 | 316 | # Number of spaces of indent required inside a hanging or continued line. 317 | indent-after-paren=4 318 | 319 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 320 | # tab). 321 | indent-string=' ' 322 | 323 | # Maximum number of characters on a single line. 324 | max-line-length=100 325 | 326 | # Maximum number of lines in a module. 327 | max-module-lines=1000 328 | 329 | # List of optional constructs for which whitespace checking is disabled. `dict- 330 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. 331 | # `trailing-comma` allows a space between comma and closing bracket: (a, ). 332 | # `empty-line` allows space-only lines. 333 | no-space-check=trailing-comma, 334 | dict-separator 335 | 336 | # Allow the body of a class to be on the same line as the declaration if body 337 | # contains single statement. 338 | single-line-class-stmt=no 339 | 340 | # Allow the body of an if to be on the same line as the test if there is no 341 | # else. 342 | single-line-if-stmt=no 343 | 344 | 345 | [SIMILARITIES] 346 | 347 | # Ignore comments when computing similarities. 348 | ignore-comments=no 349 | 350 | # Ignore docstrings when computing similarities. 351 | ignore-docstrings=no 352 | 353 | # Ignore imports when computing similarities. 354 | ignore-imports=no 355 | 356 | # Minimum lines number of a similarity. 357 | min-similarity-lines=15 358 | 359 | 360 | [BASIC] 361 | 362 | # Naming style matching correct argument names. 363 | argument-naming-style=snake_case 364 | 365 | # Regular expression matching correct argument names. Overrides argument- 366 | # naming-style. 367 | #argument-rgx= 368 | 369 | # Naming style matching correct attribute names. 370 | attr-naming-style=snake_case 371 | 372 | # Regular expression matching correct attribute names. Overrides attr-naming- 373 | # style. 374 | #attr-rgx= 375 | 376 | # Bad variable names which should always be refused, separated by a comma. 377 | bad-names=foo, 378 | bar, 379 | baz, 380 | toto, 381 | tutu, 382 | tata 383 | 384 | # Naming style matching correct class attribute names. 385 | class-attribute-naming-style=any 386 | 387 | # Regular expression matching correct class attribute names. Overrides class- 388 | # attribute-naming-style. 389 | #class-attribute-rgx= 390 | 391 | # Naming style matching correct class names. 392 | class-naming-style=PascalCase 393 | 394 | # Regular expression matching correct class names. Overrides class-naming- 395 | # style. 396 | #class-rgx= 397 | 398 | # Naming style matching correct constant names. 399 | const-naming-style=UPPER_CASE 400 | 401 | # Regular expression matching correct constant names. Overrides const-naming- 402 | # style. 403 | #const-rgx= 404 | 405 | # Minimum line length for functions/classes that require docstrings, shorter 406 | # ones are exempt. 407 | docstring-min-length=-1 408 | 409 | # Naming style matching correct function names. 410 | function-naming-style=snake_case 411 | 412 | # Regular expression matching correct function names. Overrides function- 413 | # naming-style. 414 | #function-rgx= 415 | 416 | # Good variable names which should always be accepted, separated by a comma. 417 | good-names=i, 418 | j, 419 | k, 420 | ex, 421 | Run, 422 | _, 423 | x1, 424 | y1, 425 | x2, 426 | y2 427 | 428 | # Include a hint for the correct naming format with invalid-name. 429 | include-naming-hint=no 430 | 431 | # Naming style matching correct inline iteration names. 432 | inlinevar-naming-style=any 433 | 434 | # Regular expression matching correct inline iteration names. Overrides 435 | # inlinevar-naming-style. 436 | #inlinevar-rgx= 437 | 438 | # Naming style matching correct method names. 439 | method-naming-style=snake_case 440 | 441 | # Regular expression matching correct method names. Overrides method-naming- 442 | # style. 443 | #method-rgx= 444 | 445 | # Naming style matching correct module names. 446 | module-naming-style=snake_case 447 | 448 | # Regular expression matching correct module names. Overrides module-naming- 449 | # style. 450 | #module-rgx= 451 | 452 | # Colon-delimited sets of names that determine each other's naming style when 453 | # the name regexes allow several styles. 454 | name-group= 455 | 456 | # Regular expression which should only match function or class names that do 457 | # not require a docstring. 458 | no-docstring-rgx=^_ 459 | 460 | # List of decorators that produce properties, such as abc.abstractproperty. Add 461 | # to this list to register other decorators that produce valid properties. 462 | # These decorators are taken in consideration only for invalid-name. 463 | property-classes=abc.abstractproperty 464 | 465 | # Naming style matching correct variable names. 466 | variable-naming-style=snake_case 467 | 468 | # Regular expression matching correct variable names. Overrides variable- 469 | # naming-style. 470 | #variable-rgx= 471 | 472 | 473 | [STRING] 474 | 475 | # This flag controls whether the implicit-str-concat-in-sequence should 476 | # generate a warning on implicit string concatenation in sequences defined over 477 | # several lines. 478 | check-str-concat-over-line-jumps=no 479 | 480 | 481 | [IMPORTS] 482 | 483 | # Allow wildcard imports from modules that define __all__. 484 | allow-wildcard-with-all=no 485 | 486 | # Analyse import fallback blocks. This can be used to support both Python 2 and 487 | # 3 compatible code, which means that the block might have code that exists 488 | # only in one or another interpreter, leading to false positives when analysed. 489 | analyse-fallback-blocks=no 490 | 491 | # Deprecated modules which should not be used, separated by a comma. 492 | deprecated-modules=optparse,tkinter.tix 493 | 494 | # Create a graph of external dependencies in the given file (report RP0402 must 495 | # not be disabled). 496 | ext-import-graph= 497 | 498 | # Create a graph of every (i.e. internal and external) dependencies in the 499 | # given file (report RP0402 must not be disabled). 500 | import-graph= 501 | 502 | # Create a graph of internal dependencies in the given file (report RP0402 must 503 | # not be disabled). 504 | int-import-graph= 505 | 506 | # Force import order to recognize a module as part of the standard 507 | # compatibility libraries. 508 | known-standard-library= 509 | 510 | # Force import order to recognize a module as part of a third party library. 511 | known-third-party=enchant 512 | 513 | 514 | [CLASSES] 515 | 516 | # List of method names used to declare (i.e. assign) instance attributes. 517 | defining-attr-methods=__init__, 518 | __new__, 519 | setUp 520 | 521 | # List of member names, which should be excluded from the protected access 522 | # warning. 523 | exclude-protected=_asdict, 524 | _fields, 525 | _replace, 526 | _source, 527 | _make 528 | 529 | # List of valid names for the first argument in a class method. 530 | valid-classmethod-first-arg=cls 531 | 532 | # List of valid names for the first argument in a metaclass class method. 533 | valid-metaclass-classmethod-first-arg=cls 534 | 535 | 536 | [DESIGN] 537 | 538 | # Maximum number of arguments for function / method. 539 | max-args=7 540 | 541 | # Maximum number of attributes for a class (see R0902). 542 | max-attributes=12 543 | 544 | # Maximum number of boolean expressions in an if statement. 545 | max-bool-expr=5 546 | 547 | # Maximum number of branch for function / method body. 548 | max-branches=12 549 | 550 | # Maximum number of locals for function / method body. 551 | max-locals=18 552 | 553 | # Maximum number of parents for a class (see R0901). 554 | max-parents=7 555 | 556 | # Maximum number of public methods for a class (see R0904). 557 | max-public-methods=20 558 | 559 | # Maximum number of return / yield for function / method body. 560 | max-returns=6 561 | 562 | # Maximum number of statements in function / method body. 563 | max-statements=50 564 | 565 | # Minimum number of public methods for a class (see R0903). 566 | min-public-methods=2 567 | 568 | 569 | [EXCEPTIONS] 570 | 571 | # Exceptions that will emit a warning when being caught. Defaults to 572 | # "BaseException, Exception". 573 | overgeneral-exceptions=BaseException, 574 | Exception 575 | --------------------------------------------------------------------------------