Spaces:
Sleeping
Sleeping
import gradio as gr | |
import os | |
import shutil | |
import tempfile | |
from huggingface_hub import HfApi | |
from git import Repo | |
api = HfApi() | |
def clone_and_create(hf_token, git_url, repo_type, private, space_id, port, title, description): | |
if not git_url.strip(): | |
return "Git リポジトリのURLを入力してください。" | |
temp_dir = tempfile.mkdtemp() | |
try: | |
# リポジトリをクローン(github 以外も可) | |
Repo.clone_from(git_url, temp_dir) | |
# 空欄ならIDをリポジトリ名から自動生成 | |
if not space_id.strip(): | |
space_id = git_url.rstrip("/").split("/")[-1].replace(".git", "") | |
user_info = api.whoami(token=hf_token) | |
repo_id = f"{user_info['name']}/{space_id}" | |
# Hugging Face 上でリポジトリ作成 | |
api.create_repo( | |
repo_id=repo_id, | |
repo_type=repo_type, | |
private=private, | |
token=hf_token, | |
exist_ok=False | |
) | |
# README.md の作成(Space のときだけ) | |
if repo_type == "space": | |
readme_path = os.path.join(temp_dir, "README.md") | |
readme_lines = [] | |
if title.strip(): | |
readme_lines.append(f"# {title.strip()}") | |
if description.strip(): | |
readme_lines.append(f"\n{description.strip()}") | |
if port.strip(): | |
readme_lines.append(f"\napp_port: {port.strip()}") | |
if readme_lines: | |
with open(readme_path, "w", encoding="utf-8") as f: | |
f.write("\n".join(readme_lines)) | |
# クローンしたファイルをアップロード | |
api.upload_folder( | |
folder_path=temp_dir, | |
repo_id=repo_id, | |
repo_type=repo_type, | |
token=hf_token | |
) | |
return f"✅ {repo_type} を作成しました!\nhttps://huggingface.co/{repo_type}s/{space_id}" | |
except Exception as e: | |
return f"❌ エラー: {str(e)}" | |
finally: | |
shutil.rmtree(temp_dir) | |
with gr.Blocks(title="Hugging Face リポジトリ作成ツール") as demo: | |
gr.Markdown("## 🛠️ Hugging Face Space / Dataset / Model 作成ツール") | |
login = gr.LoginButton() | |
with gr.Column(): | |
token = gr.Textbox(label="Hugging Face トークン", type="password") | |
git_url = gr.Textbox(label="Git リポジトリのURL(GitHub / GitLab など)", placeholder="https://...") | |
repo_type = gr.Radio(label="作成タイプ", choices=["space", "dataset", "model"], value="space") | |
private = gr.Checkbox(label="非公開にする", value=False) | |
with gr.Group(visible=True) as space_options: | |
space_id = gr.Textbox(label="Space ID(空欄で自動生成)", placeholder="例: my-space") | |
port = gr.Textbox(label="起動ポート(READMEに記載)", placeholder="例: 7860") | |
title = gr.Textbox(label="スペース名(READMEタイトル)", placeholder="例: My App") | |
description = gr.Textbox(label="説明文(READMEに記載)", placeholder="例: これは〇〇なスペースです") | |
repo_type.change(lambda t: gr.update(visible=(t == "space")), inputs=repo_type, outputs=space_options) | |
submit_btn = gr.Button("作成") | |
output = gr.Textbox(label="出力", lines=5) | |
# ログイン成功時にトークンを自動取得 | |
def on_login(login_data): | |
return login_data["access_token"] | |
login.login(on_login, outputs=token) | |
# 実行 | |
submit_btn.click( | |
fn=clone_and_create, | |
inputs=[token, git_url, repo_type, private, space_id, port, title, description], | |
outputs=output | |
) | |
demo.launch() | |