Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSL: CERTIFICATE_VERIFY_FAILED #193

Open
jesford opened this issue May 28, 2020 · 5 comments
Open

SSL: CERTIFICATE_VERIFY_FAILED #193

jesford opened this issue May 28, 2020 · 5 comments

Comments

@jesford
Copy link

jesford commented May 28, 2020

I am getting an SSL Error trying to load ImageNet weights for the SEResNeXt50 & 101 models. Perhaps there is an expired certificate? Here is code to reproduce. Thanks in advance for your help, and many thanks for providing this package!

>>> import pretrainedmodels

>>> model_name = 'se_resnext101_32x4d'  # same for 'se_resnext50_32x4d'
>>> model = pretrainedmodels.__dict__[model_name](num_classes=1000, pretrained='imagenet')

Downloading: "http://data.lip6.fr/cadene/pretrainedmodels/se_resnext101_32x4d-3b2fe3d8.pth" to /root/.cache/torch/checkpoints/se_resnext101_32x4d-3b2fe3d8.pth
---------------------------------------------------------------------------
SSLError                                  Traceback (most recent call last)
/opt/conda/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1317                 h.request(req.get_method(), req.selector, req.data, headers,
-> 1318                           encode_chunked=req.has_header('Transfer-encoding'))
   1319             except OSError as err: # timeout error

/opt/conda/lib/python3.6/http/client.py in request(self, method, url, body, headers, encode_chunked)
   1261         """Send a complete request to the server."""
-> 1262         self._send_request(method, url, body, headers, encode_chunked)
   1263 

/opt/conda/lib/python3.6/http/client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1307             body = _encode(body, 'body')
-> 1308         self.endheaders(body, encode_chunked=encode_chunked)
   1309 

/opt/conda/lib/python3.6/http/client.py in endheaders(self, message_body, encode_chunked)
   1256             raise CannotSendHeader()
-> 1257         self._send_output(message_body, encode_chunked=encode_chunked)
   1258 

/opt/conda/lib/python3.6/http/client.py in _send_output(self, message_body, encode_chunked)
   1035         del self._buffer[:]
-> 1036         self.send(msg)
   1037 

/opt/conda/lib/python3.6/http/client.py in send(self, data)
    973             if self.auto_open:
--> 974                 self.connect()
    975             else:

/opt/conda/lib/python3.6/http/client.py in connect(self)
   1422             self.sock = self._context.wrap_socket(self.sock,
-> 1423                                                   server_hostname=server_hostname)
   1424             if not self._context.check_hostname and self._check_hostname:

/opt/conda/lib/python3.6/ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
    406                          server_hostname=server_hostname,
--> 407                          _context=self, _session=session)
    408 

/opt/conda/lib/python3.6/ssl.py in __init__(self, sock, keyfile, certfile, server_side, cert_reqs, ssl_version, ca_certs, do_handshake_on_connect, family, type, proto, fileno, suppress_ragged_eofs, npn_protocols, ciphers, server_hostname, _context, _session)
    816                         raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
--> 817                     self.do_handshake()
    818 

/opt/conda/lib/python3.6/ssl.py in do_handshake(self, block)
   1076                 self.settimeout(None)
-> 1077             self._sslobj.do_handshake()
   1078         finally:

/opt/conda/lib/python3.6/ssl.py in do_handshake(self)
    688         """Start the SSL/TLS handshake."""
--> 689         self._sslobj.do_handshake()
    690         if self.context.check_hostname:

SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
<ipython-input-13-1dd4c79befba> in <module>
----> 1 model = pretrainedmodels.__dict__[model_name](num_classes=1000, pretrained='imagenet')
      2 # model.eval()

/opt/conda/lib/python3.6/site-packages/pretrainedmodels/models/senet.py in se_resnext101_32x4d(num_classes, pretrained)
    439     if pretrained is not None:
    440         settings = pretrained_settings['se_resnext101_32x4d'][pretrained]
--> 441         initialize_pretrained_model(model, num_classes, settings)
    442     return model

/opt/conda/lib/python3.6/site-packages/pretrainedmodels/models/senet.py in initialize_pretrained_model(model, num_classes, settings)
    371         'num_classes should be {}, but is {}'.format(
    372             settings['num_classes'], num_classes)
--> 373     model.load_state_dict(model_zoo.load_url(settings['url']))
    374     model.input_space = settings['input_space']
    375     model.input_size = settings['input_size']

/opt/conda/lib/python3.6/site-packages/torch/hub.py in load_state_dict_from_url(url, model_dir, map_location, progress, check_hash)
    490         sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
    491         hash_prefix = HASH_REGEX.search(filename).group(1) if check_hash else None
--> 492         download_url_to_file(url, cached_file, hash_prefix, progress=progress)
    493 
    494     # Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand.

/opt/conda/lib/python3.6/site-packages/torch/hub.py in download_url_to_file(url, dst, hash_prefix, progress)
    389     # We use a different API for python2 since urllib(2) doesn't recognize the CA
    390     # certificates in older Python
--> 391     u = urlopen(url)
    392     meta = u.info()
    393     if hasattr(meta, 'getheaders'):

/opt/conda/lib/python3.6/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    221     else:
    222         opener = _opener
--> 223     return opener.open(url, data, timeout)
    224 
    225 def install_opener(opener):

/opt/conda/lib/python3.6/urllib/request.py in open(self, fullurl, data, timeout)
    530         for processor in self.process_response.get(protocol, []):
    531             meth = getattr(processor, meth_name)
--> 532             response = meth(req, response)
    533 
    534         return response

/opt/conda/lib/python3.6/urllib/request.py in http_response(self, request, response)
    640         if not (200 <= code < 300):
    641             response = self.parent.error(
--> 642                 'http', request, response, code, msg, hdrs)
    643 
    644         return response

/opt/conda/lib/python3.6/urllib/request.py in error(self, proto, *args)
    562             http_err = 0
    563         args = (dict, proto, meth_name) + args
--> 564         result = self._call_chain(*args)
    565         if result:
    566             return result

/opt/conda/lib/python3.6/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    502         for handler in handlers:
    503             func = getattr(handler, meth_name)
--> 504             result = func(*args)
    505             if result is not None:
    506                 return result

/opt/conda/lib/python3.6/urllib/request.py in http_error_302(self, req, fp, code, msg, headers)
    754         fp.close()
    755 
--> 756         return self.parent.open(new, timeout=req.timeout)
    757 
    758     http_error_301 = http_error_303 = http_error_307 = http_error_302

/opt/conda/lib/python3.6/urllib/request.py in open(self, fullurl, data, timeout)
    524             req = meth(req)
    525 
--> 526         response = self._open(req, data)
    527 
    528         # post-process response

/opt/conda/lib/python3.6/urllib/request.py in _open(self, req, data)
    542         protocol = req.type
    543         result = self._call_chain(self.handle_open, protocol, protocol +
--> 544                                   '_open', req)
    545         if result:
    546             return result

/opt/conda/lib/python3.6/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    502         for handler in handlers:
    503             func = getattr(handler, meth_name)
--> 504             result = func(*args)
    505             if result is not None:
    506                 return result

/opt/conda/lib/python3.6/urllib/request.py in https_open(self, req)
   1359         def https_open(self, req):
   1360             return self.do_open(http.client.HTTPSConnection, req,
-> 1361                 context=self._context, check_hostname=self._check_hostname)
   1362 
   1363         https_request = AbstractHTTPHandler.do_request_

/opt/conda/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1318                           encode_chunked=req.has_header('Transfer-encoding'))
   1319             except OSError as err: # timeout error
-> 1320                 raise URLError(err)
   1321             r = h.getresponse()
   1322         except:

URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)>
@AlxZed
Copy link

AlxZed commented May 29, 2020

Solution:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

@ValdemarQ
Copy link

Solution:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

This solution works well, solves the same problem on google colab
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

@mertguvencli
Copy link

Solution:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

I had a similar issue and @AlxZed's solution worked for me! Thanks 🚀

@ageron
Copy link

ageron commented Sep 26, 2022

Once more, the infamous SSL: CERTIFICATE_VERIFY_FAILED error has struck. Do not be tempted by the minions of the dark side! Do not turn off SSL verification: it's a trap! It will deactivate your protection shield. Nowhere will you be safe.

Instead, close your eyes and listen to the force. Let it guide you to the light. Open a terminal and run the following command:

/Applications/Python\ 3.10/Install\ Certificates.command

This will install the certifi bundle of root certificates and solve the problem without destroying all security.

If you installed Python using MacPorts, then run sudo port install curl-ca-bundle instead.

Now you can open your eyes. Feel the gentle tickle of the force running through you.

@Fzz123
Copy link

Fzz123 commented Sep 26, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants