abidlabs HF Staff commited on
Commit
1a26838
·
verified ·
1 Parent(s): 16ac787

Create app.py

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