John6666 commited on
Commit
856a47f
·
verified ·
1 Parent(s): a09ab48

Upload 6 files

Browse files
Files changed (6) hide show
  1. README.md +12 -12
  2. app.py +66 -0
  3. packages.txt +1 -0
  4. pre-requirements.txt +1 -0
  5. requirements.txt +25 -0
  6. utils.py +197 -0
README.md CHANGED
@@ -1,12 +1,12 @@
1
- ---
2
- title: Comfy Test
3
- emoji: 🐢
4
- colorFrom: purple
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 5.1.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: ComfyUI (test)
3
+ emoji:
4
+ colorFrom: pink
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.0.2
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ if os.environ.get("SPACES_ZERO_GPU") is not None:
3
+ import spaces
4
+ else:
5
+ class spaces:
6
+ @staticmethod
7
+ def GPU(func):
8
+ def wrapper(*args, **kwargs):
9
+ return func(*args, **kwargs)
10
+ return wrapper
11
+ import subprocess
12
+ import gc
13
+ from pathlib import Path
14
+ from utils import set_token, get_download_file
15
+
16
+ @spaces.GPU
17
+ def fake_gpu():
18
+ pass
19
+
20
+ HF_TOKEN = os.environ.get("HF_TOKEN")
21
+ CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
22
+ set_token(HF_TOKEN)
23
+ BASE_DIR = Path(__file__).resolve().parent
24
+ DATA_DIR = "data"
25
+ os.makedirs(str(Path(BASE_DIR, DATA_DIR)), exist_ok=True)
26
+
27
+ def get_file(url: str, path: str):
28
+ print(f"Downloading {url} to {path}...")
29
+ get_download_file(path, url, CIVITAI_API_KEY)
30
+
31
+ def git_clone(url: str, path: str, pip: bool=False, addcmd: str=""):
32
+ os.makedirs(str(Path(BASE_DIR, path)), exist_ok=True)
33
+ os.chdir(Path(BASE_DIR, path))
34
+ print(f"Cloning {url} to {path}...")
35
+ cmd = f'git clone {url}'
36
+ print(f'Running {cmd} at {Path.cwd()}')
37
+ i = subprocess.run(cmd, shell=True).returncode
38
+ if i != 0: print(f'Error occured at running {cmd}')
39
+ p = url.split("/")[-1]
40
+ if not Path(p).exists: return
41
+ if pip:
42
+ os.chdir(Path(BASE_DIR, path, p))
43
+ cmd = f'pip install -r requirements.txt'
44
+ print(f'Running {cmd} at {Path.cwd()}')
45
+ i = subprocess.run(cmd, shell=True).returncode
46
+ if i != 0: print(f'Error occured at running {cmd}')
47
+ if addcmd:
48
+ os.chdir(Path(BASE_DIR, path, p))
49
+ cmd = addcmd
50
+ print(f'Running {cmd} at {Path.cwd()}')
51
+ i = subprocess.run(cmd, shell=True).returncode
52
+ if i != 0: print(f'Error occured at running {cmd}')
53
+
54
+ def run(cmd: str):
55
+ print(f'Running {cmd} at {Path.cwd()}')
56
+ i = subprocess.run(cmd, shell=True).returncode
57
+ if i != 0: print(f'Error occured at running {cmd}')
58
+
59
+ git_clone("https://github.com/comfyanonymous/ComfyUI", ".", True)
60
+ run('pip install -U onnxruntime-gpu')
61
+
62
+ get_file("https://huggingface.co/SG161222/RealVisXL_V4.0_Lightning/resolve/main/RealVisXL_V4.0_Lightning.safetensors", "./models/checkpoints/")
63
+
64
+ run(f"python main.py --listen 0.0.0.0 --port 7860 --cpu --output-directory {DATA_DIR}")
65
+
66
+ # https://github.com/comfyanonymous/ComfyUI
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ aria2 git libgl1 libglib2.0-0 make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev git git-lfs ffmpeg libsm6 libxext6 cmake libgl1-mesa-glx
pre-requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pip>=24.1
requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ huggingface-hub
2
+ gdown
3
+ safetensors
4
+ torch
5
+ torchsde
6
+ torchvision
7
+ torchaudio
8
+ einops
9
+ transformers>=4.28.1
10
+ tokenizers>=0.13.3
11
+ sentencepiece
12
+ safetensors>=0.4.2
13
+ aiohttp
14
+ pyyaml
15
+ Pillow
16
+ scipy
17
+ tqdm
18
+ psutil
19
+ kornia>=0.7.1
20
+ spandrel
21
+ soundfile
22
+ datasets
23
+ protobuf<4
24
+ click<8.1
25
+ xformers!=0.0.24
utils.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import HfApi, HfFolder, hf_hub_download, snapshot_download
3
+ import os
4
+ from pathlib import Path
5
+ import shutil
6
+ import gc
7
+ import re
8
+ import urllib.parse
9
+
10
+
11
+ def get_token():
12
+ try:
13
+ token = HfFolder.get_token()
14
+ except Exception:
15
+ token = ""
16
+ return token
17
+
18
+
19
+ def set_token(token):
20
+ try:
21
+ HfFolder.save_token(token)
22
+ except Exception:
23
+ print(f"Error: Failed to save token.")
24
+
25
+
26
+ def get_user_agent():
27
+ return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
28
+
29
+
30
+ def is_repo_exists(repo_id: str, repo_type: str="model"):
31
+ hf_token = get_token()
32
+ api = HfApi(token=hf_token)
33
+ try:
34
+ if api.repo_exists(repo_id=repo_id, repo_type=repo_type, token=hf_token): return True
35
+ else: return False
36
+ except Exception as e:
37
+ print(f"Error: Failed to connect {repo_id} ({repo_type}). {e}")
38
+ return True # for safe
39
+
40
+
41
+ MODEL_TYPE_CLASS = {
42
+ "diffusers:StableDiffusionPipeline": "SD 1.5",
43
+ "diffusers:StableDiffusionXLPipeline": "SDXL",
44
+ "diffusers:FluxPipeline": "FLUX",
45
+ }
46
+
47
+
48
+ def get_model_type(repo_id: str):
49
+ hf_token = get_token()
50
+ api = HfApi(token=hf_token)
51
+ lora_filename = "pytorch_lora_weights.safetensors"
52
+ diffusers_filename = "model_index.json"
53
+ default = "SDXL"
54
+ try:
55
+ if api.file_exists(repo_id=repo_id, filename=lora_filename, token=hf_token): return "LoRA"
56
+ if not api.file_exists(repo_id=repo_id, filename=diffusers_filename, token=hf_token): return "None"
57
+ model = api.model_info(repo_id=repo_id, token=hf_token)
58
+ tags = model.tags
59
+ for tag in tags:
60
+ if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
61
+ except Exception:
62
+ return default
63
+ return default
64
+
65
+
66
+ def list_uniq(l):
67
+ return sorted(set(l), key=l.index)
68
+
69
+
70
+ def list_sub(a, b):
71
+ return [e for e in a if e not in b]
72
+
73
+
74
+ def is_repo_name(s):
75
+ return re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', s)
76
+
77
+
78
+ def split_hf_url(url: str):
79
+ try:
80
+ s = list(re.findall(r'^(?:https?://huggingface.co/)(?:(datasets)/)?(.+?/.+?)/\w+?/.+?/(?:(.+)/)?(.+?.\w+)(?:\?download=true)?$', url)[0])
81
+ if len(s) < 4: return "", "", "", ""
82
+ repo_id = s[1]
83
+ repo_type = "dataset" if s[0] == "datasets" else "model"
84
+ subfolder = urllib.parse.unquote(s[2]) if s[2] else None
85
+ filename = urllib.parse.unquote(s[3])
86
+ return repo_id, filename, subfolder, repo_type
87
+ except Exception as e:
88
+ print(e)
89
+
90
+
91
+ def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
92
+ hf_token = get_token()
93
+ repo_id, filename, subfolder, repo_type = split_hf_url(url)
94
+ try:
95
+ if subfolder is not None: hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder, repo_type=repo_type, local_dir=directory, token=hf_token)
96
+ else: hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type, local_dir=directory, token=hf_token)
97
+ except Exception as e:
98
+ print(f"Failed to download: {e}")
99
+
100
+
101
+ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
102
+ hf_token = get_token()
103
+ url = url.strip()
104
+ if "drive.google.com" in url:
105
+ original_dir = os.getcwd()
106
+ os.chdir(directory)
107
+ os.system(f"gdown --fuzzy {url}")
108
+ os.chdir(original_dir)
109
+ elif "huggingface.co" in url:
110
+ url = url.replace("?download=true", "")
111
+ if "/blob/" in url:
112
+ url = url.replace("/blob/", "/resolve/")
113
+ #user_header = f'"Authorization: Bearer {hf_token}"'
114
+ if True or hf_token:
115
+ download_hf_file(directory, url)
116
+ #os.system(f"aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 {url} -d {directory} -o {url.split('/')[-1]}")
117
+ else:
118
+ os.system(f"aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 {url} -d {directory} -o {url.split('/')[-1]}")
119
+ elif "civitai.com" in url:
120
+ if "?" in url:
121
+ url = url.split("?")[0]
122
+ if civitai_api_key:
123
+ url = url + f"?token={civitai_api_key}"
124
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
125
+ else:
126
+ print("You need an API key to download Civitai models.")
127
+ else:
128
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
129
+
130
+
131
+ def get_local_model_list(dir_path):
132
+ model_list = []
133
+ valid_extensions = ('.safetensors', '.fp16.safetensors', '.sft')
134
+ for file in Path(dir_path).glob("**/*.*"):
135
+ if file.is_file() and file.suffix in valid_extensions:
136
+ file_path = str(file)
137
+ model_list.append(file_path)
138
+ return model_list
139
+
140
+
141
+ def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
142
+ if not "http" in url and is_repo_name(url) and not Path(url).exists():
143
+ print(f"Use HF Repo: {url}")
144
+ new_file = url
145
+ elif not "http" in url and Path(url).exists():
146
+ print(f"Use local file: {url}")
147
+ new_file = url
148
+ elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
149
+ print(f"File to download alreday exists: {url}")
150
+ new_file = f"{temp_dir}/{url.split('/')[-1]}"
151
+ else:
152
+ print(f"Start downloading: {url}")
153
+ before = get_local_model_list(temp_dir)
154
+ try:
155
+ download_thing(temp_dir, url.strip(), civitai_key)
156
+ except Exception:
157
+ print(f"Download failed: {url}")
158
+ return ""
159
+ after = get_local_model_list(temp_dir)
160
+ new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
161
+ if not new_file:
162
+ print(f"Download failed: {url}")
163
+ return ""
164
+ print(f"Download completed: {url}")
165
+ return new_file
166
+
167
+
168
+ # https://huggingface.co/docs/huggingface_hub/v0.25.1/en/package_reference/file_download#huggingface_hub.snapshot_download
169
+ def download_repo(repo_id, dir_path, progress=gr.Progress(track_tqdm=True)):
170
+ hf_token = get_token()
171
+ try:
172
+ snapshot_download(repo_id=repo_id, local_dir=dir_path, token=hf_token, allow_patterns=["*.safetensors", "*.bin"],
173
+ ignore_patterns=["*.fp16.*", "/*.safetensors", "/*.bin"], force_download=True)
174
+ return True
175
+ except Exception as e:
176
+ print(f"Error: Failed to download {repo_id}. {e}")
177
+ gr.Warning(f"Error: Failed to download {repo_id}. {e}")
178
+ return False
179
+
180
+
181
+ def upload_repo(new_repo_id, dir_path, is_private, progress=gr.Progress(track_tqdm=True)):
182
+ hf_token = get_token()
183
+ api = HfApi(token=hf_token)
184
+ try:
185
+ progress(0, desc="Start uploading...")
186
+ api.create_repo(repo_id=new_repo_id, token=hf_token, private=is_private, exist_ok=True)
187
+ for path in Path(dir_path).glob("*"):
188
+ if path.is_dir():
189
+ api.upload_folder(repo_id=new_repo_id, folder_path=str(path), path_in_repo=path.name, token=hf_token)
190
+ elif path.is_file():
191
+ api.upload_file(repo_id=new_repo_id, path_or_fileobj=str(path), path_in_repo=path.name, token=hf_token)
192
+ progress(1, desc="Uploaded.")
193
+ url = f"https://huggingface.co/{new_repo_id}"
194
+ except Exception as e:
195
+ print(f"Error: Failed to upload to {new_repo_id}. {e}")
196
+ return ""
197
+ return url