folium icon indicating copy to clipboard operation
folium copied to clipboard

Folium doesn't package as expected when compiling to an executable

Open nathan3leaf opened this issue 7 years ago • 32 comments

Please add a code sample or a nbviewer link, copy-pastable if possible

import folium
from tkinter import *

class UserInterface:
	"""This is just a basic interface to enter coordinates to test the folium functionality"""

	def __init__(self):
		super(UserInterface,self).__init__()
		UserInterface.window = Tk()
		UserInterface.map_name_label = Label(UserInterface.window, text="Enter A Map Name")
		UserInterface.map_name_label.grid(row=0, column=0)
		UserInterface.map_name_text = StringVar()
		UserInterface.map_name_entry = Entry(UserInterface.window, textvariable=UserInterface.map_name_text)
		UserInterface.map_name_entry.grid(row=0, column=1)

		UserInterface.lat1label = Label(UserInterface.window, text="Point 1 Lat:")
		UserInterface.lat1label.grid(row=1, column=0)
		UserInterface.lat1text = StringVar()
		UserInterface.lat1_entry = Entry(UserInterface.window, textvariable=UserInterface.lat1text)
		UserInterface.lat1_entry.grid(row=1, column=1)

		UserInterface.long1label = Label(UserInterface.window, text="Point 1 Long:")
		UserInterface.long1label.grid(row=2, column=0)
		UserInterface.long1text = StringVar()
		UserInterface.lat1_entry = Entry(UserInterface.window, textvariable=UserInterface.long1text)
		UserInterface.lat1_entry.grid(row=2, column=1)

		UserInterface.lat2label = Label(UserInterface.window, text="Point 2 Lat:")
		UserInterface.lat2label.grid(row=3, column=0)
		UserInterface.lat2text = StringVar()
		UserInterface.lat2_entry = Entry(UserInterface.window, textvariable=UserInterface.lat2text)
		UserInterface.lat2_entry.grid(row=3, column=1)

		UserInterface.long2label = Label(UserInterface.window, text="Point 2 Long:")
		UserInterface.long2label.grid(row=4, column=0)
		UserInterface.long2text = StringVar()
		UserInterface.long2_entry = Entry(UserInterface.window, textvariable=UserInterface.long2text)
		UserInterface.long2_entry.grid(row=4, column=1)

		UserInterface.create_map_button = Button(UserInterface.window, text="Get Map", command=UserInterface.get_map, width=20)
		UserInterface.create_map_button.grid(row=5, columnspan=2)
		UserInterface.map_status = Label(UserInterface.window, text="")
		UserInterface.map_status.grid(row=6, column=0)
		UserInterface.window.mainloop()

	def get_map():
		UserInterface.map_status = Label(UserInterface.window, text="Getting map...")
		UserInterface.map_status.grid(row=6, column=0)
		centerpoint = [float(UserInterface.lat1text.get()), float(UserInterface.long1text.get())]
		marker = [float(UserInterface.lat2text.get()),float(UserInterface.long2text.get())]
		MapProgram.mapping.create_map(centerpoint=centerpoint, marker=marker)

class FoliumTest:
	"""This is just a basic class declaration to test the compiling process of folium when using Pyinstaller"""
	
	def __init__(self):
		super(FoliumTest,self).__init__()

	def create_map(self, centerpoint, marker):
		map_image = folium.Map(location=[centerpoint[0], centerpoint[1]], zoom_start=14, tiles='OpenStreetMap')
		centerpoint_icon_url = "http://maps.google.com/mapfiles/kml/shapes/star.png"
		centerpoint_icon = folium.features.CustomIcon(centerpoint_icon_url, icon_size=(70,70))
		folium.Marker([centerpoint[0], centerpoint[1]], icon=centerpoint_icon).add_to(map_image)
		custom_map_icon_url = "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"
		custom_map_icon = folium.features.CustomIcon(custom_map_icon_url, icon_size=(50,50))
		folium.Marker([marker[0], marker[1]], icon=custom_map_icon).add_to(map_image)
		map_image.save(outfile=UserInterface.map_name_text.get() + ".html")
		UserInterface.map_status = Label(UserInterface.window, text="Map created!")
		UserInterface.map_status.grid(row=6, column=0)

class MapProgram:
	"""This sets up the interface with the mapping functionality"""

	def __init__(self):
		MapProgram.mapping = FoliumTest()
		UserInterface()
		#Optional Coords to use for testing
		#centerpoint = [37.9969,-121.2919]
		#marker = [38.0132,-121.3671])

def main():
	MapProgram()
	
if __name__ == '__main__':
	main()

Problem description

When attempting to make an exe using pyinstaller, cx_freeze, py2exe etc, the folium module and its dependencies don't seem to get compiled properly so that the program can run successfully. In the process of trying to determine where the core problem resided, I came across unexpected behavior when typing from folium import * which resulted in an error AttributeError: module 'folium' has no attribute 'GeoJsonStyle' This seemed odd to me and I thought possibly why the exe is not being compiled as it would throw the error that _cnames.json could not be found, which makes sense if GeoJsonStyle doesn't exist in the module but perhaps it's supposed to. If I attempt to compile the above program, but comment out folium, the compiled executable runs fine, so I know it's related to folium specifically.

Expected Output

I expected the module to compile and load correctly so that it can be utilized in an executable.

Output of folium.__version__

0.7.0

nathan3leaf avatar Mar 06 '19 21:03 nathan3leaf

I expected the module to compile and load correctly so that it can be utilized in an executable.

I don't know any of those tools and I'm not familiar with the process of creating an exe. All I can say is that, if folium is properly installed, it should work :grimacing:

With that said, if you can provide any details of those tools and its limitations/expectations of a package it would help us debug this. I Google about some of them and it seems that there are a number of limitations!

Closing this b/c folium does not aim to be made into an exe. We can still discuss in this thread to figure out why and, if the solution is simple, implement a fix for it.

ocefpaf avatar Mar 06 '19 21:03 ocefpaf

@ocefpaf Ok let's forget the exe issue for now.

Is it problematic that from folium import * would throw an error? And if it is problematic, could that have been caused by something on my end?

nathan3leaf avatar Mar 06 '19 21:03 nathan3leaf

@ocefpaf Ok let's forget the exe issue for now.

OK.

Is it problematic that from folium import * would throw an error?

Problematic? Yes. I could not reproduce that with folium 0.8.0 (latest) I'm guessing that is a bug that was fixed in 0.7.0.

And if it is problematic, could that have been caused by something on my end?

You probably just need an update.

ocefpaf avatar Mar 06 '19 22:03 ocefpaf

Upgraded fine and from folium import * no longer throws an error.

It seems that one of the dependencies of folium is branca, is that correct or am I mistaken? The error that I see when I run my exe refers to a file called _cnames.json which is in the site-packages/branca folder. Could this potentially be a branca issue or is there something about how folium 'talks' to branca that could be an issue? Pardon my understanding of this, I'm still very new to Python and coding and just trying to learn how to properly track down problems that I encounter. I appreciate your help.

nathan3leaf avatar Mar 06 '19 22:03 nathan3leaf

Upgraded fine and from folium import * no longer throws an error.

:tada:

It seems that one of the dependencies of folium is branca, is that correct or am I mistaken?

That is correct.

The error that I see when I run my exe refers to a file called _cnames.json which is in the site-packages/branca folder. Could this potentially be a branca issue or is there something about how folium 'talks' to branca that could be an issue?

It is probably a branca issue but we need to understand what these exe creators "want" to fix it.

Pardon my understanding of this, I'm still very new to Python and coding and just trying to learn how to properly track down problems that I encounter. I appreciate your help.

No problem. I do recommend you to move this discussion to branca though.

ocefpaf avatar Mar 06 '19 22:03 ocefpaf

Gotcha, I'll head over to branca. Thanks!

nathan3leaf avatar Mar 06 '19 22:03 nathan3leaf

Hi @nathan3leaf, No problem for me to build an exe using folium with cx_freeze. Could you copy/paste the setup.py file you are using in order to find out what's going wrong ?

FabeG avatar Mar 07 '19 13:03 FabeG

@FabeG This is what I have, which builds but crashes immediately when running the exe. Any guidance you can offer as to what else I need to add to this would be much appreciated.

from cx_Freeze import setup, Executable
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os","pandas","numpy","idna","branca","jinja2","matplotlib"]}

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
    base = "Win32GUI"

options = {
    'build_exe': {
        'include_files':[
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),
         ],
    },
}

setup(  name = "projectName",
        version = "0.1",
        description = "My program",
        options = {"build_exe": build_exe_options},
        executables = [Executable("projectName.py", base=base)])```

nathan3leaf avatar Mar 07 '19 15:03 nathan3leaf

@nathan3leaf could you try to add in the list of packages "pkg_resources" ?

build_exe_options = {"packages": ["pkg_resources", "os","pandas","numpy","idna","branca","jinja2","matplotlib"]}

FabeG avatar Mar 07 '19 16:03 FabeG

@FabeG I gave it a shot and got this 2019-03-07

This is actually the same error I've been receiving when using cx_freeze, so it's getting tripped up in the same spot.

nathan3leaf avatar Mar 07 '19 17:03 nathan3leaf

@nathan3leaf I had to add also asyncio in the list of packages, could you try it ?

FabeG avatar Mar 07 '19 17:03 FabeG

@FabeG I tried that and am now getting the error that stumps me when I use pyinstaller, which seems related to pkg_resources, which I did add to the setup file.

image

nathan3leaf avatar Mar 07 '19 17:03 nathan3leaf

  • Does the file color_scale.js exists in install_dir / 'folium' / 'lib' / 'branca' / 'templates' ?
  • what version of setuptools are you using ?
import setuptools
print(setuptools.__version__)
  • what version of cx_freeze are you using ?
import cx_freeze
print(cx_freeze.__version__)

FabeG avatar Mar 07 '19 17:03 FabeG

@FabeG yes, the color_scale.js file is residing in that folder setuptools version 39.0.1 cx_freeze version 5.1.1

nathan3leaf avatar Mar 07 '19 17:03 nathan3leaf

I see now that my setuptools may be out of date

nathan3leaf avatar Mar 07 '19 17:03 nathan3leaf

I updated setuptools and no longer see the traceback related to pkg_resources or asyncio. However, in my script I have these lines:

def resource_path(relative_path): 
	try: 
		base_path = sys._MEIPASS
	except Exception:
		base_path = os.path.abspath(".")
	return os.path.join(base_path, relative_path)

homeDir = resource_path(os.path.dirname(os.path.abspath(__file__)))

which apparently it doesn't like because now I get an error that __file__ is not defined I haven't seen this error before so I'm unsure how to resolve it, considering it has been working up until this point, at least when I made an exe that excluded folium

nathan3leaf avatar Mar 07 '19 18:03 nathan3leaf

Seems you are about to solve your problem: for a frozen exe, you have to use sys.executable instead of __file__:

if getattr(sys, 'frozen', False):
    # The application is frozen
    datadir = os.path.dirname(sys.executable)
else:
    # The application is not frozen
    datadir = os.path.dirname(__file__)

FabeG avatar Mar 07 '19 19:03 FabeG

@FabeG Well I can't thank you enough for your patience and knowledge. My executable is FINALLY running when using folium. I've had to comment it out for months because I could never get it to run correctly, so this is actually a pretty big deal to me. Thanks so much!

nathan3leaf avatar Mar 07 '19 20:03 nathan3leaf

I updated setuptools and no longer see the traceback related to pkg_resources or asyncio. However, in my script I have these lines:

def resource_path(relative_path): 
	try: 
		base_path = sys._MEIPASS
	except Exception:
		base_path = os.path.abspath(".")
	return os.path.join(base_path, relative_path)

homeDir = resource_path(os.path.dirname(os.path.abspath(__file__)))

which apparently it doesn't like because now I get an error that __file__ is not defined I haven't seen this error before so I'm unsure how to resolve it, considering it has been working up until this point, at least when I made an exe that excluded folium

I updated setuptools and no longer see the traceback related to pkg_resources or asyncio. However, in my script I have these lines:

def resource_path(relative_path): 
	try: 
		base_path = sys._MEIPASS
	except Exception:
		base_path = os.path.abspath(".")
	return os.path.join(base_path, relative_path)

homeDir = resource_path(os.path.dirname(os.path.abspath(__file__)))

which apparently it doesn't like because now I get an error that __file__ is not defined I haven't seen this error before so I'm unsure how to resolve it, considering it has been working up until this point, at least when I made an exe that excluded folium

Could you please tell me the file name to add the code is it console.py or startup.py

Uzair919 avatar May 30 '19 16:05 Uzair919

The last few code samples above were all added to my main project file, which of course would be different for you. However, the setup.py file which needs to be created in order to use cx_freeze, is also referenced above, which I've pasted below.

from cx_Freeze import setup, Executable import os.path PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.file)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')

Dependencies are automatically detected, but it might need fine tuning.

build_exe_options = {"packages": ["os","pandas","numpy","idna","branca","jinja2","matplotlib"]}

GUI applications require a different base on Windows (the default is for a

console application).

base = None if sys.platform == "win32": base = "Win32GUI"

options = { 'build_exe': { 'include_files':[ os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'), os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'), ], }, }

setup( name = "projectName", version = "0.1", description = "My program", options = {"build_exe": build_exe_options}, executables = [Executable("projectName.py", base=base)])```

nathan3leaf avatar May 30 '19 16:05 nathan3leaf