Spaces:
Sleeping
Sleeping
File size: 3,413 Bytes
d79620f | 1 | {"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: validator_test"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "\n", "def validate_input(age, location):\n", " is_age_valid = True\n", " is_location_valid = True\n", " if not age or age < 3:\n", " is_age_valid = False\n", " if \"london\" in location.lower():\n", " is_location_valid = False\n", "\n", " return [\n", " gr.validate(is_age_valid, \"Age must be at least 3\"),\n", " gr.validate(is_location_valid, \"Location must not be in London\"),\n", " ]\n", "\n", "\n", "def process_text(age, location):\n", " result = f\"Processed: {age} -- {location.upper()}\"\n", " return result\n", "\n", "\n", "def validate_image(image):\n", " # we don't want to error when a user is clearing the image\n", " if not image:\n", " return None\n", " is_portrait = image.width < image.height\n", "\n", " return gr.validate(is_portrait, \"Image must be in portrait mode\")\n", "\n", "\n", "def process_image(image):\n", " if not image:\n", " return \"No image uploaded\"\n", " return \"HELLO IMAGE!!!\"\n", "\n", "\n", "def raise_error():\n", " raise ValueError(\"test error\")\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tab(\"Text\"):\n", " gr.Markdown(\"# Validator Parameter Test Demo\")\n", "\n", " with gr.Row():\n", " with gr.Column():\n", " age = gr.Number(\n", " label=\"Enter age\",\n", " placeholder=\"Enter age\",\n", " )\n", " location = gr.Textbox(\n", " max_lines=3,\n", " label=\"Enter location\",\n", " placeholder=\"Enter location\",\n", " )\n", "\n", " validate_btn = gr.Button(\"Process with Validation\", variant=\"primary\")\n", "\n", " output_with_validation = gr.Textbox(\n", " label=\"Output (with validation)\", interactive=False\n", " )\n", "\n", " validate_btn.click(\n", " fn=process_text,\n", " validator=validate_input,\n", " inputs=[age, location],\n", " outputs=output_with_validation,\n", " )\n", " with gr.Tab(\"Image\"):\n", " im = gr.Image(label=\"Enter image\", placeholder=\"Enter image\", type=\"pil\")\n", " t = gr.Textbox(label=\"Enter text\", placeholder=\"Enter text\")\n", " im.change(\n", " fn=process_image,\n", " validator=validate_image,\n", " inputs=im,\n", " outputs=t,\n", " )\n", " with gr.Tab(\"Validation Error\"):\n", " error_btn = gr.Button(\"Raise Validation Error\", variant=\"primary\")\n", " error_btn.click(\n", " validator=raise_error,\n", " fn=raise_error,\n", " inputs=[],\n", " outputs=[],\n", " )\n", "\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} |