Washedashore commited on
Commit
d90ce10
·
verified ·
1 Parent(s): e90e021

Create run

Browse files
Files changed (1) hide show
  1. run +50 -0
run ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import gradio as gr
3
+ import numpy as np
4
+ from PIL import Image
5
+ from pathlib import Path
6
+ import secrets
7
+ import shutil
8
+
9
+ current_dir = Path(__file__).parent
10
+
11
+ def generate_random_img(history: list[Image.Image], request: gr.Request):
12
+ """Generate a random red, green, blue, orange, yellor or purple image."""
13
+ colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 165, 0), (255, 255, 0), (128, 0, 128)]
14
+ color = colors[np.random.randint(0, len(colors))]
15
+ img = Image.new('RGB', (100, 100), color)
16
+
17
+ user_dir: Path = current_dir / str(request.session_hash)
18
+ user_dir.mkdir(exist_ok=True)
19
+ path = user_dir / f"{secrets.token_urlsafe(8)}.webp"
20
+
21
+ img.save(path)
22
+ history.append(img)
23
+
24
+ return img, history, history
25
+
26
+ def delete_directory(req: gr.Request):
27
+ if not req.username:
28
+ return
29
+ user_dir: Path = current_dir / req.username
30
+ shutil.rmtree(str(user_dir))
31
+
32
+ with gr.Blocks(delete_cache=(60, 3600)) as demo:
33
+ gr.Markdown("""# State Cleanup Demo
34
+ 🖼️ Images are saved in a user-specific directory and deleted when the users closes the page via demo.unload.
35
+ """)
36
+ with gr.Row():
37
+ with gr.Column(scale=1):
38
+ with gr.Row():
39
+ img = gr.Image(label="Generated Image", height=300, width=300)
40
+ with gr.Row():
41
+ gen = gr.Button(value="Generate")
42
+ with gr.Row():
43
+ history = gr.Gallery(label="Previous Generations", height=500, columns=10)
44
+ state = gr.State(value=[], delete_callback=lambda v: print("STATE DELETED"))
45
+
46
+ demo.load(generate_random_img, [state], [img, state, history])
47
+ gen.click(generate_random_img, [state], [img, state, history])
48
+ demo.unload(delete_directory)
49
+
50
+ demo.launch()