face_recognition: Freeze your script with Pyinstaller

Hi, You might want to freeze your script into a standalone executable to run on any system without the need of installing python or face_recognition and maybe you want to create a demo for your application and want to give it to someone else without giving your source code. Here is a simple tutorial to do that. I tested this method with python3.6 on Windows 10, but I think you can get it working on Linux with a similar method.

  1. Make sure you have correctly installed both face_recognition and dlib and you see no error when importing them into your script.
  2. Make sure your script works fine, and all its dependencies are right next to it, and you can run it fine with python yourscript.py.
  3. Install Pyinstaller with pip: pip install pyinstaller
  4. Create a new directory and move your python script and all dependencies into it. I call it myproject and myscript.py
  5. Copy face_recognition_models and scipy-extra-dll from your python installed directory to your project directory.
  6. Create an empty file called <yourscriptname>.spec like myscript.spec next to your python script.
  7. Use below Pyinstaller spec file sample and edit some parts according to your needs: (I mark it with <> tag)
# -*- mode: python -*-

block_cipher = None

face_models = [
('.\\face_recognition_models\\models\\dlib_face_recognition_resnet_model_v1.dat', './face_recognition_models/models'),
('.\\face_recognition_models\\models\\mmod_human_face_detector.dat', './face_recognition_models/models'),
('.\\face_recognition_models\\models\\shape_predictor_5_face_landmarks.dat', './face_recognition_models/models'),
('.\\face_recognition_models\\models\\shape_predictor_68_face_landmarks.dat', './face_recognition_models/models'),
]

a = Analysis(['<your python script name.py>'],
             pathex=['<path to working directory>'],
             binaries=face_models,
             datas=[],
             hiddenimports=['scipy._lib.messagestream', 'scipy', 'scipy.signal', 'scipy.signal.bsplines', 'scipy.special', 'scipy.special._ufuncs_cxx',
                            'scipy.linalg.cython_blas',
                            'scipy.linalg.cython_lapack',
                            'scipy.integrate',
                            'scipy.integrate.quadrature',
                            'scipy.integrate.odepack',
                            'scipy.integrate._odepack',
                            'scipy.integrate.quadpack',
                            'scipy.integrate._quadpack',
                            'scipy.integrate._ode',
                            'scipy.integrate.vode',
                            'scipy.integrate._dop', 'scipy._lib', 'scipy._build_utils','scipy.__config__',
                            'scipy.integrate.lsoda', 'scipy.cluster', 'scipy.constants','scipy.fftpack','scipy.interpolate','scipy.io','scipy.linalg','scipy.misc','scipy.ndimage','scipy.odr','scipy.optimize','scipy.setup','scipy.sparse','scipy.spatial','scipy.special','scipy.stats','scipy.version'],

             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

a.datas += Tree('./scipy-extra-dll', prefix=None)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='<your python script name>',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

  1. Generate your executable with python -m pyinstaller myscript.spec
  2. If you see no error then your executable can be found in dist directory.
  3. Enjoy!

Thanks to @ageitgey and @davisking for their awesome work.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 49
  • Comments: 56 (1 by maintainers)

Most upvoted comments

@sincerefly Hi, If I remember correctly there are some examples that need scipy so if you are using scipy with your project you need those files but if you don’t, just use face_models no need for hidden imports that is it. And remember you just need to first freeze your script normally and if you got any errors about missing packages, you need to feed them manually in your spec file.

I found this worked very well when running on Windows desktop, but the application would crash on Windows Server 2012 - 2016 with an unhelpful, vague unable to execute DLL error. I found this issue was caused by using the latest version of dlib linked in the project install guide under issue 175 (currently 19.9.99). However, by using ‘pip install dlib’, which installs 19.9.0 (again, currently as of writing this). The frozen executable is running without errors on both desktop and server. I’ve also been testing freezing this in both 32-bit and 64-bit python and both are working. Thanks

thanks for sharing your knowledge…i can’t find scipy-extra-dll …how i can to find them in python directory??i am in ubuntu 16.04, thank you in advance

Cool, thanks for sharing!

I am having this output after freezing my code with this .spec file below. When I run my app on console on Linux I get this:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "/home/neo/Desktop/faseez/dev/refasee/venv/lib/python3.6/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "face_recognition/__init__.py", line 7, in <module>
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "/home/neo/Desktop/faseez/dev/refasee/venv/lib/python3.6/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "face_recognition/api.py", line 20, in <module>
RuntimeError: Unable to open /tmp/_MEIHAOamS/face_recognition_models/models/shape_predictor_68_face_landmarks.dat
[11437] Failed to execute script main

Fascee.spec.txt

@HAKANMAZI Try to run executable with CMD and you should get the error in the console. Then put the error.

Thanks @masoudr ; output error below, error says me No module named ‘sklearn’. Yes true there is no sklearn because I don’t use it. Even if when I run my .py file there is no error. But when I change from .py to .exe file it saying No module named ‘sklearn’. Why ?

raceback (most recent call last): File “C:\Users\HH\Desktop\python\exe\test.py”, line 94, in openCamera() File “C:\Users\HH\Desktop\python\exe\test.py”, line 66, in openCamera predictions = predict(facePath, model_path=model_path) File “C:\Users\HH\Desktop\python\exe\test.py”, line 30, in predict knn_clf = pickle.load(f) ModuleNotFoundError: No module named ‘sklearn’ [14372] Failed to execute script test [ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback

Finally I solved my problem. As I said I don’t use sklearn on my code but background sklearn was using. Then I add in hiddenimports=[‘sklearn’,‘sklearn.neighbors._typedefs’,‘sklearn.utils._cython_blas’] in my spec file. and it is okey, it solved 😃

@HAKANMAZI Try to run executable with CMD and you should get the error in the console. Then put the error.

I can’t find the scipy-extra-dll in windows although I installed scipy. Help me.

You can search extra-dll using below code on cmd dir extra-dll /s /p I hope you will find it in scipy directory. After create scipy-extra-dll directory. Then all dll files transfer to scipy-extra-dll directory.

image

can you help me for this error ? i already have face-recognition-models while i check with pip freeze. and i already create and execute the attendance.spec. please help me. Thank You

try to copy the dependencies that open fail to your output dependencies dir, its helpful for me

@masoudr

I’m not find scipy-extra-dll in my site-packages, should I need install scipy?

1, when I am not install scipy, I can run face_recognition, Is scipy necessary? 2, I install scipy, and copy scipy dir from site-packages to project dir, with a.datas += Tree('./scipy-extra-dll', prefix=None), I can’t find scipy-extra-dll, but I find extra-dll in scipy dir, can I write scipy/extra-dll instead it or not

thank you

i replaced datas=[] with datas=[(‘shape_predictor_68_face_landmarks.dat’,‘./face_recognition_models/models’),(‘shape_predictor_5_face_landmarks.dat’,‘./face_recognition_models/models’),(‘mmod_human_face_detector.dat’,‘./face_recognition_models/models’),(‘dlib_face_recognition_resnet_model_v1.dat’,‘./face_recognition_models/models’)] that works,thanks

Thanks! It works