Search code examples
pythonnltkchaquopy

What directory does chaquopy code search for the Python packages which are imported in the Python code of the Android app code


I have imported nltk library in my main method of the Python code of the chaquopy Android app. It is asking me to implement nltk.download('punkt') for my processing. So I wanted to know: in what directory does the code look for the packages, so that I can download a copy of them in the desired folder for my code to work right?

Edit: I implemented the solution provided by @mhsmith, but nltk.download('punkt') is still giving Lookup Error. Screenshots are attached:

The first line is the download_dir in which nltk.download('punkt') is downloading data

The first line is the download_dir in which nltk.download('punkt') is downloading data

This is the error I am getting even after implementing solution by @mhsmith

This is the error I am getting even after implementing solution by @mhsmith

This is the snippet of my code

This is the snippet of my code


Solution

  • Chaquopy 4.0.0 and newer

    These versions set the HOME environment variable to your app's files directory, and nltk will automatically create an nltk_data subdirectory there. So no special action is required.


    Chaquopy 3.3.2 and older

    I think the cleanest solution would be to create a separate directory for your downloads, like this:

    from com.chaquo.python import Python
    download_dir = "{}/nltk".format(Python.getPlatform().getApplication().getFilesDir())
    if not os.path.exists(download_dir):
        os.mkdir(download_dir)
    nltk.download(..., download_dir=download_dir)
    

    (The getPlatform method requires Chaquopy 3.2.0 or later.)

    From the NLTK documentation, it looks like you'll have to set the NLTK_DATA environment variable to this directory. This should probably be done before you import nltk.