Spaces:
Runtime error
Runtime error
Delete gallery_history.py
Browse files- gallery_history.py +0 -129
gallery_history.py
DELETED
@@ -1,129 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
How to use:
|
3 |
-
1. Create a Space with a Persistent Storage attached. Filesystem will be available under `/data`.
|
4 |
-
2. Add `hf_oauth: true` to the Space metadata (README.md). Make sure to have Gradio>=3.41.0 configured.
|
5 |
-
3. Add `HISTORY_FOLDER` as a Space variable (example. `"/data/history"`).
|
6 |
-
4. Add `filelock` as dependency in `requirements.txt`.
|
7 |
-
5. Add history gallery to your Gradio app:
|
8 |
-
a. Add imports: `from gallery_history import fetch_gallery_history, show_gallery_history`
|
9 |
-
a. Add `history = show_gallery_history()` within `gr.Blocks` context.
|
10 |
-
b. Add `.then(fn=fetch_gallery_history, inputs=[prompt, result], outputs=history)` on the generate event.
|
11 |
-
"""
|
12 |
-
import json
|
13 |
-
import os
|
14 |
-
import shutil
|
15 |
-
from pathlib import Path
|
16 |
-
from typing import Dict, List, Optional, Tuple
|
17 |
-
from uuid import uuid4
|
18 |
-
|
19 |
-
import gradio as gr
|
20 |
-
from filelock import FileLock
|
21 |
-
|
22 |
-
_folder = os.environ.get("HISTORY_FOLDER")
|
23 |
-
if _folder is None:
|
24 |
-
print(
|
25 |
-
"'HISTORY_FOLDER' environment variable not set. User history will be saved "
|
26 |
-
"locally and will be lost when the Space instance is restarted."
|
27 |
-
)
|
28 |
-
_folder = Path(__file__).parent / "history"
|
29 |
-
HISTORY_FOLDER_PATH = Path(_folder)
|
30 |
-
|
31 |
-
IMAGES_FOLDER_PATH = HISTORY_FOLDER_PATH / "images"
|
32 |
-
IMAGES_FOLDER_PATH.mkdir(parents=True, exist_ok=True)
|
33 |
-
|
34 |
-
|
35 |
-
def show_gallery_history():
|
36 |
-
gr.Markdown(
|
37 |
-
"## Your past generations\n\n(Log in to keep a gallery of your previous generations."
|
38 |
-
" Your history will be saved and available on your next visit.)"
|
39 |
-
)
|
40 |
-
with gr.Column():
|
41 |
-
with gr.Row():
|
42 |
-
gr.LoginButton(min_width=250)
|
43 |
-
gr.LogoutButton(min_width=250)
|
44 |
-
gallery = gr.Gallery(
|
45 |
-
label="Past images",
|
46 |
-
show_label=True,
|
47 |
-
elem_id="gallery",
|
48 |
-
object_fit="contain",
|
49 |
-
columns=3,
|
50 |
-
height=300,
|
51 |
-
preview=False,
|
52 |
-
show_share_button=False,
|
53 |
-
show_download_button=False,
|
54 |
-
)
|
55 |
-
gr.Markdown(
|
56 |
-
"Make sure to save your images from time to time, this gallery may be deleted in the future."
|
57 |
-
)
|
58 |
-
gallery.attach_load_event(fetch_gallery_history, every=None)
|
59 |
-
return gallery
|
60 |
-
|
61 |
-
|
62 |
-
def fetch_gallery_history(
|
63 |
-
prompt: Optional[str] = None,
|
64 |
-
result: Optional[Dict] = None,
|
65 |
-
user: Optional[gr.OAuthProfile] = None,
|
66 |
-
):
|
67 |
-
if user is None:
|
68 |
-
return []
|
69 |
-
try:
|
70 |
-
if prompt is not None and result is not None: # None values means no new images
|
71 |
-
return _update_user_history(
|
72 |
-
user["preferred_username"], [(item["name"], prompt) for item in result]
|
73 |
-
)
|
74 |
-
else:
|
75 |
-
return _read_user_history(user["preferred_username"])
|
76 |
-
except Exception as e:
|
77 |
-
raise gr.Error(f"Error while fetching history: {e}") from e
|
78 |
-
|
79 |
-
|
80 |
-
####################
|
81 |
-
# Internal helpers #
|
82 |
-
####################
|
83 |
-
|
84 |
-
|
85 |
-
def _read_user_history(username: str) -> List[Tuple[str, str]]:
|
86 |
-
"""Return saved history for that user."""
|
87 |
-
with _user_lock(username):
|
88 |
-
path = _user_history_path(username)
|
89 |
-
if path.exists():
|
90 |
-
return json.loads(path.read_text())
|
91 |
-
return [] # No history yet
|
92 |
-
|
93 |
-
|
94 |
-
def _update_user_history(
|
95 |
-
username: str, new_images: List[Tuple[str, str]]
|
96 |
-
) -> List[Tuple[str, str]]:
|
97 |
-
"""Update history for that user and return it."""
|
98 |
-
with _user_lock(username):
|
99 |
-
# Read existing
|
100 |
-
path = _user_history_path(username)
|
101 |
-
if path.exists():
|
102 |
-
images = json.loads(path.read_text())
|
103 |
-
else:
|
104 |
-
images = [] # No history yet
|
105 |
-
|
106 |
-
# Copy images to persistent folder
|
107 |
-
images = [
|
108 |
-
(_copy_image(src_path), prompt) for src_path, prompt in new_images
|
109 |
-
] + images
|
110 |
-
|
111 |
-
# Save and return
|
112 |
-
path.write_text(json.dumps(images))
|
113 |
-
return images
|
114 |
-
|
115 |
-
|
116 |
-
def _user_history_path(username: str) -> Path:
|
117 |
-
return HISTORY_FOLDER_PATH / f"{username}.json"
|
118 |
-
|
119 |
-
|
120 |
-
def _user_lock(username: str) -> FileLock:
|
121 |
-
"""Ensure history is not corrupted if concurrent calls."""
|
122 |
-
return FileLock(f"{_user_history_path(username)}.lock")
|
123 |
-
|
124 |
-
|
125 |
-
def _copy_image(src: str) -> str:
|
126 |
-
"""Copy image to the persistent storage."""
|
127 |
-
dst = IMAGES_FOLDER_PATH / f"{uuid4().hex}_{Path(src).name}" # keep file ext
|
128 |
-
shutil.copyfile(src, dst)
|
129 |
-
return str(dst)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|