John6666 commited on
Commit
32e0736
1 Parent(s): 3ec9212

Upload 6 files

Browse files
Files changed (3) hide show
  1. README.md +2 -2
  2. app.py +15 -6
  3. t2i_space.py +88 -77
README.md CHANGED
@@ -1,10 +1,10 @@
1
  ---
2
- title: Gradio Demo Space creation helper
3
  emoji: 🐶
4
  colorFrom: yellow
5
  colorTo: red
6
  sdk: gradio
7
- sdk_version: 4.41.0
8
  app_file: app.py
9
  pinned: false
10
  ---
 
1
  ---
2
+ title: Gradio Demo Space creation helper V2
3
  emoji: 🐶
4
  colorFrom: yellow
5
  colorTo: red
6
  sdk: gradio
7
+ sdk_version: 4.44.0
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py CHANGED
@@ -3,7 +3,7 @@ from t2i_space import get_t2i_space_contents
3
 
4
  css = """"""
5
 
6
- with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
7
  gr.Markdown("# Gradio Demo Space creation helper")
8
  gr.Markdown(
9
  f"""
@@ -18,17 +18,26 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
18
  )
19
  with gr.Column():
20
  repo_id = gr.Textbox(label="Model repo ID", placeholder="username/modelname", value="", max_lines=1)
21
- with gr.Row():
22
- gradio_version = gr.Textbox(label="Gradio version", placeholder="username/modelname", value="4.44.0", max_lines=1)
23
- private_ok = gr.Checkbox(label="Allow private repo", value=True)
 
 
 
 
 
 
 
 
24
  run_button = gr.Button(value="Submit")
25
  space_file = gr.Files(label="Output", interactive=False)
 
26
 
27
  gr.on(
28
  triggers=[repo_id.submit, run_button.click],
29
  fn=get_t2i_space_contents,
30
- inputs=[repo_id, gradio_version, private_ok],
31
- outputs=[space_file],
32
  )
33
 
34
  demo.queue()
 
3
 
4
  css = """"""
5
 
6
+ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css) as demo:
7
  gr.Markdown("# Gradio Demo Space creation helper")
8
  gr.Markdown(
9
  f"""
 
18
  )
19
  with gr.Column():
20
  repo_id = gr.Textbox(label="Model repo ID", placeholder="username/modelname", value="", max_lines=1)
21
+ with gr.Accordion("Advanced", open=False):
22
+ with gr.Row():
23
+ gradio_version = gr.Textbox(label="Gradio version", placeholder="username/modelname", value="4.44.0", max_lines=1)
24
+ private_ok = gr.Checkbox(label="Allow private repo", value=True)
25
+ with gr.Row():
26
+ hf_user = gr.Textbox(label="Your HF user ID (Optional)", placeholder="username", value="", max_lines=1)
27
+ hf_repo = gr.Textbox(label="New space name (Optional)", placeholder="spacename", info="If empty, auto-complete", value="", max_lines=1)
28
+ hf_token = gr.Textbox(label="Your HF write token (Optional)", placeholder="hf_...", value="", max_lines=1)
29
+ with gr.Row():
30
+ is_private = gr.Checkbox(label="Create private repo (Optional)", value=True)
31
+ is_setkey = gr.Checkbox(label="Set your token to space (Optional)", info="For private / gated models", value=False)
32
  run_button = gr.Button(value="Submit")
33
  space_file = gr.Files(label="Output", interactive=False)
34
+ output_md = gr.Markdown(label="Output")
35
 
36
  gr.on(
37
  triggers=[repo_id.submit, run_button.click],
38
  fn=get_t2i_space_contents,
39
+ inputs=[repo_id, gradio_version, private_ok, hf_user, hf_repo, is_private, is_setkey, hf_token],
40
+ outputs=[space_file, output_md],
41
  )
42
 
43
  demo.queue()
t2i_space.py CHANGED
@@ -1,77 +1,88 @@
1
- from pathlib import Path
2
- import os
3
- import gradio as gr
4
- from huggingface_hub import HfApi, HfFolder, CommitOperationAdd, create_repo, Repository
5
-
6
- def is_repo_name(s):
7
- import re
8
- return re.fullmatch(r'^[^/,\s]+?/[^/,\s]+?$', s)
9
-
10
- def is_repo_exists(repo_id):
11
- api = HfApi()
12
- try:
13
- return api.repo_exists(repo_id=repo_id, repo_type="space")
14
- except Exception as e:
15
- print(f"Error: Failed to connect {repo_id}.")
16
- return True # for safe handling
17
-
18
- def save_space_contents(repo_id: str, gradio_version: str, private_ok: bool, dir: str):
19
- if not is_repo_name(repo_id):
20
- gr.Info(f"Error: Invalid repo ID: {repo_id}.")
21
- return []
22
- if not private_ok and not is_repo_exists(repo_id):
23
- gr.Info(f"Error: Repo doesn't exist: {repo_id}.")
24
- return []
25
- os.makedirs(dir, exist_ok=True)
26
- model_name = repo_id.split("/")[-1]
27
- app_py = f"""import gradio as gr
28
- import os
29
- demo = gr.load("{repo_id}", src="models", hf_token=os.environ.get("HF_TOKEN")).launch()
30
- """
31
- readme_md = f"""---
32
- title: {model_name} Demo
33
- emoji: 🖼
34
- colorFrom: purple
35
- colorTo: red
36
- sdk: gradio
37
- sdk_version: {gradio_version}
38
- app_file: app.py
39
- pinned: false
40
- ---
41
-
42
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
43
- """
44
- app_path = str(Path(dir, "app.py"))
45
- with open(app_path, mode='w', encoding="utf-8") as f:
46
- f.write(app_py)
47
- readme_path = str(Path(dir, "README.md"))
48
- with open(readme_path, mode='w', encoding="utf-8") as f:
49
- f.write(readme_md)
50
- return [app_path, readme_path]
51
-
52
- def upload_to_space(repo_id, app_path, readme_path):
53
- api = HfApi()
54
- token = HfFolder.get_token()
55
-
56
- # Create the repo if it does not exist
57
- if not is_repo_exists(repo_id):
58
- create_repo(repo_id, repo_type="space", token=token, private=False)
59
-
60
- # Upload files to the repository
61
- operations = [
62
- CommitOperationAdd(path_in_repo="app.py", path_or_fileobj=app_path),
63
- CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=readme_path),
64
- ]
65
- api.create_commit(
66
- repo_id=repo_id,
67
- repo_type="space",
68
- operations=operations,
69
- commit_message="Add Gradio app and README",
70
- token=token,
71
- )
72
- print(f"Files uploaded successfully to {repo_id}.")
73
-
74
- def get_t2i_space_contents(repo_id: str, gradio_version: str, private_ok: bool):
75
- paths = save_space_contents(repo_id, gradio_version, private_ok, "./temp/")
76
- if paths:
77
- upload_to_space(repo_id, *paths)
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import os
3
+ import gradio as gr
4
+ from huggingface_hub import HfApi, HfFolder, CommitOperationAdd, create_repo
5
+
6
+
7
+ def is_repo_name(s):
8
+ import re
9
+ return re.fullmatch(r'^[^/,\s]+?/[^/,\s]+?$', s)
10
+
11
+
12
+ def get_token():
13
+ try:
14
+ token = HfFolder.get_token()
15
+ except Exception as e:
16
+ token = ""
17
+ return token
18
+
19
+
20
+ def is_repo_exists(repo_id: str):
21
+ api = HfApi(token=get_token())
22
+ try:
23
+ if api.repo_exists(repo_id=repo_id, repo_type="model"): return True
24
+ else: return False
25
+ except Exception as e:
26
+ print(f"Error: Failed to connect {repo_id}. {e}")
27
+ return True # for safe
28
+
29
+
30
+ def is_repo_t2i(repo_id: str):
31
+ api = HfApi(token=get_token())
32
+ try:
33
+ model_info = api.repo_info(repo_id=repo_id, repo_type="model")
34
+ if model_info.pipeline_tag == "text-to-image": return True
35
+ else: return False
36
+ except Exception as e:
37
+ print(f"Error: Failed to connect {repo_id}. {e}")
38
+ return True # for safe
39
+
40
+
41
+ def save_space_contents(repo_id: str, gradio_version: str, private_ok: bool, dir: str, template_dir: str = "template"):
42
+ if not is_repo_name(repo_id):
43
+ gr.Info(f"Error: Invalid repo ID: {repo_id}.")
44
+ return []
45
+ if not private_ok and not is_repo_exists(repo_id):
46
+ gr.Info(f"Error: Repo doesn't exist: {repo_id}.")
47
+ return []
48
+ os.makedirs(dir, exist_ok=True)
49
+ model_name = repo_id.split("/")[-1]
50
+ files = []
51
+ for readpath in Path(template_dir).glob("*.*"):
52
+ with open(readpath, mode='r', encoding="utf-8") as f:
53
+ content = str(f.read())
54
+ content = content.format(repo_id=repo_id, model_name=model_name, gradio_version=gradio_version)
55
+ writepath = str(Path(dir, readpath.name))
56
+ with open(writepath, mode='w', encoding="utf-8") as f:
57
+ f.write(content)
58
+ files.append(writepath)
59
+ return files
60
+
61
+
62
+ def upload_to_space(repo_id: str, paths: list[str], is_private: bool, is_setkey: bool):
63
+ token = get_token()
64
+ api = HfApi(token=token)
65
+ try:
66
+ # Create the repo if it does not exist
67
+ if not is_repo_exists(repo_id):
68
+ create_repo(repo_id, repo_type="space", space_sdk="gradio", token=token, private=is_private,
69
+ space_secrets=[{"key": "HF_TOKEN", "value": token}] if is_setkey else [{"key": "HF_TOKEN", "value": ""}])
70
+ # Upload files to the repository
71
+ operations = [CommitOperationAdd(path_in_repo=Path(p).name, path_or_fileobj=p) for p in paths]
72
+ api.create_commit(repo_id=repo_id, repo_type="space", operations=operations,
73
+ commit_message="Add Gradio app and README", token=token)
74
+ print(f"Files uploaded successfully to {repo_id}.")
75
+ return repo_id
76
+ except Exception as e:
77
+ raise gr.Error(f"Failed to upload files to {repo_id}. {e}")
78
+
79
+
80
+ 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):
81
+ HfFolder.save_token(hf_token)
82
+ paths = save_space_contents(repo_id, gradio_version, private_ok, "./temp/", "./template")
83
+ if hf_repo == "": new_repo_id = f"{hf_user}/{repo_id.split('/')[-1]}" # model name
84
+ else: new_repo_id = f"{hf_user}/{hf_repo}"
85
+ if hf_token and hf_user and upload_to_space(new_repo_id, paths, is_private, is_setkey):
86
+ md = f"Your new repo:<br>https://huggingface.co/spaces/{new_repo_id}"
87
+ else: md = ""
88
+ return paths, md