File size: 2,590 Bytes
0bd62e5
1
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: state_cleanup"]}, {"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": ["from __future__ import annotations\n", "import gradio as gr\n", "import numpy as np\n", "from PIL import Image\n", "from pathlib import Path\n", "import secrets\n", "import shutil\n", "\n", "current_dir = Path(__file__).parent\n", "\n", "def generate_random_img(history: list[Image.Image], request: gr.Request):\n", "    \"\"\"Generate a random red, green, blue, orange, yellor or purple image.\"\"\"\n", "    colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 165, 0), (255, 255, 0), (128, 0, 128)]\n", "    color = colors[np.random.randint(0, len(colors))]\n", "    img = Image.new('RGB', (100, 100), color)\n", "\n", "    user_dir: Path = current_dir / str(request.session_hash)\n", "    user_dir.mkdir(exist_ok=True)\n", "    path = user_dir / f\"{secrets.token_urlsafe(8)}.webp\"\n", "\n", "    img.save(path)\n", "    history.append(img)\n", "\n", "    return img, history, history\n", "\n", "def delete_directory(req: gr.Request):\n", "    if not req.username:\n", "        return\n", "    user_dir: Path = current_dir / req.username\n", "    shutil.rmtree(str(user_dir))\n", "\n", "with gr.Blocks(delete_cache=(60, 3600)) as demo:\n", "    gr.Markdown(\"\"\"# State Cleanup Demo\n", "                \ud83d\uddbc\ufe0f Images are saved in a user-specific directory and deleted when the users closes the page via demo.unload.\n", "                \"\"\")\n", "    with gr.Row():\n", "        with gr.Column(scale=1):\n", "            with gr.Row():\n", "                img = gr.Image(label=\"Generated Image\", height=300, width=300)\n", "            with gr.Row():\n", "                gen = gr.Button(value=\"Generate\")\n", "            with gr.Row():\n", "                history = gr.Gallery(label=\"Previous Generations\", height=500, columns=10)\n", "                state = gr.State(value=[], delete_callback=lambda v: print(\"STATE DELETED\"))\n", "\n", "    demo.load(generate_random_img, [state], [img, state, history])\n", "    gen.click(generate_random_img, [state], [img, state, history])\n", "    demo.unload(delete_directory)\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}