File size: 2,198 Bytes
32e0736
 
 
 
 
 
 
 
 
eb00743
 
 
32e0736
 
 
 
eb00743
32e0736
 
 
eb00743
 
 
32e0736
 
 
 
 
eb00743
32e0736
eb00743
32e0736
eb00743
 
32e0736
 
 
 
 
 
 
eb00743
 
 
 
 
 
 
 
 
 
 
 
 
 
32e0736
eb00743
32e0736
eb00743
 
 
 
 
 
 
 
32e0736
 
eb00743
 
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
from pathlib import Path
import os
import gradio as gr

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


def is_repo_exists(repo_id):
    from huggingface_hub import HfApi
    api = HfApi()
    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}.")
        return True # for safe


def is_repo_t2i(repo_id):
    from huggingface_hub import HfApi
    api = HfApi()
    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}.")
        return True # for safe
    

def save_space_contents(repo_id: str, gradio_version: str, private_ok: bool, dir: str):
    if not is_repo_name(repo_id): #  or not is_repo_t2i(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]
    app_py = f"""import gradio as gr

import os

demo = gr.load("{repo_id}", src="models", hf_token=os.environ.get("HF_TOKEN")).launch()

"""
    readme_md = f"""---

title: {model_name} Demo

emoji: 🖼

colorFrom: purple

colorTo: red

sdk: gradio

sdk_version: {gradio_version}

app_file: app.py

pinned: false

---



Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference



"""
    app_path = str(Path(dir, "app.py"))
    with open(app_path, mode='w', encoding="utf-8") as f:
        f.write(app_py)
    readme_path = str(Path(dir, "README.md"))
    with open(readme_path, mode='w', encoding="utf-8") as f:
        f.write(readme_md)
    return [app_path, readme_path]


def get_t2i_space_contents(repo_id: str, gradio_version: str, private_ok: bool):
    return save_space_contents(repo_id, gradio_version, private_ok, "./temp/")