Spaces:
Running
Running
import gradio as gr | |
import os | |
import shutil | |
import tempfile | |
from huggingface_hub import HfApi, create_repo, create_repo_readme | |
from git import Repo | |
api = HfApi() | |
def clone_and_create(hf_token, github_url, repo_type, private, space_id, port, title, description): | |
if not github_url.strip(): | |
return "GitHub URLを入力してください。" | |
temp_dir = tempfile.mkdtemp() | |
try: | |
# GitHubからクローン | |
Repo.clone_from(github_url, temp_dir) | |
# 自動生成ID | |
if not space_id.strip(): | |
space_id = github_url.strip().rstrip('/').split('/')[-1] | |
# README.mdの処理(Space用) | |
readme_path = os.path.join(temp_dir, "README.md") | |
if repo_type == "space": | |
lines = [] | |
if title.strip(): | |
lines.append(f"# {title.strip()}") | |
if description.strip(): | |
lines.append(f"\n{description.strip()}") | |
if port.strip(): | |
lines.append(f"\napp_port: {port.strip()}") | |
readme_text = "\n".join(lines) | |
with open(readme_path, "w", encoding="utf-8") as f: | |
f.write(readme_text) | |
# huggingface に作成 | |
repo_url = create_repo( | |
name=space_id, | |
token=hf_token, | |
repo_type=repo_type, | |
private=private, | |
exist_ok=False | |
) | |
# リポジトリをpush | |
local_repo = Repo(temp_dir) | |
local_repo.create_remote("hf", repo_url) | |
local_repo.git.push("hf", "HEAD:main") | |
return f"{repo_type} を作成しました:\n{repo_url}" | |
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 を作成") | |
with gr.Row(): | |
login = gr.LoginButton() | |
with gr.Column(): | |
token = gr.Textbox(label="Hugging Face Token(ログイン後自動取得)", type="password") | |
github_url = gr.Textbox(label="GitHub リポジトリURL", placeholder="https://github.com/your/repo") | |
repo_type = gr.Radio(label="作成タイプ", choices=["space", "dataset", "model"], value="space") | |
private = gr.Checkbox(label="非公開にする", value=False) | |
with gr.Group(visible=False) as space_options: | |
space_id = gr.Textbox(label="Space ID(空欄で自動生成)", placeholder="例: my-awesome-space") | |
port = gr.Textbox(label="起動ポート(README.mdに追加)", placeholder="例: 7860") | |
title = gr.Textbox(label="スペース名(READMEのタイトル)", placeholder="例: My Space") | |
description = gr.Textbox(label="説明(READMEのshort_description)", placeholder="例: これは○○なスペースです") | |
repo_type.change(lambda x: gr.update(visible=(x == "space")), inputs=repo_type, outputs=space_options) | |
submit_btn = gr.Button("作成") | |
output = gr.Textbox(label="出力メッセージ", lines=5) | |
def auto_token(login_data): | |
return login_data["access_token"] | |
login.login(auto_token, outputs=token) | |
submit_btn.click( | |
clone_and_create, | |
inputs=[token, github_url, repo_type, private, space_id, port, title, description], | |
outputs=output | |
) | |
demo.launch() | |