from pathlib import Path import os import gradio as gr from huggingface_hub import HfApi, HfFolder, CommitOperationAdd, create_repo, Repository def is_repo_name(s): import re return re.fullmatch(r'^[^/,\s]+?/[^/,\s]+?$', s) def is_repo_exists(repo_id): api = HfApi() try: return api.repo_exists(repo_id=repo_id, repo_type="space") except Exception as e: print(f"Error: Failed to connect {repo_id}.") return True # for safe handling def save_space_contents(repo_id: str, gradio_version: str, private_ok: bool, dir: str): 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] 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 upload_to_space(repo_id, app_path, readme_path): api = HfApi() token = HfFolder.get_token() # Create the repo if it does not exist if not is_repo_exists(repo_id): create_repo(repo_id, repo_type="space", token=token, private=False) # Upload files to the repository operations = [ CommitOperationAdd(path_in_repo="app.py", path_or_fileobj=app_path), CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=readme_path), ] 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}.") def get_t2i_space_contents(repo_id: str, gradio_version: str, private_ok: bool): paths = save_space_contents(repo_id, gradio_version, private_ok, "./temp/") if paths: upload_to_space(repo_id, *paths)