|
| 1 | +import { kw, python, PythonError } from "../mod.ts"; |
| 2 | + |
| 3 | +import { join } from "https://deno.land/std@0.198.0/path/mod.ts"; |
| 4 | +import { ensureDir } from "https://deno.land/std@0.198.0/fs/mod.ts"; |
| 5 | +import { green, yellow } from "https://deno.land/std@0.198.0/fmt/colors.ts"; |
| 6 | + |
| 7 | +import type { CacheLocation } from "https://deno.land/x/plug@1.0.2/types.ts"; |
| 8 | +import { ensureCacheLocation } from "https://deno.land/x/plug@1.0.2/download.ts"; |
| 9 | +import { hash } from "https://deno.land/x/plug@1.0.2/util.ts"; |
| 10 | + |
| 11 | +const sys = python.import("sys"); |
| 12 | +const runpy = python.import("runpy"); |
| 13 | +const importlib = python.import("importlib"); |
| 14 | + |
| 15 | +// https://packaging.python.org/en/latest/specifications/name-normalization/ |
| 16 | +const MODULE_REGEX = |
| 17 | + /^([a-z0-9]|[a-z0-9][a-z0-9._-]*[a-z0-9])([^a-z0-9._-].*)?$/i; |
| 18 | + |
| 19 | +function normalizeModuleName(name: string) { |
| 20 | + return name.replaceAll(/[-_.]+/g, "-").toLowerCase(); |
| 21 | +} |
| 22 | + |
| 23 | +function getModuleNameAndVersion(module: string): { |
| 24 | + name: string; |
| 25 | + version?: string; |
| 26 | +} { |
| 27 | + const match = module.match(MODULE_REGEX); |
| 28 | + const name = match?.[1]; |
| 29 | + const version = match?.[2]; |
| 30 | + |
| 31 | + if (name == null) { |
| 32 | + throw new TypeError("Could not match any valid pip module name"); |
| 33 | + } |
| 34 | + |
| 35 | + return { |
| 36 | + name: normalizeModuleName(name), |
| 37 | + version, |
| 38 | + }; |
| 39 | +} |
| 40 | + |
| 41 | +export class Pip { |
| 42 | + #cacheLocation: Promise<string>; |
| 43 | + |
| 44 | + constructor(location: CacheLocation) { |
| 45 | + this.#cacheLocation = Promise.all([ |
| 46 | + ensureCacheLocation(location), |
| 47 | + globalThis.location !== undefined |
| 48 | + ? hash(globalThis.location.href) |
| 49 | + : Promise.resolve("pip"), |
| 50 | + ]).then(async (parts) => { |
| 51 | + const cacheLocation = join(...parts); |
| 52 | + await ensureDir(cacheLocation); |
| 53 | + |
| 54 | + if (!(cacheLocation in sys.path)) { |
| 55 | + sys.path.insert(0, cacheLocation); |
| 56 | + } |
| 57 | + |
| 58 | + return cacheLocation; |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Install a Python module using the `pip` package manager. |
| 64 | + * |
| 65 | + * @param module The Python module which you wish to install |
| 66 | + * |
| 67 | + * @example |
| 68 | + * ```ts |
| 69 | + * import { python } from "https://deno.land/x/python/mod.ts"; |
| 70 | + * import { install } from "https://deno.land/x/python/ext/pip.ts"; |
| 71 | + * |
| 72 | + * await install("numpy"); |
| 73 | + * const numpy = python.import("numpy"); |
| 74 | + * |
| 75 | + * ``` |
| 76 | + */ |
| 77 | + async install(module: string) { |
| 78 | + const argv = sys.argv; |
| 79 | + sys.argv = [ |
| 80 | + "pip", |
| 81 | + "install", |
| 82 | + "-q", |
| 83 | + "-t", |
| 84 | + await this.#cacheLocation, |
| 85 | + module, |
| 86 | + ]; |
| 87 | + |
| 88 | + console.log(`${green("Installing")} ${module}`); |
| 89 | + |
| 90 | + try { |
| 91 | + runpy.run_module("pip", kw`run_name=${"__main__"}`); |
| 92 | + } catch (error) { |
| 93 | + if ( |
| 94 | + !( |
| 95 | + error instanceof PythonError && |
| 96 | + error.type.isInstance(python.builtins.SystemExit()) && |
| 97 | + error.value.asLong() === 0 |
| 98 | + ) |
| 99 | + ) { |
| 100 | + throw error; |
| 101 | + } |
| 102 | + } finally { |
| 103 | + sys.argv = argv; |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + /** |
| 108 | + * Install and import a Python module using the `pip` package manager. |
| 109 | + * |
| 110 | + * @param module The Python module which you wish to install |
| 111 | + * |
| 112 | + * @example |
| 113 | + * ```ts |
| 114 | + * import { python } from "https://deno.land/x/python/mod.ts"; |
| 115 | + * import { pip } from "https://deno.land/x/python/ext/pip.ts"; |
| 116 | + * |
| 117 | + * const numpy = await pip.import("numpy==1.25.2"); |
| 118 | + * |
| 119 | + * ``` |
| 120 | + */ |
| 121 | + async import(module: string, entrypoint?: string) { |
| 122 | + const { name } = getModuleNameAndVersion(module); |
| 123 | + |
| 124 | + await this.install(module); |
| 125 | + |
| 126 | + if (entrypoint) { |
| 127 | + return python.import(entrypoint); |
| 128 | + } |
| 129 | + |
| 130 | + const packages = importlib.metadata.packages_distributions(); |
| 131 | + const entrypoints = []; |
| 132 | + |
| 133 | + for (const entry of packages) { |
| 134 | + if (packages[entry].valueOf().includes(name)) { |
| 135 | + entrypoints.push(entry.valueOf()); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + if (entrypoints.length === 0) { |
| 140 | + throw new TypeError( |
| 141 | + `Failed to import module ${module}, could not find import name ${name}`, |
| 142 | + ); |
| 143 | + } |
| 144 | + |
| 145 | + entrypoint = entrypoints[0]; |
| 146 | + |
| 147 | + if (entrypoints.length > 1) { |
| 148 | + if (entrypoints.includes(name)) { |
| 149 | + entrypoint = entrypoints[entrypoints.indexOf(name)]; |
| 150 | + } else { |
| 151 | + console.warn( |
| 152 | + `${ |
| 153 | + yellow( |
| 154 | + "Warning", |
| 155 | + ) |
| 156 | + } could not determine a single entrypoint for module ${module}, please specify one of: ${ |
| 157 | + entrypoints.join( |
| 158 | + ", ", |
| 159 | + ) |
| 160 | + }. Importing ${entrypoint}`, |
| 161 | + ); |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + return python.import(entrypoint!); |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +export const pip = new Pip(); |
| 170 | +export default pip; |
0 commit comments