diff --git a/.circleci/config.yml b/.circleci/config.yml index 2d139d05b2..cc2a0c2e4e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -53,7 +53,7 @@ jobs: - run: command: | . venv/bin/activate - python -m flake8 --ignore=E731,E501,E722,W503,E126,F401 gradio test + python -m flake8 --ignore=E731,E501,E722,W503,E126,F401,E203 gradio test - codecov/upload: file: 'coverage.xml' - store_artifacts: diff --git a/gradio/encryptor.py b/gradio/encryptor.py index 6dafec43fc..01951ea1d2 100644 --- a/gradio/encryptor.py +++ b/gradio/encryptor.py @@ -22,10 +22,10 @@ def encrypt(key: bytes, source: bytes) -> bytes: def decrypt(key: bytes, source: bytes) -> bytes: IV = source[: AES.block_size] # extract the IV from the beginning decryptor = AES.new(key, AES.MODE_CBC, IV) - data = decryptor.decrypt(source[AES.block_size:]) # decrypt + data = decryptor.decrypt(source[AES.block_size :]) # decrypt padding = data[-1] # pick the padding value from the end; Python 2.x: ord(data[-1]) if ( - data[-padding:] != bytes([padding]) * padding + data[-padding:] != bytes([padding]) * padding ): # Python 2.x: chr(padding) * padding raise ValueError("Invalid padding...") return data[:-padding] # remove the padding diff --git a/gradio/external.py b/gradio/external.py index 978a82ff9e..9684ba221e 100644 --- a/gradio/external.py +++ b/gradio/external.py @@ -1,6 +1,7 @@ import base64 import json import re + import requests from gradio import inputs, outputs @@ -213,7 +214,7 @@ def get_huggingface_interface(model_name, api_key, alias): # Convert to a list of input components data = pipeline["preprocess"](*params) if isinstance( - data, dict + data, dict ): # HF doesn't allow additional parameters for binary files (e.g. images or audio files) data.update({"options": {"wait_for_model": True}}) data = json.dumps(data) @@ -248,7 +249,7 @@ def load_interface(name, src=None, api_key=None, alias=None): "/" ) # Separate the source (e.g. "huggingface") from the repo name (e.g. "google/vit-base-patch16-224") assert ( - len(tokens) > 1 + len(tokens) > 1 ), "Either `src` parameter must be provided, or `name` must be formatted as {src}/{repo name}" src = tokens[0] name = "/".join(tokens[1:]) @@ -308,11 +309,11 @@ def get_spaces_interface(model_name, api_key, alias): result = json.loads(response.content.decode("utf-8")) output = result["data"] if ( - len(interface_info["outputs"]) == 1 + len(interface_info["outputs"]) == 1 ): # if the fn is supposed to return a single value, pop it output = output[0] if len(interface_info["outputs"]) == 1 and isinstance( - output, list + output, list ): # Needed to support Output.Image() returning bounding boxes as well (TODO: handle different versions of gradio since they have slightly different APIs) output = output[0] return output @@ -350,7 +351,7 @@ def load_from_pipeline(pipeline): # Handle the different pipelines. The has_attr() checks to make sure the pipeline exists in the # version of the transformers library that the user has installed. if hasattr(transformers, "AudioClassificationPipeline") and isinstance( - pipeline, transformers.AudioClassificationPipeline + pipeline, transformers.AudioClassificationPipeline ): pipeline_info = { "inputs": inputs.Audio(label="Input", source="microphone", type="filepath"), @@ -359,7 +360,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: {i["label"].split(", ")[0]: i["score"] for i in r}, } elif hasattr(transformers, "AutomaticSpeechRecognitionPipeline") and isinstance( - pipeline, transformers.AutomaticSpeechRecognitionPipeline + pipeline, transformers.AutomaticSpeechRecognitionPipeline ): pipeline_info = { "inputs": inputs.Audio(label="Input", source="microphone", type="filepath"), @@ -368,7 +369,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: r["text"], } elif hasattr(transformers, "FeatureExtractionPipeline") and isinstance( - pipeline, transformers.FeatureExtractionPipeline + pipeline, transformers.FeatureExtractionPipeline ): pipeline_info = { "inputs": inputs.Textbox(label="Input"), @@ -377,7 +378,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: r[0], } elif hasattr(transformers, "FillMaskPipeline") and isinstance( - pipeline, transformers.FillMaskPipeline + pipeline, transformers.FillMaskPipeline ): pipeline_info = { "inputs": inputs.Textbox(label="Input"), @@ -386,7 +387,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: {i["token_str"]: i["score"] for i in r}, } elif hasattr(transformers, "ImageClassificationPipeline") and isinstance( - pipeline, transformers.ImageClassificationPipeline + pipeline, transformers.ImageClassificationPipeline ): pipeline_info = { "inputs": inputs.Image(label="Input Image", type="filepath"), @@ -395,7 +396,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: {i["label"].split(", ")[0]: i["score"] for i in r}, } elif hasattr(transformers, "QuestionAnsweringPipeline") and isinstance( - pipeline, transformers.QuestionAnsweringPipeline + pipeline, transformers.QuestionAnsweringPipeline ): pipeline_info = { "inputs": [ @@ -407,7 +408,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: (r["answer"], r["score"]), } elif hasattr(transformers, "SummarizationPipeline") and isinstance( - pipeline, transformers.SummarizationPipeline + pipeline, transformers.SummarizationPipeline ): pipeline_info = { "inputs": inputs.Textbox(label="Input", lines=7), @@ -416,7 +417,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: r[0]["summary_text"], } elif hasattr(transformers, "TextClassificationPipeline") and isinstance( - pipeline, transformers.TextClassificationPipeline + pipeline, transformers.TextClassificationPipeline ): pipeline_info = { "inputs": inputs.Textbox(label="Input"), @@ -425,7 +426,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: {i["label"].split(", ")[0]: i["score"] for i in r}, } elif hasattr(transformers, "TextGenerationPipeline") and isinstance( - pipeline, transformers.TextGenerationPipeline + pipeline, transformers.TextGenerationPipeline ): pipeline_info = { "inputs": inputs.Textbox(label="Input"), @@ -434,7 +435,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: r[0]["generated_text"], } elif hasattr(transformers, "TranslationPipeline") and isinstance( - pipeline, transformers.TranslationPipeline + pipeline, transformers.TranslationPipeline ): pipeline_info = { "inputs": inputs.Textbox(label="Input"), @@ -443,7 +444,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: r[0]["translation_text"], } elif hasattr(transformers, "Text2TextGenerationPipeline") and isinstance( - pipeline, transformers.Text2TextGenerationPipeline + pipeline, transformers.Text2TextGenerationPipeline ): pipeline_info = { "inputs": inputs.Textbox(label="Input"), @@ -452,7 +453,7 @@ def load_from_pipeline(pipeline): "postprocess": lambda r: r[0]["generated_text"], } elif hasattr(transformers, "ZeroShotClassificationPipeline") and isinstance( - pipeline, transformers.ZeroShotClassificationPipeline + pipeline, transformers.ZeroShotClassificationPipeline ): pipeline_info = { "inputs": [ @@ -478,12 +479,12 @@ def load_from_pipeline(pipeline): data = pipeline_info["preprocess"](*params) # special cases that needs to be handled differently if isinstance( - pipeline, - ( - transformers.TextClassificationPipeline, - transformers.Text2TextGenerationPipeline, - transformers.TranslationPipeline, - ), + pipeline, + ( + transformers.TextClassificationPipeline, + transformers.Text2TextGenerationPipeline, + transformers.TranslationPipeline, + ), ): data = pipeline(*data) else: diff --git a/gradio/inputs.py b/gradio/inputs.py index 057ed47031..3cff47e6b1 100644 --- a/gradio/inputs.py +++ b/gradio/inputs.py @@ -77,7 +77,7 @@ class InputComponent(Component): pass def get_interpretation_scores( - self, x: Any, neighbors: List[Any], scores: List[float], **kwargs + self, x: Any, neighbors: List[Any], scores: List[float], **kwargs ) -> List[Any]: """ Arrange the output values from the neighbors into interpretation scores for the interface to render. @@ -106,13 +106,13 @@ class Textbox(InputComponent): """ def __init__( - self, - lines: int = 1, - placeholder: Optional[str] = None, - default: str = "", - numeric: Optional[bool] = False, - type: Optional[str] = "str", - label: Optional[str] = None, + self, + lines: int = 1, + placeholder: Optional[str] = None, + default: str = "", + numeric: Optional[bool] = False, + type: Optional[str] = "str", + label: Optional[str] = None, ): """ Parameters: @@ -183,7 +183,7 @@ class Textbox(InputComponent): return x def set_interpret_parameters( - self, separator: str = " ", replacement: Optional[str] = None + self, separator: str = " ", replacement: Optional[str] = None ): """ Calculates interpretation score of characters in input by splitting input into tokens, then using a "leave one out" method to calculate the score of each token by removing each token and measuring the delta of the output value. @@ -213,7 +213,7 @@ class Textbox(InputComponent): return tokens, leave_one_out_strings, None def get_masked_inputs( - self, tokens: List[str], binary_mask_matrix: List[List[int]] + self, tokens: List[str], binary_mask_matrix: List[List[int]] ) -> List[str]: """ Constructs partially-masked sentences for SHAP interpretation @@ -225,7 +225,7 @@ class Textbox(InputComponent): return masked_inputs def get_interpretation_scores( - self, x, neighbors, scores: List[float], tokens: List[str], masks=None + self, x, neighbors, scores: List[float], tokens: List[str], masks=None ) -> List[Tuple[str, float]]: """ Returns: @@ -285,7 +285,7 @@ class Number(InputComponent): return x def set_interpret_parameters( - self, steps: int = 3, delta: float = 1, delta_type: str = "percent" + self, steps: int = 3, delta: float = 1, delta_type: str = "percent" ): """ Calculates interpretation scores of numeric values close to the input number. @@ -310,7 +310,7 @@ class Number(InputComponent): return negatives + positives, {} def get_interpretation_scores( - self, x: Number, neighbors: List[float], scores: List[float] + self, x: Number, neighbors: List[float], scores: List[float] ) -> List[Tuple[float, float]]: """ Returns: @@ -332,12 +332,12 @@ class Slider(InputComponent): """ def __init__( - self, - minimum: float = 0, - maximum: float = 100, - step: Optional[float] = None, - default: Optional[float] = None, - label: Optional[str] = None, + self, + minimum: float = 0, + maximum: float = 100, + step: Optional[float] = None, + default: Optional[float] = None, + label: Optional[str] = None, ): """ Parameters: @@ -352,7 +352,7 @@ class Slider(InputComponent): if step is None: difference = maximum - minimum power = math.floor(math.log10(difference) - 2) - step = 10 ** power + step = 10**power self.step = step self.default = minimum if default is None else default self.test_input = self.default @@ -406,7 +406,7 @@ class Slider(InputComponent): ) def get_interpretation_scores( - self, x, neighbors, scores: List[float] + self, x, neighbors, scores: List[float] ) -> List[float]: """ Returns: @@ -492,11 +492,11 @@ class CheckboxGroup(InputComponent): """ def __init__( - self, - choices: List[str], - default: List[str] = [], - type: str = "value", - label: Optional[str] = None, + self, + choices: List[str], + default: List[str] = [], + type: str = "value", + label: Optional[str] = None, ): """ Parameters: @@ -589,11 +589,11 @@ class Radio(InputComponent): """ def __init__( - self, - choices: List(str), - type: str = "value", - default: Optional[str] = None, - label: Optional[str] = None, + self, + choices: List(str), + type: str = "value", + default: Optional[str] = None, + label: Optional[str] = None, ): """ Parameters: @@ -665,11 +665,11 @@ class Dropdown(InputComponent): """ def __init__( - self, - choices: List[str], - type: str = "value", - default: Optional[str] = None, - label: Optional[str] = None, + self, + choices: List[str], + type: str = "value", + default: Optional[str] = None, + label: Optional[str] = None, ): """ Parameters: @@ -741,15 +741,15 @@ class Image(InputComponent): """ def __init__( - self, - shape: Tuple[int, int] = None, - image_mode: str = "RGB", - invert_colors: bool = False, - source: str = "upload", - tool: str = "editor", - type: str = "numpy", - label: str = None, - optional: bool = False, + self, + shape: Tuple[int, int] = None, + image_mode: str = "RGB", + invert_colors: bool = False, + source: str = "upload", + tool: str = "editor", + type: str = "numpy", + label: str = None, + optional: bool = False, ): """ Parameters: @@ -978,11 +978,11 @@ class Video(InputComponent): """ def __init__( - self, - type: Optional[str] = None, - source: str = "upload", - label: Optional[str] = None, - optional: bool = False, + self, + type: Optional[str] = None, + source: str = "upload", + label: Optional[str] = None, + optional: bool = False, ): """ Parameters: @@ -1035,7 +1035,7 @@ class Video(InputComponent): file_name = file.name uploaded_format = file_name.split(".")[-1].lower() if self.type is not None and uploaded_format != self.type: - output_file_name = file_name[0: file_name.rindex(".") + 1] + self.type + output_file_name = file_name[0 : file_name.rindex(".") + 1] + self.type ff = FFmpeg(inputs={file_name: None}, outputs={output_file_name: None}) ff.run() return output_file_name @@ -1065,11 +1065,11 @@ class Audio(InputComponent): """ def __init__( - self, - source: str = "upload", - type: str = "numpy", - label: str = None, - optional: bool = False, + self, + source: str = "upload", + type: str = "numpy", + label: str = None, + optional: bool = False, ): """ Parameters: @@ -1277,12 +1277,12 @@ class File(InputComponent): """ def __init__( - self, - file_count: str = "single", - type: str = "file", - label: Optional[str] = None, - keep_filename: bool = True, - optional: bool = False, + self, + file_count: str = "single", + type: str = "file", + label: Optional[str] = None, + keep_filename: bool = True, + optional: bool = False, ): """ Parameters: @@ -1378,15 +1378,15 @@ class Dataframe(InputComponent): """ def __init__( - self, - headers: Optional[List[str]] = None, - row_count: int = 3, - col_count: Optional[int] = 3, - datatype: str | List[str] = "str", - col_width: int | List[int] = None, - default: Optional[List[List[Any]]] = None, - type: str = "pandas", - label: Optional[str] = None, + self, + headers: Optional[List[str]] = None, + row_count: int = 3, + col_count: Optional[int] = 3, + datatype: str | List[str] = "str", + col_width: int | List[int] = None, + default: Optional[List[List[Any]]] = None, + type: str = "pandas", + label: Optional[str] = None, ): """ Parameters: @@ -1491,11 +1491,11 @@ class Timeseries(InputComponent): """ def __init__( - self, - x: Optional[str] = None, - y: str | List[str] = None, - label: Optional[str] = None, - optional: bool = False, + self, + x: Optional[str] = None, + y: str | List[str] = None, + label: Optional[str] = None, + optional: bool = False, ): """ Parameters: @@ -1591,7 +1591,7 @@ def get_input_instance(iface: Interface): shortcut = InputComponent.get_all_shortcut_implementations()[iface] return shortcut[0](**shortcut[1]) elif isinstance( - iface, dict + iface, dict ): # a dict with `name` as the input component type and other keys as parameters name = iface.pop("name") for component in InputComponent.__subclasses__(): diff --git a/gradio/outputs.py b/gradio/outputs.py index a9760dd0e2..06d4210532 100644 --- a/gradio/outputs.py +++ b/gradio/outputs.py @@ -99,10 +99,10 @@ class Label(OutputComponent): CONFIDENCES_KEY = "confidences" def __init__( - self, - num_top_classes: Optional[int] = None, - type: str = "auto", - label: Optional[str] = None, + self, + num_top_classes: Optional[int] = None, + type: str = "auto", + label: Optional[str] = None, ): """ Parameters: @@ -122,11 +122,11 @@ class Label(OutputComponent): (Dict[label: str, confidences: List[Dict[label: str, confidence: number]]]): Object with key 'label' representing primary label, and key 'confidences' representing a list of label-confidence pairs """ if self.type == "label" or ( - self.type == "auto" and (isinstance(y, str) or isinstance(y, Number)) + self.type == "auto" and (isinstance(y, str) or isinstance(y, Number)) ): return {"label": str(y)} elif self.type == "confidences" or ( - self.type == "auto" and isinstance(y, dict) + self.type == "auto" and isinstance(y, dict) ): sorted_pred = sorted(y.items(), key=operator.itemgetter(1), reverse=True) if self.num_top_classes is not None: @@ -146,13 +146,13 @@ class Label(OutputComponent): def deserialize(self, y): # 5 cases: (1): {'label': 'lion'}, {'label': 'lion', 'confidences':...}, {'lion': 0.46, ...}, 'lion', '0.46' if self.type == "label" or ( - self.type == "auto" - and ( - isinstance(y, str) - or isinstance(y, int) - or isinstance(y, float) - or ("label" in y and not ("confidences" in y.keys())) - ) + self.type == "auto" + and ( + isinstance(y, str) + or isinstance(y, int) + or isinstance(y, float) + or ("label" in y and not ("confidences" in y.keys())) + ) ): if isinstance(y, str) or isinstance(y, int) or isinstance(y, float): return y @@ -201,7 +201,7 @@ class Image(OutputComponent): """ def __init__( - self, type: str = "auto", plot: bool = False, label: Optional[str] = None + self, type: str = "auto", plot: bool = False, label: Optional[str] = None ): """ Parameters: @@ -301,7 +301,7 @@ class Video(OutputComponent): """ returned_format = y.split(".")[-1].lower() if self.type is not None and returned_format != self.type: - output_file_name = y[0: y.rindex(".") + 1] + self.type + output_file_name = y[0 : y.rindex(".") + 1] + self.type ff = FFmpeg(inputs={y: None}, outputs={output_file_name: None}) ff.run() y = output_file_name @@ -373,10 +373,10 @@ class HighlightedText(OutputComponent): """ def __init__( - self, - color_map: Dict[str, str] = None, - label: Optional[str] = None, - show_legend: bool = False, + self, + color_map: Dict[str, str] = None, + label: Optional[str] = None, + show_legend: bool = False, ): """ Parameters: @@ -591,13 +591,13 @@ class Dataframe(OutputComponent): """ def __init__( - self, - headers: Optional[List[str]] = None, - max_rows: Optional[int] = 20, - max_cols: Optional[int] = None, - overflow_row_behaviour: str = "paginate", - type: str = "auto", - label: Optional[str] = None, + self, + headers: Optional[List[str]] = None, + max_rows: Optional[int] = 20, + max_cols: Optional[int] = None, + overflow_row_behaviour: str = "paginate", + type: str = "auto", + label: Optional[str] = None, ): """ Parameters: @@ -679,9 +679,9 @@ class Carousel(OutputComponent): """ def __init__( - self, - components: OutputComponent | List[OutputComponent], - label: Optional[str] = None, + self, + components: OutputComponent | List[OutputComponent], + label: Optional[str] = None, ): """ Parameters: @@ -752,7 +752,7 @@ class Timeseries(OutputComponent): """ def __init__( - self, x: str = None, y: str | List[str] = None, label: Optional[str] = None + self, x: str = None, y: str | List[str] = None, label: Optional[str] = None ): """ Parameters: diff --git a/gradio/processing_utils.py b/gradio/processing_utils.py index 4b354de892..d95b9d40ab 100644 --- a/gradio/processing_utils.py +++ b/gradio/processing_utils.py @@ -60,10 +60,10 @@ def encode_file_to_base64(f, encryption_key=None): base64_str = str(encoded_string, "utf-8") mimetype = get_mimetype(f) return ( - "data:" - + (mimetype if mimetype is not None else "") - + ";base64," - + base64_str + "data:" + + (mimetype if mimetype is not None else "") + + ";base64," + + base64_str ) @@ -72,7 +72,7 @@ def encode_url_to_base64(url): base64_str = str(encoded_string, "utf-8") mimetype = get_mimetype(url) return ( - "data:" + (mimetype if mimetype is not None else "") + ";base64," + base64_str + "data:" + (mimetype if mimetype is not None else "") + ";base64," + base64_str ) @@ -190,8 +190,8 @@ def decode_base64_to_file(encoding, encryption_key=None, file_path=None): filename = os.path.basename(file_path) prefix = filename if "." in filename: - prefix = filename[0: filename.index(".")] - extension = filename[filename.index(".") + 1:] + prefix = filename[0 : filename.index(".")] + extension = filename[filename.index(".") + 1 :] if extension is None: file_obj = tempfile.NamedTemporaryFile(delete=False, prefix=prefix) else: @@ -209,8 +209,8 @@ def create_tmp_copy_of_file(file_path): file_name = os.path.basename(file_path) prefix, extension = file_name, None if "." in file_name: - prefix = file_name[0: file_name.index(".")] - extension = file_name[file_name.index(".") + 1:] + prefix = file_name[0 : file_name.index(".")] + extension = file_name[file_name.index(".") + 1 :] if extension is None: file_obj = tempfile.NamedTemporaryFile(delete=False, prefix=prefix) else: @@ -336,7 +336,7 @@ def _convert(image, dtype, force_copy=False, uniform=False): Output image array. Has the same kind as `a`. """ kind = a.dtype.kind - if n > m and a.max() < 2 ** m: + if n > m and a.max() < 2**m: return a.astype(_dtype_bits(kind, m)) elif n == m: return a.copy() if copy else a @@ -353,11 +353,11 @@ def _convert(image, dtype, force_copy=False, uniform=False): # exact upscale to a multiple of `n` bits if copy: b = np.empty(a.shape, _dtype_bits(kind, m)) - np.multiply(a, (2 ** m - 1) // (2 ** n - 1), out=b, dtype=b.dtype) + np.multiply(a, (2**m - 1) // (2**n - 1), out=b, dtype=b.dtype) return b else: a = a.astype(_dtype_bits(kind, m, a.dtype.itemsize), copy=False) - a *= (2 ** m - 1) // (2 ** n - 1) + a *= (2**m - 1) // (2**n - 1) return a else: # upscale to a multiple of `n` bits, @@ -365,12 +365,12 @@ def _convert(image, dtype, force_copy=False, uniform=False): o = (m // n + 1) * n if copy: b = np.empty(a.shape, _dtype_bits(kind, o)) - np.multiply(a, (2 ** o - 1) // (2 ** n - 1), out=b, dtype=b.dtype) + np.multiply(a, (2**o - 1) // (2**n - 1), out=b, dtype=b.dtype) b //= 2 ** (o - m) return b else: a = a.astype(_dtype_bits(kind, o, a.dtype.itemsize), copy=False) - a *= (2 ** o - 1) // (2 ** n - 1) + a *= (2**o - 1) // (2**n - 1) a //= 2 ** (o - m) return a diff --git a/gradio/routes.py b/gradio/routes.py index 6f5347a5a0..2a7e7f9db9 100644 --- a/gradio/routes.py +++ b/gradio/routes.py @@ -82,9 +82,9 @@ def get_token(request: Request) -> Optional[str]: def login(form_data: OAuth2PasswordRequestForm = Depends()): username, password = form_data.username, form_data.password if ( - not callable(app.auth) - and username in app.auth - and app.auth[username] == password + not callable(app.auth) + and username in app.auth + and app.auth[username] == password ) or (callable(app.auth) and app.auth.__call__(username, password)): token = secrets.token_urlsafe(16) app.tokens[token] = username @@ -144,9 +144,9 @@ def build_resource(path: str): @app.get("/file/{path:path}", dependencies=[Depends(login_check)]) def file(path): if ( - app.interface.encrypt - and isinstance(app.interface.examples, str) - and path.startswith(app.interface.examples) + app.interface.encrypt + and isinstance(app.interface.examples, str) + and path.startswith(app.interface.examples) ): with open(safe_join(app.cwd, path), "rb") as encrypted_file: encrypted_data = encrypted_file.read() @@ -305,10 +305,10 @@ def safe_join(directory: str, path: str) -> Optional[str]: filename = posixpath.normpath(path) if ( - any(sep in filename for sep in _os_alt_seps) - or os.path.isabs(filename) - or filename == ".." - or filename.startswith("../") + any(sep in filename for sep in _os_alt_seps) + or os.path.isabs(filename) + or filename == ".." + or filename.startswith("../") ): return None diff --git a/gradio/utils.py b/gradio/utils.py index 92c6d384f0..da878d17b3 100644 --- a/gradio/utils.py +++ b/gradio/utils.py @@ -105,7 +105,7 @@ async def log_feature_analytics(ip_address: str, feature: str) -> None: async with aiohttp.ClientSession() as session: try: async with session.post( - analytics_url + "gradio-feature-analytics/", data=data + analytics_url + "gradio-feature-analytics/", data=data ): pass except (aiohttp.ClientError): @@ -232,9 +232,9 @@ def get_config_file(interface: Interface) -> Dict[str, Any]: iface["label"] = ret_name if len(interface.predict) > 1: iface["label"] = ( - interface.function_names[function_index].replace("_", " ") - + ": " - + iface["label"] + interface.function_names[function_index].replace("_", " ") + + ": " + + iface["label"] ) except ValueError: @@ -263,10 +263,10 @@ def get_config_file(interface: Interface) -> Dict[str, Any]: examples = examples[1:] # remove header for i, example in enumerate(examples): for j, (component, cell) in enumerate( - zip( - interface.input_components + interface.output_components, - example, - ) + zip( + interface.input_components + interface.output_components, + example, + ) ): examples[i][j] = component.restore_flagged( interface.flagging_dir, diff --git a/scripts/format.sh b/scripts/format.sh new file mode 100644 index 0000000000..f08bb097f6 --- /dev/null +++ b/scripts/format.sh @@ -0,0 +1,10 @@ +#!/bin/bash +if [ -z "$(ls | grep CONTRIBUTING.md)" ]; then + echo "Please run the script from repo directory" + exit -1 +else + echo "Installing formatting with black and isort, also checking for standards with flake8" + python -m black gradio test + python -m isort --profile=black gradio test + python -m flake8 --ignore=E731,E501,E722,W503,E126,F401,E203 gradio test +fi diff --git a/test/test_interfaces.py b/test/test_interfaces.py index 4faf3bc4ab..cdb93c1d30 100644 --- a/test/test_interfaces.py +++ b/test/test_interfaces.py @@ -7,7 +7,8 @@ from contextlib import contextmanager import mlflow import requests import wandb -from gradio.interface import Interface, os, close_all + +from gradio.interface import Interface, close_all, os os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" diff --git a/test/test_queuing.py b/test/test_queuing.py index cca40f91dc..7bbfe5d159 100644 --- a/test/test_queuing.py +++ b/test/test_queuing.py @@ -2,6 +2,7 @@ import os import unittest + from gradio import queueing os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" diff --git a/test/test_utils.py b/test/test_utils.py index b9c4502982..4f17a68a14 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -7,7 +7,16 @@ import warnings import pkg_resources import requests -from gradio.utils import version_check, json, error_analytics, colab_check, ipython_check, readme_to_html, get_local_ip_address, launch_analytics +from gradio.utils import ( + colab_check, + error_analytics, + get_local_ip_address, + ipython_check, + json, + launch_analytics, + readme_to_html, + version_check, +) os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"