File size: 3,683 Bytes
32e0736
 
 
f26fd20
 
32e0736
 
 
 
 
 
f26fd20
 
 
 
 
 
 
 
 
 
32e0736
 
 
 
f26fd20
32e0736
 
 
f26fd20
 
32e0736
 
 
 
 
f26fd20
32e0736
 
f26fd20
 
 
32e0736
 
 
 
 
 
 
f26fd20
 
 
 
 
 
 
 
 
 
32e0736
 
f26fd20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32e0736
 
f26fd20
 
 
 
 
 
 
 
 
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
from pathlib import Path
import os
import gradio as gr
from huggingface_hub import HfApi, HfFolder, CommitOperationAdd, create_repo


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


def get_token():
    try:
        token = HfFolder.get_token()
    except Exception:
        token = ""
    return token


def is_repo_exists(repo_id: str):
    api = HfApi(token=get_token())
    try:
        if api.repo_exists(repo_id=repo_id, repo_type="model"): return True
        else: return False
    except Exception as e:
        print(f"Error: Failed to connect {repo_id}. {e}")
        return True # for safe


def is_repo_t2i(repo_id: str):
    api = HfApi(token=get_token())
    try:
        model_info = api.repo_info(repo_id=repo_id, repo_type="model")
        if model_info.pipeline_tag == "text-to-image": return True
        else: return False
    except Exception as e:
        print(f"Error: Failed to connect {repo_id}. {e}")
        return True # for safe


def save_space_contents(repo_id: str, gradio_version: str, private_ok: bool, dir: str, template_dir: str = "template"):
    if not is_repo_name(repo_id):
        gr.Info(f"Error: Invalid repo ID: {repo_id}.")
        return []
    if not private_ok and not is_repo_exists(repo_id):
        gr.Info(f"Error: Repo doesn't exist: {repo_id}.")
        return []
    os.makedirs(dir, exist_ok=True)
    model_name = repo_id.split("/")[-1]
    files = []
    for readpath in Path(template_dir).glob("*.*"):
        with open(readpath, mode='r', encoding="utf-8") as f:
            content = str(f.read())
        content = content.format(repo_id=repo_id, model_name=model_name, gradio_version=gradio_version)
        writepath = str(Path(dir, readpath.name))
        with open(writepath, mode='w', encoding="utf-8") as f:
            f.write(content)
        files.append(writepath)
    return files


def upload_to_space(repo_id: str, paths: list[str], is_private: bool, is_setkey: bool):
    token = get_token()
    api = HfApi(token=token)
    try:
        # Create the repo if it does not exist
        if not is_repo_exists(repo_id):
            if is_setkey: create_repo(repo_id, repo_type="space", space_sdk="gradio", token=token, private=is_private,
                                      space_secrets=[{"key": "HF_TOKEN", "value": token}])
            else: create_repo(repo_id, repo_type="space", space_sdk="gradio", token=token, private=is_private)
            
        # Upload files to the repository
        operations = [CommitOperationAdd(path_in_repo=Path(p).name, path_or_fileobj=p) for p in paths]
        api.create_commit(repo_id=repo_id, repo_type="space", operations=operations,
                          commit_message="Add Gradio app and README", token=token)
        print(f"Files uploaded successfully to {repo_id}.")
        return repo_id
    except Exception as e:
        raise gr.Error(f"Failed to upload files to {repo_id}. {e}")


def get_t2i_space_contents(repo_id: str, gradio_version: str, private_ok: bool, hf_user: str, hf_repo: str, is_private: bool, is_setkey: bool, hf_token: str):
    HfFolder.save_token(hf_token)
    paths = save_space_contents(repo_id, gradio_version, private_ok, "./temp/", "./template")
    if hf_repo == "": new_repo_id = f"{hf_user}/{repo_id.split('/')[-1]}" # model name
    else: new_repo_id = f"{hf_user}/{hf_repo}"
    if hf_token and hf_user and upload_to_space(new_repo_id, paths, is_private, is_setkey):
        md = f"Your new repo:<br>https://huggingface.co/spaces/{new_repo_id}"
    else: md = ""
    return paths, md