Skip to content

Commit

Permalink
clean-deprecated-parameters (#1090)
Browse files Browse the repository at this point in the history
* clean-deprecated-parameters

- resolve conflicts

* clean-deprecated-parameters

- fix tests

* clean-deprecated-parameters

- fix tests

* clean-deprecated-parameters

- resolve conflicts

* clean-deprecated-parameters

- refactor blocks.py

* clean-deprecated-parameters

- remove capture_session support

* clean-deprecated-parameters

- fix get_component_instance

* clean-deprecated-parameters

- fix tests

* clean-deprecated-parameters

- reformat

* clean-deprecated-parameters

- fix tests

* clean-deprecated-parameters

- fix tests

* clean-deprecated-parameters

- resolve conflicts

* clean-deprecated-parameters

- resolve conflicts

* Update gradio/deprecation.py

* Update gradio/deprecation.py

* Update gradio/deprecation.py

* removed some incorrect kwargs

* formatting

Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
  • Loading branch information
omerXfaruq and abidlabs authored Apr 28, 2022
1 parent f856869 commit 930c4a3
Show file tree
Hide file tree
Showing 13 changed files with 113 additions and 1,589 deletions.
3 changes: 1 addition & 2 deletions gradio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@
HuggingFaceDatasetSaver,
SimpleCSVLogger,
)
from gradio.interface import Interface, TabbedInterface, close_all, reset_all
from gradio.interface import Interface, TabbedInterface, close_all
from gradio.mix import Parallel, Series
from gradio.routes import get_state, set_state

current_pkg_version = pkg_resources.require("gradio")[0].version
__version__ = current_pkg_version
22 changes: 13 additions & 9 deletions gradio/blocks.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
from __future__ import annotations

import enum
import getpass
import os
import sys
import time
import warnings
import webbrowser
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple

from gradio import encryptor, networking, queueing, strings, utils
from gradio.context import Context
from gradio.deprecation import check_deprecated_parameters

if TYPE_CHECKING: # Only import for type checking (is False at runtime).
from fastapi.applications import FastAPI
Expand All @@ -19,11 +20,13 @@


class Block:
def __init__(self, without_rendering=False, css=None):
def __init__(self, without_rendering=False, css=None, **kwargs):
self._id = None
self.css = css if css is not None else {}
if without_rendering:
return
self.render()
check_deprecated_parameters(self.__class__.__name__, **kwargs)

def render(self):
"""
Expand All @@ -35,7 +38,6 @@ def render(self):
Context.block.children.append(self)
if Context.root_block is not None:
Context.root_block.blocks[self._id] = self
self.events = []

def get_block_name(self) -> str:
"""
Expand Down Expand Up @@ -96,13 +98,15 @@ def set_event_trigger(


class BlockContext(Block):
def __init__(self, visible: bool = True, css: Optional[Dict[str, str]] = None):
def __init__(
self, visible: bool = True, css: Optional[Dict[str, str]] = None, **kwargs
):
"""
css: Css rules to apply to block.
"""
self.children = []
self.visible = visible
super().__init__(css=css)
super().__init__(css=css, **kwargs)

def __enter__(self):
self.parent = Context.block
Expand Down Expand Up @@ -204,6 +208,7 @@ def __init__(
theme: str = "default",
analytics_enabled: Optional[bool] = None,
mode: str = "blocks",
**kwargs,
):

# Cleanup shared parameters with Interface #TODO: is this part still necessary after Interface with Blocks?
Expand All @@ -221,7 +226,7 @@ def __init__(
else os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True"
)

super().__init__()
super().__init__(**kwargs)
self.blocks = {}
self.fns: List[BlockFunction] = []
self.dependencies = []
Expand Down Expand Up @@ -431,9 +436,8 @@ def launch(
self.width = width
self.favicon_path = favicon_path

if hasattr(self, "encrypt") and self.encrypt is None:
self.encrypt = encrypt
if hasattr(self, "encrypt") and self.encrypt:
self.encrypt = encrypt
if self.encrypt:
self.encryption_key = encryptor.get_key(
getpass.getpass("Enter key for encryption: ")
)
Expand Down
90 changes: 31 additions & 59 deletions gradio/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,7 @@ def __init__(
without_rendering: bool = False,
**kwargs,
):
if "optional" in kwargs:
warnings.warn(
"Usage of optional is deprecated, and it has no effect",
DeprecationWarning,
)
super().__init__(without_rendering=without_rendering, css=css)
super().__init__(without_rendering=without_rendering, css=css, **kwargs)

def __str__(self):
return self.__repr__()
Expand Down Expand Up @@ -269,16 +264,6 @@ def __init__(
placeholder (str): placeholder hint to provide behind textarea.
label (str): component name in interface.
"""
if "numeric" in kwargs:
warnings.warn(
"The 'numeric' type has been deprecated. Use the Number component instead.",
DeprecationWarning,
)
if "type" in kwargs:
warnings.warn(
"The 'type' parameter has been deprecated. Use the Number component instead if you need it.",
DeprecationWarning,
)
default_value = str(default_value)
self.lines = lines
self.max_lines = max_lines
Expand Down Expand Up @@ -1135,15 +1120,7 @@ def __init__(
type (str): The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "file" produces a temporary file object whose path can be retrieved by file_obj.name, "filepath" returns the path directly.
label (str): component name in interface.
"""
if "plot" in kwargs:
warnings.warn(
"The 'plot' parameter has been deprecated. Use the new Plot() component instead",
DeprecationWarning,
)
self.type = "plot"
else:
self.type = type

self.type = type
self.default_value = (
processing_utils.encode_url_or_file_to_base64(default_value)
if default_value
Expand Down Expand Up @@ -1954,8 +1931,6 @@ def __init__(
type (str): Type of value to be returned by component. "file" returns a temporary file object whose path can be retrieved by file_obj.name, "binary" returns an bytes object.
label (str): component name in interface.
"""
if "keep_filename" in kwargs:
warnings.warn("keep_filename is deprecated", DeprecationWarning)
self.default_value = (
processing_utils.encode_url_or_file_to_base64(default_value)
if default_value
Expand Down Expand Up @@ -3144,7 +3119,6 @@ def __init__(
self,
default_value: str = "",
*,
label: Optional[str] = None,
css: Optional[Dict] = None,
**kwargs,
):
Expand All @@ -3154,7 +3128,7 @@ def __init__(
label (str): component name
css (dict): optional css parameters for the component
"""
super().__init__(label=label, css=css, **kwargs)
super().__init__(css=css, **kwargs)
self.default_value = default_value

def get_template_context(self):
Expand Down Expand Up @@ -3315,10 +3289,37 @@ def get_template_context(self):
}


class StatusTracker(Component):
"""
Used to indicate status of a function call. Event listeners can bind to a StatusTracker with 'status=' keyword argument.
"""

def __init__(
self,
*,
cover_container: bool = False,
css: Optional[Dict] = None,
**kwargs,
):
"""
Parameters:
cover_container (bool): If True, will expand to cover parent container while function pending.
label (str): component name
css (dict): optional css parameters for the component
"""
super().__init__(css=css, **kwargs)
self.cover_container = cover_container

def get_template_context(self):
return {
"cover_container": self.cover_container,
**super().get_template_context(),
}


def component(cls_name: str):
"""
Returns a component or template with the given class name, or raises a ValueError if not found.
@param cls_name: lower-case string class name of a component
@return cls: the component class
"""
Expand Down Expand Up @@ -3355,32 +3356,3 @@ def get_component_instance(comp: str | dict | Component):
raise ValueError(
f"Component must provided as a `str` or `dict` or `Component` but is {comp}"
)


class StatusTracker(Component):
"""
Used to indicate status of a function call. Event listeners can bind to a StatusTracker with 'status=' keyword argument.
"""

def __init__(
self,
*,
cover_container: bool = False,
label: Optional[str] = None,
css: Optional[Dict] = None,
**kwargs,
):
"""
Parameters:
cover_container (bool): If True, will expand to cover parent container while function pending.
label (str): component name
css (dict): optional css parameters for the component
"""
super().__init__(label=label, css=css, **kwargs)
self.cover_container = cover_container

def get_template_context(self):
return {
"cover_container": self.cover_container,
**super().get_template_context(),
}
42 changes: 42 additions & 0 deletions gradio/deprecation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import warnings


def simple_deprecated_notice(term: str) -> str:
return f"`{term}` parameter is deprecated, and it has no effect"


def use_in_launch(term: str) -> str:
return f"`{term}` is deprecated in `Interface()`, please use it within `launch()` instead."


DEPRECATION_MESSAGE = {
"optional": simple_deprecated_notice("optional"),
"keep_filename": simple_deprecated_notice("keep_filename"),
"numeric": simple_deprecated_notice("numeric"),
"verbose": simple_deprecated_notice("verbose"),
"allow_screenshot": simple_deprecated_notice("allow_screenshot"),
"capture_session": simple_deprecated_notice("capture_session"),
"api_mode": simple_deprecated_notice("api_mode"),
"show_tips": use_in_launch("show_tips"),
"encrypt": use_in_launch("encrypt"),
"enable_queue": use_in_launch("enable_queue"),
"server_name": use_in_launch("server_name"),
"server_port": use_in_launch("server_port"),
"width": use_in_launch("width"),
"height": use_in_launch("height"),
"plot": "The 'plot' parameter has been deprecated. Use the new Plot component instead",
"type": "The 'type' parameter has been deprecated. Use the Number component instead.",
}


def check_deprecated_parameters(cls: str, **kwargs) -> None:
for key, value in DEPRECATION_MESSAGE.items():
if key in kwargs:
kwargs.pop(key)
# Interestingly, using DeprecationWarning causes warning to not appear.
warnings.warn(value)

if len(kwargs) != 0:
warnings.warn(
f"You have unused kwarg parameters in {cls}, please remove them: {kwargs}"
)
Loading

0 comments on commit 930c4a3

Please sign in to comment.