t2i-demo-creator / t2i_space.py
John6666's picture
Upload t2i_space.py
5870f39 verified
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