Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use importlib in favor of deprecated pkg_resources #5048

Merged
merged 16 commits into from
Aug 1, 2023
5 changes: 5 additions & 0 deletions .changeset/fine-ways-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"gradio": minor
---

feat:Use `importlib` in favor of deprecated `pkg_resources`
45 changes: 27 additions & 18 deletions gradio/cli_env_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,37 @@
for the cli command 'gradio environment'
"""
import platform

import pkg_resources
from importlib import metadata


def print_environment_info():
print("Gradio Environment Information:")

print("Operating System: ", platform.system())
print("\n")
print("Gradio Environment Information:\n------------------------------")
print("Operating System:", platform.system())

for package_name in ["gradio", "gradio_client"]:
try:
package_dist = pkg_resources.get_distribution(package_name)
package_version = package_dist.version
print(f"{package_name} version: ", package_version)

print(f"\n{package_name} Dependencies:")
for req in package_dist.requires():
print(
f" {req.project_name}: {pkg_resources.get_distribution(req.project_name).version}"
)

print("\n")
except pkg_resources.DistributionNotFound:
package_version = metadata.version(package_name)
print(f"{package_name} version:", package_version)
except metadata.PackageNotFoundError:
print(f"{package_name} package is not installed.")
print("\n------------------------------------------------")
for package_name in ["gradio", "gradio_client"]:
try:
dist = metadata.distribution(package_name)
print(f"{package_name} dependencies in your environment:\n")
if dist.requires is not None:
for req in dist.requires:
req_base_name = (
req.split(">")[0]
.split("<")[0]
.split("~")[0]
.split("[")[0]
.split("!")[0]
)
try:
print(f"{req_base_name}: {metadata.version(req_base_name)}")
except metadata.PackageNotFoundError:
print(f"{req_base_name} is not installed.")
print("\n")
except metadata.PackageNotFoundError:
print(f"{package_name} package is not installed.")
12 changes: 0 additions & 12 deletions gradio/flagging.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@
import uuid
from abc import ABC, abstractmethod
from collections import OrderedDict
from distutils.version import StrictVersion
from pathlib import Path
from typing import TYPE_CHECKING, Any

import filelock
import huggingface_hub
import pkg_resources
from gradio_client import utils as client_utils
from gradio_client.documentation import document, set_documentation_group

Expand Down Expand Up @@ -242,16 +240,6 @@ def setup(self, components: list[IOComponent], flagging_dir: str):
flagging_dir (str): local directory where the dataset is cloned,
updated, and pushed from.
"""
hh_version = pkg_resources.get_distribution("huggingface_hub").version
try:
if StrictVersion(hh_version) < StrictVersion("0.12.0"):
raise ImportError(
"The `huggingface_hub` package must be version 0.12.0 or higher"
"for HuggingFaceDatasetSaver. Try 'pip install huggingface_hub --upgrade'."
)
except ValueError:
pass

# Setup dataset on the Hub
self.dataset_id = huggingface_hub.create_repo(
repo_id=self.dataset_id,
Expand Down
2 changes: 1 addition & 1 deletion gradio/processing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def _convert(image, dtype, force_copy=False, uniform=False):
dtype_range = {
bool: (False, True),
np.bool_: (False, True),
np.bool8: (False, True),
np.bool8: (False, True), # type: ignore
float: (-1, 1),
np.float_: (-1, 1),
np.float16: (-1, 1),
Expand Down
17 changes: 10 additions & 7 deletions gradio/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
from __future__ import annotations

import asyncio
import sys

if sys.version_info >= (3, 9):
from importlib.resources import files
else:
from importlib_resources import files
jayceslesar marked this conversation as resolved.
Show resolved Hide resolved
import inspect
import json
import mimetypes
Expand All @@ -23,7 +29,6 @@
import httpx
import markupsafe
import orjson
import pkg_resources
from fastapi import Depends, FastAPI, File, HTTPException, UploadFile, WebSocket, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import (
Expand Down Expand Up @@ -52,12 +57,10 @@

mimetypes.init()

STATIC_TEMPLATE_LIB = pkg_resources.resource_filename("gradio", "templates/")
STATIC_PATH_LIB = pkg_resources.resource_filename("gradio", "templates/frontend/static")
BUILD_PATH_LIB = pkg_resources.resource_filename("gradio", "templates/frontend/assets")
VERSION_FILE = pkg_resources.resource_filename("gradio", "version.txt")
with open(VERSION_FILE) as version_file:
VERSION = version_file.read()
STATIC_TEMPLATE_LIB = files("gradio").joinpath("templates").as_posix() # type: ignore
STATIC_PATH_LIB = files("gradio").joinpath("templates", "frontend", "static").as_posix() # type: ignore
BUILD_PATH_LIB = files("gradio").joinpath("templates", "frontend", "assets").as_posix() # type: ignore
VERSION = files("gradio").joinpath("version.txt").read_text()


class ORJSONResponse(JSONResponse):
Expand Down
4 changes: 2 additions & 2 deletions gradio/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def colab_check() -> bool:
"""
is_colab = False
try: # Check if running interactively using ipython.
from IPython import get_ipython
from IPython.core.getipython import get_ipython

from_ipynb = get_ipython()
if "google.colab" in str(from_ipynb):
Expand Down Expand Up @@ -97,7 +97,7 @@ def ipython_check() -> bool:
"""
is_ipython = False
try: # Check if running interactively using ipython.
from IPython import get_ipython
from IPython.core.getipython import get_ipython

if get_ipython() is not None:
is_ipython = True
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ ffmpy
gradio_client>=0.3.0
httpx
huggingface_hub>=0.14.0
importlib_resources>=1.3,<7.0
Jinja2<4.0
markdown-it-py[linkify]>=2.0.0
mdit-py-plugins<=0.3.3
Expand Down