File size: 6,476 Bytes
3385bd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import gradio as gr
from huggingface_hub import HfApi, HfFolder, hf_hub_download, snapshot_download
import os
from pathlib import Path
import shutil
import gc
import re
import urllib.parse
import subprocess
import time
from typing import Any





def get_state(state: dict, key: str):
    if key in state.keys(): return state[key]
    else:
        print(f"State '{key}' not found.")
        return None


def set_state(state: dict, key: str, value: Any):
    state[key] = value


def get_user_agent():
    return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'




MODEL_TYPE_CLASS = {
    "diffusers:StableDiffusionPipeline": "SD 1.5",
    "diffusers:StableDiffusionXLPipeline": "SDXL",
    "diffusers:FluxPipeline": "FLUX",
}


def get_model_type(repo_id: str):
    hf_token = get_token()
    api = HfApi(token=hf_token)
    lora_filename = "pytorch_lora_weights.safetensors"
    diffusers_filename = "model_index.json"
    default = "SDXL"
    try:
        if api.file_exists(repo_id=repo_id, filename=lora_filename, token=hf_token): return "LoRA"
        if not api.file_exists(repo_id=repo_id, filename=diffusers_filename, token=hf_token): return "None"
        model = api.model_info(repo_id=repo_id, token=hf_token)
        tags = model.tags
        for tag in tags:
            if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
    except Exception:
        return default
    return default


def list_uniq(l):
    return sorted(set(l), key=l.index)


def list_sub(a, b):
    return [e for e in a if e not in b]


def is_repo_name(s):
    return re.fullmatch(r'^[\w_\-\.]+/[\w_\-\.]+$', s)




def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
    try:
        url = url.strip()
        if "drive.google.com" in url:
            original_dir = os.getcwd()
            os.chdir(directory)
            subprocess.run(f"gdown --fuzzy {url}", shell=True)
            os.chdir(original_dir)
        elif "huggingface.co" in url:
            url = url.replace("?download=true", "")
            if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
            download_hf_file(directory, url)
        elif "civitai.com" in url:
            if civitai_api_key:
                url = f"'{url}&token={civitai_api_key}'" if "?" in url else f"{url}?token={civitai_api_key}"
                print(f"Downloading {url}")
                subprocess.run(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}", shell=True)
            else:
                print("You need an API key to download Civitai models.")
        else:
            os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
    except Exception as e:
        print(f"Failed to download: {e}")


def get_local_file_list(dir_path, recursive=False):
    file_list = []
    pattern = "**/*.*" if recursive else "*/*.*"
    for file in Path(dir_path).glob(pattern):
        if file.is_file():
            file_path = str(file)
            file_list.append(file_path)
    return file_list


def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
    try:
        if not "http" in url and is_repo_name(url) and not Path(url).exists():
            print(f"Use HF Repo: {url}")
            new_file = url
        elif not "http" in url and Path(url).exists():
            print(f"Use local file: {url}")
            new_file = url
        elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
            print(f"File to download alreday exists: {url}")
            new_file = f"{temp_dir}/{url.split('/')[-1]}"
        else:
            print(f"Start downloading: {url}")
            recursive = False if "huggingface.co" in url else True
            before = get_local_file_list(temp_dir, recursive)
            download_thing(temp_dir, url.strip(), civitai_key)
            after = get_local_file_list(temp_dir, recursive)
            new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
        if not new_file:
            print(f"Download failed: {url}")
            return ""
        print(f"Download completed: {url}")
        return new_file
    except Exception as e:
        print(f"Download failed: {url} {e}")
        return ""




def gate_repo(repo_id: str, gated_str: str, repo_type: str="model"):
    hf_token = get_token()
    api = HfApi(token=hf_token)
    try:
        if gated_str == "auto": gated = "auto"
        elif gated_str == "manual": gated = "manual"
        else: gated = False
        api.update_repo_settings(repo_id=repo_id, gated=gated, repo_type=repo_type, token=hf_token)
    except Exception as e:
        print(f"Error: Failed to update settings {repo_id}. {e}")


HF_SUBFOLDER_NAME = ["None", "user_repo"]




BASE_DIR = os.getcwd()
CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")


def get_file(url: str, path: str): # requires aria2, gdown
    print(f"Downloading {url} to {path}...")
    get_download_file(path, url, CIVITAI_API_KEY)


def git_clone(url: str, path: str, pip: bool=False, addcmd: str=""): # requires git
    os.makedirs(str(Path(BASE_DIR, path)), exist_ok=True)
    os.chdir(Path(BASE_DIR, path))
    print(f"Cloning {url} to {path}...")
    cmd = f'git clone {url}'
    print(f'Running {cmd} at {Path.cwd()}')
    i = subprocess.run(cmd, shell=True).returncode
    if i != 0: print(f'Error occured at running {cmd}')
    p = url.split("/")[-1]
    if not Path(p).exists: return
    if pip:
        os.chdir(Path(BASE_DIR, path, p))
        cmd = f'pip install -r requirements.txt'
        print(f'Running {cmd} at {Path.cwd()}')
        i = subprocess.run(cmd, shell=True).returncode
        if i != 0: print(f'Error occured at running {cmd}')
    if addcmd:
        os.chdir(Path(BASE_DIR, path, p))
        cmd = addcmd
        print(f'Running {cmd} at {Path.cwd()}')
        i = subprocess.run(cmd, shell=True).returncode
        if i != 0: print(f'Error occured at running {cmd}')


def run(cmd: str, timeout: float=0):
    print(f'Running {cmd} at {Path.cwd()}')
    if timeout == 0:
        i = subprocess.run(cmd, shell=True).returncode
        if i != 0: print(f'Error occured at running {cmd}')
    else:
        p = subprocess.Popen(cmd, shell=True)
        time.sleep(timeout)
        p.terminate()
        print(f'Terminated in {timeout} seconds')