Upload 10 files
Browse filesFiles changed (10)
- LAUNCHER - CASCADE.batAdded+9
- README.md+18-1
- app.pyAdded+273
- previewer/__pycache__/modules.cpython-310.pycAdded
- previewer/modules.pyAdded+45
- previewer/previewer_v1_100k.ptAdded+3
- previewer/text2img_wurstchen_b_v1_previewer_100k.ptAdded+3
- requirements.txtAdded+4
- style.cssAdded+24
- user_history.pyAdded+423
123456789@echo offCALL env\Scripts\activatepython app.py --inbrowser
REM List of possible arguments
REM --inbrowser Automatically open the url in browser, if --share is used, the public url will be automatically open insteadREM --server_port Choose a specific server port, default=7860 (example --server_port 420 so the local url will be: http://127.0.0.1:420)REM --share Creates a public URL123---license: unknown---1234567891011121314151617181920--inbrowser Automatically open the url in browser, if --share is used, the public url will be automatically open instead--server_port Choose a specific server port, default=7860 (example --server_port 420 so the local url will be: http://127.0.0.1:420)--share Creates a public URL---title: Stable Cascadeemoji: 👁colorFrom: bluecolorTo: purplesdk: gradiosdk_version: 4.18.0app_file: app.pypinned: falselicense: mithf_oauth: true---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273import osimport randomimport gradio as grimport numpy as npimport PIL.Imageimport torchimport argparsefrom typing import Listfrom diffusers.utils import numpy_to_pilfrom diffusers import StableCascadeDecoderPipeline, StableCascadePriorPipelinefrom diffusers.pipelines.wuerstchen import DEFAULT_STAGE_C_TIMESTEPSfrom previewer.modules import Previewer
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
DESCRIPTION = "# Stable Cascade"DESCRIPTION += "\n<p style=\"text-align: center\">Неофициальная демонстрация Stable Cascade от <a href='https://www.youtube.com/@nerual_dreming/' target='_blank'>Nerual Dreming и нейросети</a> основано на <a href='https://huggingface.co/stabilityai/stable-cascade' target='_blank'>Stable Cascade</a>, новая модель высокого разрешения для генерации изображений по текстовому запросу от Stability AI, основанная на архитектуре Würstchen - <a href='https://huggingface.co/stabilityai/stable-cascade/blob/main/LICENSE' target='_blank'>только для некоммерческого и научного использования</a></p>"
MAX_SEED = np.iinfo(np.int32).maxCACHE_EXAMPLES = FalseMAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "1536"))USE_TORCH_COMPILE = FalseENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD") == "1"PREVIEW_IMAGES = True
parser = argparse.ArgumentParser(description='Gradio App Control')parser.add_argument('--share', action='store_true', help='Create a public shareable URL')parser.add_argument('--inbrowser', action='store_true', help='Automatically launch the application in a browser')parser.add_argument('--server_port', type=int, default=7860, help='Server port')args = parser.parse_args()
dtype = torch.bfloat16if torch.cuda.is_available(): device = "cuda"elif torch.backends.mps.is_available(): device = "mps" dtype = torch.float32else: device = "cpu"print(f"device={device}")if device != "cpu": prior_pipeline = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", torch_dtype=dtype)#.to(device) decoder_pipeline = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", torch_dtype=dtype)#.to(device)
if ENABLE_CPU_OFFLOAD: prior_pipeline.enable_model_cpu_offload() decoder_pipeline.enable_model_cpu_offload() else: prior_pipeline.to(device) decoder_pipeline.to(device)
if USE_TORCH_COMPILE: prior_pipeline.prior = torch.compile(prior_pipeline.prior, mode="reduce-overhead", fullgraph=True) decoder_pipeline.decoder = torch.compile(decoder_pipeline.decoder, mode="max-autotune", fullgraph=True) if PREVIEW_IMAGES: previewer = Previewer() previewer_state_dict = torch.load("previewer/previewer_v1_100k.pt", map_location=torch.device('cpu'))["state_dict"] previewer.load_state_dict(previewer_state_dict) def callback_prior(i, t, latents): output = previewer(latents) output = numpy_to_pil(output.clamp(0, 1).permute(0, 2, 3, 1).float().cpu().numpy()) return output callback_steps = 1 else: previewer = None callback_prior = None callback_steps = Noneelse: prior_pipeline = None decoder_pipeline = None
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed
def generate( prompt: str, negative_prompt: str = "", seed: int = 0, width: int = 1024, height: int = 1024, prior_num_inference_steps: int = 30, # prior_timesteps: List[float] = None, prior_guidance_scale: float = 4.0, decoder_num_inference_steps: int = 12, # decoder_timesteps: List[float] = None, decoder_guidance_scale: float = 0.0, num_images_per_prompt: int = 2,# profile: gr.OAuthProfile | None = None,) -> PIL.Image.Image: previewer.eval().requires_grad_(False).to(device).to(dtype) prior_pipeline.to(device) decoder_pipeline.to(device) generator = torch.Generator().manual_seed(seed) prior_output = prior_pipeline( prompt=prompt, height=height, width=width, num_inference_steps=prior_num_inference_steps, timesteps=DEFAULT_STAGE_C_TIMESTEPS, negative_prompt=negative_prompt, guidance_scale=prior_guidance_scale, num_images_per_prompt=num_images_per_prompt, generator=generator, callback=callback_prior, callback_steps=callback_steps )
if PREVIEW_IMAGES: for _ in range(len(DEFAULT_STAGE_C_TIMESTEPS)): r = next(prior_output) if isinstance(r, list): yield r[0] prior_output = r
decoder_output = decoder_pipeline( image_embeddings=prior_output.image_embeddings, prompt=prompt, num_inference_steps=decoder_num_inference_steps, # timesteps=decoder_timesteps, guidance_scale=decoder_guidance_scale, negative_prompt=negative_prompt, generator=generator, output_type="pil", ).images
yield decoder_output[0]
examples = [ "An astronaut riding a green horse", "A mecha robot in a favela by Tarsila do Amaral", "The sprirt of a Tamagotchi wandering in the city of Los Angeles", "A delicious feijoada ramen dish"]
with gr.Blocks() as demo: gr.Markdown(DESCRIPTION) gr.DuplicateButton( value="Duplicate Space for private use", elem_id="duplicate-button", visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1", ) with gr.Group(): with gr.Row(): prompt = gr.Text( label="Prompt", show_label=False, max_lines=1, placeholder="Введите запрос", container=False, ) run_button = gr.Button("Создать", scale=0) result = gr.Image(label="Result", show_label=False) with gr.Accordion("Дополнительные опции", open=False): negative_prompt = gr.Text( label="Негативный запорос", max_lines=1, placeholder="Введите негативный запрос", )
seed = gr.Slider( label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, ) randomize_seed = gr.Checkbox(label="Случайный seed", value=True) with gr.Row(): width = gr.Slider( label="Ширина", minimum=1024, maximum=MAX_IMAGE_SIZE, step=512, value=1024, ) height = gr.Slider( label="Высота", minimum=1024, maximum=MAX_IMAGE_SIZE, step=512, value=1024, ) num_images_per_prompt = gr.Slider( label="Количество изображений", minimum=1, maximum=2, step=1, value=1, ) with gr.Row(): prior_guidance_scale = gr.Slider( label="Prior Guidance Scale", minimum=0, maximum=20, step=0.1, value=4.0, ) prior_num_inference_steps = gr.Slider( label="Prior Inference Steps", minimum=10, maximum=30, step=1, value=20, )
decoder_guidance_scale = gr.Slider( label="Decoder Guidance Scale", minimum=0, maximum=0, step=0.1, value=0.0, ) decoder_num_inference_steps = gr.Slider( label="Decoder Inference Steps", minimum=4, maximum=12, step=1, value=10, )
gr.Examples( examples=examples, inputs=prompt, outputs=result, fn=generate, cache_examples=CACHE_EXAMPLES, )
inputs = [ prompt, negative_prompt, seed, width, height, prior_num_inference_steps, # prior_timesteps, prior_guidance_scale, decoder_num_inference_steps, # decoder_timesteps, decoder_guidance_scale, num_images_per_prompt, ] gr.on( triggers=[prompt.submit, negative_prompt.submit, run_button.click], fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, queue=False, api_name=False, ).then( fn=generate, inputs=inputs, outputs=result, api_name="run", ) with gr.Blocks(css="style.css") as demo_with_history: with gr.Tab("App"): demo.render()
if __name__ == "__main__": launch_args = { 'inbrowser': args.inbrowser, 'share': args.share, 'server_port' : args.server_port, } demo_with_history.launch(**launch_args)123456789101112131415161718192021222324252627282930313233343536373839404142434445from torch import nn
# Fast Decoder for Stage C latents. E.g. 16 x 24 x 24 -> 3 x 192 x 192class Previewer(nn.Module): def __init__(self, c_in=16, c_hidden=512, c_out=3): super().__init__() self.blocks = nn.Sequential( nn.Conv2d(c_in, c_hidden, kernel_size=1), # 16 channels to 512 channels nn.GELU(), nn.BatchNorm2d(c_hidden),
nn.Conv2d(c_hidden, c_hidden, kernel_size=3, padding=1), nn.GELU(), nn.BatchNorm2d(c_hidden),
nn.ConvTranspose2d(c_hidden, c_hidden // 2, kernel_size=2, stride=2), # 16 -> 32 nn.GELU(), nn.BatchNorm2d(c_hidden // 2),
nn.Conv2d(c_hidden // 2, c_hidden // 2, kernel_size=3, padding=1), nn.GELU(), nn.BatchNorm2d(c_hidden // 2),
nn.ConvTranspose2d(c_hidden // 2, c_hidden // 4, kernel_size=2, stride=2), # 32 -> 64 nn.GELU(), nn.BatchNorm2d(c_hidden // 4),
nn.Conv2d(c_hidden // 4, c_hidden // 4, kernel_size=3, padding=1), nn.GELU(), nn.BatchNorm2d(c_hidden // 4),
nn.ConvTranspose2d(c_hidden // 4, c_hidden // 4, kernel_size=2, stride=2), # 64 -> 128 nn.GELU(), nn.BatchNorm2d(c_hidden // 4),
nn.Conv2d(c_hidden // 4, c_hidden // 4, kernel_size=3, padding=1), nn.GELU(), nn.BatchNorm2d(c_hidden // 4),
nn.Conv2d(c_hidden // 4, c_out, kernel_size=1), )
def forward(self, x): return self.blocks(x)123version https://git-lfs.github.com/spec/v1oid sha256:14a141d7156cf41bd32d6b68e2fc4d2cedb02db1697f862d52458670eb788958size 47820715123version https://git-lfs.github.com/spec/v1oid sha256:76e82483253b24430b20e3e0c98ec2f9aeb45f0b487f7b330bac044b5de0d6f7size 452447731234git+https://github.com/kashif/diffusers.git@diffusers-yield-callbackacceleratesafetensorstransformers123456789101112131415161718192021222324h1 { text-align: center; justify-content: center; }[role="tabpanel"]{border: 0}#duplicate-button { margin: auto; color: #fff; background: #1565c0; border-radius: 100vh;}
.gradio-container { max-width: 690px! important;}
#share-btn-container{padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; max-width: 13rem; margin-left: auto;margin-top: 0.35em;}div#share-btn-container > div {flex-direction: row;background: black;align-items: center}#share-btn-container:hover {background-color: #060606}#share-btn {all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.5rem !important; padding-bottom: 0.5rem !important;right:0;font-size: 15px;}#share-btn * {all: unset}#share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;}#share-btn-container .wrap {display: none !important}#share-btn-container.hidden {display: none!important}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423"""User History is a plugin that you can add to your Spaces to cache generated images for your users.
Key features:- 🤗 Sign in with Hugging Face- Save generated images with their metadata: prompts, timestamp, hyper-parameters, etc.- Export your history as zip.- Delete your history to respect privacy.- Compatible with Persistent Storage for long-term storage.- Admin panel to check configuration and disk usage .
Useful links:- Demo: https://huggingface.co/spaces/Wauplin/gradio-user-history- README: https://huggingface.co/spaces/Wauplin/gradio-user-history/blob/main/README.md- Source file: https://huggingface.co/spaces/Wauplin/gradio-user-history/blob/main/user_history.py- Discussions: https://huggingface.co/spaces/Wauplin/gradio-user-history/discussions"""import jsonimport osimport shutilimport warningsfrom datetime import datetimefrom functools import cachefrom pathlib import Pathfrom typing import Callable, Dict, List, Tuplefrom uuid import uuid4
import gradio as grimport numpy as npimport requestsfrom filelock import FileLockfrom PIL.Image import Image
def setup(folder_path: str | Path | None = None) -> None: user_history = _UserHistory() user_history.folder_path = _resolve_folder_path(folder_path) user_history.initialized = True
def render() -> None: user_history = _UserHistory()
# initialize with default config if not user_history.initialized: print("Initializing user history with default config. Use `user_history.setup(...)` to customize folder_path.") setup()
# Render user history tab gr.Markdown( "## Your past generations\n\nLog in to keep a gallery of your previous generations. Your history will be saved" " and available on your next visit. Make sure to export your images from time to time as this gallery may be" " deleted in the future." )
if os.getenv("SYSTEM") == "spaces" and not os.path.exists("/data"): gr.Markdown( "**⚠️ Persistent storage is disabled, meaning your history will be lost if the Space gets restarted." " Only the Space owner can setup a Persistent Storage. If you are not the Space owner, consider" " duplicating this Space to set your own storage.⚠️**" )
with gr.Row(): gr.LoginButton(min_width=250) #gr.LogoutButton(min_width=250) refresh_button = gr.Button( "Refresh", icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_refresh.png", ) export_button = gr.Button( "Export", icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_download.png", ) delete_button = gr.Button( "Delete history", icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_delete.png", )
# "Export zip" row (hidden by default) with gr.Row(): export_file = gr.File(file_count="single", file_types=[".zip"], label="Exported history", visible=False)
# "Config deletion" row (hidden by default) with gr.Row(): confirm_button = gr.Button("Confirm delete all history", variant="stop", visible=False) cancel_button = gr.Button("Cancel", visible=False)
# Gallery gallery = gr.Gallery( label="Past images", show_label=True, elem_id="gallery", object_fit="contain", columns=5, height=600, preview=False, show_share_button=False, show_download_button=False, ) gr.Markdown( "User history is powered by" " [Wauplin/gradio-user-history](https://huggingface.co/spaces/Wauplin/gradio-user-history). Integrate it to" " your own Space in just a few lines of code!" ) gallery.attach_load_event(_fetch_user_history, every=None)
# Interactions refresh_button.click(fn=_fetch_user_history, inputs=[], outputs=[gallery], queue=False) export_button.click(fn=_export_user_history, inputs=[], outputs=[export_file], queue=False)
# Taken from https://github.com/gradio-app/gradio/issues/3324#issuecomment-1446382045 delete_button.click( lambda: [gr.update(visible=True), gr.update(visible=True)], outputs=[confirm_button, cancel_button], queue=False, ) cancel_button.click( lambda: [gr.update(visible=False), gr.update(visible=False)], outputs=[confirm_button, cancel_button], queue=False, ) confirm_button.click(_delete_user_history).then( lambda: [gr.update(visible=False), gr.update(visible=False)], outputs=[confirm_button, cancel_button], queue=False, )
# Admin section (only shown locally or when logged in as Space owner) _admin_section()
def save_image( profile: gr.OAuthProfile | None, image: Image | np.ndarray | str | Path, label: str | None = None, metadata: Dict | None = None,): # Ignore images from logged out users if profile is None: return username = profile["preferred_username"]
# Ignore images if user history not used user_history = _UserHistory() if not user_history.initialized: warnings.warn( "User history is not set in Gradio demo. Saving image is ignored. You must use `user_history.render(...)`" " first." ) return
# Copy image to storage image_path = _copy_image(image, dst_folder=user_history._user_images_path(username))
# Save new image + metadata if metadata is None: metadata = {} if "datetime" not in metadata: metadata["datetime"] = str(datetime.now()) data = {"path": str(image_path), "label": label, "metadata": metadata} with user_history._user_lock(username): with user_history._user_jsonl_path(username).open("a") as f: f.write(json.dumps(data) + "\n")
############## Internals ##############
class _UserHistory(object): _instance = None initialized: bool = False folder_path: Path
def __new__(cls): # Using singleton pattern => we don't want to expose an object (more complex to use) but still want to keep # state between `render` and `save_image` calls. if cls._instance is None: cls._instance = super(_UserHistory, cls).__new__(cls) return cls._instance
def _user_path(self, username: str) -> Path: path = self.folder_path / username path.mkdir(parents=True, exist_ok=True) return path
def _user_lock(self, username: str) -> FileLock: """Ensure history is not corrupted if concurrent calls.""" return FileLock(self.folder_path / f"{username}.lock") # lock outside of folder => better when exporting ZIP
def _user_jsonl_path(self, username: str) -> Path: return self._user_path(username) / "history.jsonl"
def _user_images_path(self, username: str) -> Path: path = self._user_path(username) / "images" path.mkdir(parents=True, exist_ok=True) return path
def _fetch_user_history(profile: gr.OAuthProfile | None) -> List[Tuple[str, str]]: """Return saved history for that user, if it exists.""" # Cannot load history for logged out users if profile is None: return [] username = profile["preferred_username"]
user_history = _UserHistory() if not user_history.initialized: warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.") return []
with user_history._user_lock(username): # No file => no history saved yet jsonl_path = user_history._user_jsonl_path(username) if not jsonl_path.is_file(): return []
# Read history images = [] for line in jsonl_path.read_text().splitlines(): data = json.loads(line) images.append((data["path"], data["label"] or "")) return list(reversed(images))
def _export_user_history(profile: gr.OAuthProfile | None) -> Dict | None: """Zip all history for that user, if it exists and return it as a downloadable file.""" # Cannot load history for logged out users if profile is None: return None username = profile["preferred_username"]
user_history = _UserHistory() if not user_history.initialized: warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.") return None
# Zip history with user_history._user_lock(username): path = shutil.make_archive( str(_archives_path() / f"history_{username}"), "zip", user_history._user_path(username) )
return gr.update(visible=True, value=path)
def _delete_user_history(profile: gr.OAuthProfile | None) -> None: """Delete all history for that user.""" # Cannot load history for logged out users if profile is None: return username = profile["preferred_username"]
user_history = _UserHistory() if not user_history.initialized: warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.") return
with user_history._user_lock(username): shutil.rmtree(user_history._user_path(username))
##################### Internal helpers #####################
def _copy_image(image: Image | np.ndarray | str | Path, dst_folder: Path) -> Path: """Copy image to the images folder.""" # Already a path => copy it if isinstance(image, str): image = Path(image) if isinstance(image, Path): dst = dst_folder / f"{uuid4().hex}_{Path(image).name}" # keep file ext shutil.copyfile(image, dst) return dst
# Still a Python object => serialize it if isinstance(image, np.ndarray): image = Image.fromarray(image) if isinstance(image, Image): dst = dst_folder / f"{uuid4().hex}.png" image.save(dst) return dst
raise ValueError(f"Unsupported image type: {type(image)}")
def _resolve_folder_path(folder_path: str | Path | None) -> Path: if folder_path is not None: return Path(folder_path).expanduser().resolve()
if os.getenv("SYSTEM") == "spaces" and os.path.exists("/data"): # Persistent storage is enabled! return Path("/data") / "_user_history"
# Not in a Space or Persistent storage not enabled => local folder return Path(__file__).parent / "_user_history"
def _archives_path() -> Path: # Doesn't have to be on persistent storage as it's only used for download path = Path(__file__).parent / "_user_history_exports" path.mkdir(parents=True, exist_ok=True) return path
################## Admin section ##################
def _admin_section() -> None: title = gr.Markdown() title.attach_load_event(_display_if_admin(), every=None)
def _display_if_admin() -> Callable: def _inner(profile: gr.OAuthProfile | None) -> str: if profile is None: return "" if profile["preferred_username"] in _fetch_admins(): return _admin_content() return ""
return _inner
def _admin_content() -> str: return f"""## Admin section
Running on **{os.getenv("SYSTEM", "local")}** (id: {os.getenv("SPACE_ID")}). {_get_msg_is_persistent_storage_enabled()}
Admins: {', '.join(_fetch_admins())}
{_get_nb_users()} user(s), {_get_nb_images()} image(s)
### Configuration
History folder: *{_UserHistory().folder_path}*
Exports folder: *{_archives_path()}*
### Disk usage
{_disk_space_warning_message()}"""
def _get_nb_users() -> int: user_history = _UserHistory() if not user_history.initialized: return 0 if user_history.folder_path is not None and user_history.folder_path.exists(): return len([path for path in user_history.folder_path.iterdir() if path.is_dir()]) return 0
def _get_nb_images() -> int: user_history = _UserHistory() if not user_history.initialized: return 0 if user_history.folder_path is not None and user_history.folder_path.exists(): return len([path for path in user_history.folder_path.glob("*/images/*")]) return 0
def _get_msg_is_persistent_storage_enabled() -> str: if os.getenv("SYSTEM") == "spaces": if os.path.exists("/data"): return "Persistent storage is enabled." else: return ( "Persistent storage is not enabled. This means that user histories will be deleted when the Space is" " restarted. Consider adding a Persistent Storage in your Space settings." ) return ""
def _disk_space_warning_message() -> str: user_history = _UserHistory() if not user_history.initialized: return ""
message = "" if user_history.folder_path is not None: total, used, _ = _get_disk_usage(user_history.folder_path) message += f"History folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
total, used, _ = _get_disk_usage(_archives_path()) message += f"\n\nExports folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
return f"{message.strip()}"
def _get_disk_usage(path: Path) -> Tuple[int, int, int]: for path in [path] + list(path.parents): # first check target_dir, then each parents one by one try: return shutil.disk_usage(path) except OSError: # if doesn't exist or can't read => fail silently and try parent one pass return 0, 0, 0
@cachedef _fetch_admins() -> List[str]: # Running locally => fake user is admin if os.getenv("SYSTEM") != "spaces": return ["FakeGradioUser"]
# Running in Space but no space_id => ??? space_id = os.getenv("SPACE_ID") if space_id is None: return ["Unknown"]
# Running in Space => try to fetch organization members # Otherwise, it's not an organization => namespace is the user namespace = space_id.split("/")[0] response = requests.get(f"https://huggingface.co/api/organizations/{namespace}/members") if response.status_code == 200: return sorted((member["user"] for member in response.json()), key=lambda x: x.lower()) return [namespace]LAUNCHER - CASCADE.batAdded+9
README.md+18-1
app.pyAdded+273
previewer/__pycache__/modules.cpython-310.pycAdded
previewer/modules.pyAdded+45
previewer/previewer_v1_100k.ptAdded+3
previewer/text2img_wurstchen_b_v1_previewer_100k.ptAdded+3
requirements.txtAdded+4
style.cssAdded+24
user_history.pyAdded+423