From b6609915e0291183655a0e126975636731fe6092 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer=20Faruk=20=C3=96zdemir?= Date: Tue, 1 Mar 2022 12:45:24 +0300 Subject: [PATCH] add change and save events on backend --- gradio/__init__.py | 1 - gradio/blocks.py | 58 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/gradio/__init__.py b/gradio/__init__.py index 8a9b9b4ab7..c6c85cb55b 100644 --- a/gradio/__init__.py +++ b/gradio/__init__.py @@ -11,6 +11,5 @@ from gradio.interface import Interface, close_all, reset_all from gradio.mix import Parallel, Series from gradio.routes import get_state, set_state from gradio.static import Button, Markdown - current_pkg_version = pkg_resources.require("gradio")[0].version __version__ = current_pkg_version diff --git a/gradio/blocks.py b/gradio/blocks.py index 53b1745f0e..7aaafba182 100644 --- a/gradio/blocks.py +++ b/gradio/blocks.py @@ -3,7 +3,7 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple from gradio import utils from gradio.context import Context from gradio.launchable import Launchable - +from gradio.component import Component class Block: def __init__(self): @@ -30,6 +30,62 @@ class Block: } ) + def change(self, fn: str, inputs: List[Component], outputs: List[Component]) -> None: + """ + Adds change event to the dependencies. + + Whenever one of the inputs changes the function is triggered. + + Parameters: + fn: + inputs: + outputs: + + Returns: None + + """ + if not isinstance(inputs, list): + inputs = [inputs] + if not isinstance(outputs, list): + outputs = [outputs] + Context.root_block.fns.append(fn) + Context.root_block.dependencies.append( + { + "targets": [self._id], + "trigger": "change", + "inputs": [block._id for block in inputs], + "outputs": [block._id for block in outputs], + } + ) + + def save(self, fn: str, inputs: List[Component], outputs: List[Component]) -> None: + """ + Adds save event to the dependencies. + + Whenever one of the inputs is saved, function is triggered. + + Parameters: + fn: function name + inputs: input list + outputs: output list + + Returns: None + + """ + if not isinstance(inputs, list): + inputs = [inputs] + if not isinstance(outputs, list): + outputs = [outputs] + Context.root_block.fns.append(fn) + Context.root_block.dependencies.append( + { + "targets": [self._id], + "trigger": "save", + "inputs": [block._id for block in inputs], + "outputs": [block._id for block in outputs], + } + ) + class BlockContext(Block): def __init__(self):