Pierre-olivier Gendraud
Pierre-olivier Gendraud

Reputation: 1927

How to install a python package in jupiter server defined with a flake.nix

I want to follow this tutorial on colab. But I don't want to create a google account to execute the code.

I've created a jupiter server with nix.

flake.nix:

{
  inputs = {
    nixpkgs = {
      url = "github:nixos/nixpkgs/nixos-unstable";
    };
    flake-utils = {
      url = "github:numtide/flake-utils";
    };
  };
  outputs = { nixpkgs, flake-utils, ... }: flake-utils.lib.eachDefaultSystem (system:
    let
      pkgs = import nixpkgs {
        inherit system;
      };
    in rec {
      devShell = pkgs.mkShell {
        buildInputs = with pkgs; [
          (python3.withPackages(ps: with ps; [
            ipython
            matplotlib
            tensorflow
            python3Packages.opencv4
            python3Packages.pip
            pillow
            scipy
          ]))
        ];
        shellHook = "jupyter notebook";
      };
    }
  );
}

and then the following bash command

nix develop

I've opened the url and created a notebook. copy paste the first cell.

!pip install -q xplique

import numpy as np
from matplotlib import pyplot as plt
import tensorflow as tf
from math import ceil
import cv2

%matplotlib inline
%config InlineBackend.figure_format='retina'

import xplique
from xplique.plots import plot_attributions

ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/nix/store/a7k1ggpnhsrzpfcsw3dyw12kzl7j2vq5-python3-3.10.10-env/lib/python3.10/site-packages/tifffile' Check the permissions.

Upvotes: 0

Views: 491

Answers (1)

kbmz
kbmz

Reputation: 123

If you must use pip, which seems to be the case since xplique is not packaged in nixpkgs, you can combine nix and virtualenv:

{
  inputs = {
    nixpkgs = {
      url = "github:nixos/nixpkgs/nixos-unstable";
    };
    flake-utils = {
      url = "github:numtide/flake-utils";
    };
  };
  outputs = { nixpkgs, flake-utils, ... }: flake-utils.lib.eachDefaultSystem (system:
    let
      pkgs = import nixpkgs {
        inherit system;
      };
    in rec {
      devShell = pkgs.mkShell {
        buildInputs = with pkgs; [
          (python3.withPackages(ps: with ps; [
            ipython
            matplotlib
            tensorflow
            python3Packages.opencv4
            python3Packages.pip
            pillow
            scipy
          ]))
        ];
        shellHook = ''if [ ! -d ".venv" ]; then
            python3 -m venv .venv;
            fi
            source .venv/bin/activate;
            jupyter notebook'';
      };
    }
  );
}

To your shell hook, I just added four lines that enter a virtual environment, creating one if it does not exist.

Upvotes: 0

Related Questions