File size: 1,623 Bytes
595d1e1
1
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: unload_event_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": ["\"\"\"This demo is only meant to test the unload event.\n", "It will write to a file when the unload event is triggered.\n", "May not work as expected if multiple people are using it.\n", "\"\"\"\n", "import gradio as gr\n", "from pathlib import Path\n", "\n", "log_file = (Path(__file__).parent / \"output_log.txt\").resolve()\n", "\n", "def test_fn(x):\n", "    with open(log_file, \"a\") as f:\n", "        f.write(f\"incremented {x}\\n\")\n", "    return x + 1, x + 1\n", "\n", "def delete_fn(v):\n", "    with log_file.open(\"a\") as f:\n", "        f.write(f\"deleted {v}\\n\")\n", "\n", "def unload_fn():\n", "   with log_file.open(\"a\") as f:\n", "      f.write(\"unloading\\n\")\n", "\n", "with gr.Blocks() as demo:\n", "    n1 = gr.Number(value=0, label=\"Number\")\n", "    state = gr.State(value=0, delete_callback=delete_fn)\n", "    button = gr.Button(\"Increment\")\n", "    button.click(test_fn, [state], [n1, state], api_name=\"increment\")\n", "    demo.unload(unload_fn)\n", "    demo.load(lambda: log_file.write_text(\"\"))\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}