John6666 commited on
Commit
eb00743
1 Parent(s): 406daa0

Upload 6 files

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