Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import gradio as grfrom huggingface_hub import HfApi, HfFolderfrom huggingface_hub.utils import HfHubHTTPError# Helper function to initialize the HfApi clientdef get_hf_api(token):if not token:raise gr.Error("Hugging Face API token is required.")return HfApi(token=token)# --- Spaces Functions ---def list_user_spaces(token, author):try:api = get_hf_api(token)spaces = api.list_spaces(author=author)return "\n".join([space.id for space in spaces]) if spaces else "No spaces found for this user."except HfHubHTTPError as e:return f"Error: {e}"def create_space(token, repo_id, repo_type, space_sdk):try:api = get_hf_api(token)repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, space_sdk=space_sdk)return f"Space created successfully! URL: {repo_url}"except HfHubHTTPError as e:return f"Error: {e}"def delete_space(token, repo_id):try:api = get_hf_api(token)api.delete_repo(repo_id=repo_id, repo_type='space')return f"Space '{repo_id}' deleted successfully."except HfHubHTTPError as e:return f"Error: {e}"# --- Models Functions ---def list_user_models(token, author):try:api = get_hf_api(token)models = api.list_models(author=author)return "\n".join([model.id for model in models]) if models else "No models found for this user."except HfHubHTTPError as e:return f"Error: {e}"def delete_model(token, repo_id):try:api = get_hf_api(token)api.delete_repo(repo_id=repo_id, repo_type='model')return f"Model '{repo_id}' deleted successfully."except HfHubHTTPError as e:return f"Error: {e}"# --- Datasets Functions ---def list_user_datasets(token, author):try:api = get_hf_api(token)datasets = api.list_datasets(author=author)return "\n".join([dataset.id for dataset in datasets]) if datasets else "No datasets found for this user."except HfHubHTTPError as e:return f"Error: {e}"def delete_dataset(token, repo_id):try:api = get_hf_api(token)api.delete_repo(repo_id=repo_id, repo_type='dataset')return f"Dataset '{repo_id}' deleted successfully."except HfHubHTTPError as e:return f"Error: {e}"# --- User Info Functions ---def whoami(token):try:api = get_hf_api(token)user_info = api.whoami()return user_infoexcept HfHubHTTPError as e:return f"Error: {e}"def get_user_info(token, user):try:api = get_hf_api(token)user_info = api.get_user_info(user)return user_infoexcept HfHubHTTPError as e:return f"Error: {e}"with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# Hugging Face Hub Toolkit")gr.Markdown("A Gradio interface for interacting with the Hugging Face Hub. Enter your Hugging Face API token with 'write' permissions to use the tools.")with gr.Row():hf_token = gr.Textbox(label="Hugging Face API Token", type="password", placeholder="hf_...")with gr.Tabs():with gr.TabItem("Spaces"):with gr.Row():with gr.Column():gr.Markdown("### List User Spaces")list_spaces_author = gr.Textbox(label="Author (Username)")list_spaces_btn = gr.Button("List Spaces")list_spaces_output = gr.Textbox(label="User Spaces", lines=10)with gr.Column():gr.Markdown("### Create a New Space")create_space_id = gr.Textbox(label="Space Repo ID (e.g., username/spacename)")create_space_sdk = gr.Dropdown(label="Space SDK", choices=["gradio", "streamlit", "docker", "static"])create_space_btn = gr.Button("Create Space")create_space_output = gr.Textbox(label="Result")with gr.Column():gr.Markdown("### Delete a Space")delete_space_id = gr.Textbox(label="Space Repo ID to Delete")delete_space_btn = gr.Button("Delete Space")delete_space_output = gr.Textbox(label="Result")with gr.TabItem("Models"):with gr.Row():with gr.Column():gr.Markdown("### List User Models")list_models_author = gr.Textbox(label="Author (Username)")list_models_btn = gr.Button("List Models")list_models_output = gr.Textbox(label="User Models", lines=10)with gr.Column():gr.Markdown("### Delete a Model")delete_model_id = gr.Textbox(label="Model Repo ID to Delete")delete_model_btn = gr.Button("Delete Model")delete_model_output = gr.Textbox(label="Result")with gr.TabItem("Datasets"):with gr.Row():with gr.Column():gr.Markdown("### List User Datasets")list_datasets_author = gr.Textbox(label="Author (Username)")list_datasets_btn = gr.Button("List Datasets")list_datasets_output = gr.Textbox(label="User Datasets", lines=10)with gr.Column():gr.Markdown("### Delete a Dataset")delete_dataset_id = gr.Textbox(label="Dataset Repo ID to Delete")delete_dataset_btn = gr.Button("Delete Dataset")delete_dataset_output = gr.Textbox(label="Result")with gr.TabItem("User Info"):with gr.Row():with gr.Column():gr.Markdown("### Who Am I?")whoami_btn = gr.Button("Get My Info")whoami_output = gr.JSON(label="My User Info")with gr.Column():gr.Markdown("### Get User Info")get_user_info_user = gr.Textbox(label="Username")get_user_info_btn = gr.Button("Get User Info")get_user_info_output = gr.JSON(label="User Info")# --- Event Handlers ---# Spaceslist_spaces_btn.click(list_user_spaces, inputs=[hf_token, list_spaces_author], outputs=list_spaces_output)create_space_btn.click(create_space, inputs=[hf_token, create_space_id, gr.Textbox(value="space", visible=False), create_space_sdk], outputs=create_space_output)delete_space_btn.click(delete_space, inputs=[hf_token, delete_space_id], outputs=delete_space_output)# Modelslist_models_btn.click(list_user_models, inputs=[hf_token, list_models_author], outputs=list_models_output)delete_model_btn.click(delete_model, inputs=[hf_token, delete_model_id], outputs=delete_model_output)# Datasetslist_datasets_btn.click(list_user_datasets, inputs=[hf_token, list_datasets_author], outputs=list_datasets_output)delete_dataset_btn.click(delete_dataset, inputs=[hf_token, delete_dataset_id], outputs=delete_dataset_output)# User Infowhoami_btn.click(whoami, inputs=hf_token, outputs=whoami_output)get_user_info_btn.click(get_user_info, inputs=[hf_token, get_user_info_user], outputs=get_user_info_output)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318import gradio as grfrom huggingface_hub import HfApifrom huggingface_hub.utils import HfHubHTTPError, RepositoryNotFoundErrorimport osimport uuid# --- State Management and API Client ---def get_hf_api(token):if not token:# Allow read-only operations without a tokenreturn HfApi()return HfApi(token=token)# --- UI Functions ---def handle_token_change(token):"""Called when the token is entered. Fetches user info and enables/disables UI elements."""if not token:# No token, so disable write actions and clear usernameupdate_dict = {# In 'Actions' panelmanage_files_btn: gr.update(interactive=False),delete_repo_btn: gr.update(interactive=False),# In 'Editor' panelcommit_btn: gr.update(interactive=False),# In 'List Repos' panelauthor_input: gr.update(value=""),# User info outputwhoami_output: gr.update(value=None, visible=False)}return (None, "") + (gr.update(),) * (len(update_dict))try:api = get_hf_api(token)user_info = api.whoami()username = user_info.get('name')# Token is valid, enable write actionsupdate_dict = {manage_files_btn: gr.update(interactive=True),delete_repo_btn: gr.update(interactive=True),commit_btn: gr.update(interactive=True),author_input: gr.update(value=username),whoami_output: gr.update(value=user_info, visible=True)}# The first two return values update gr.State objectsreturn (token, username, *update_dict.values())except HfHubHTTPError as e:# Token is invalidgr.Warning(f"Invalid Token: {e}. You can only perform read-only actions.")update_dict = {manage_files_btn: gr.update(interactive=False),delete_repo_btn: gr.update(interactive=False),commit_btn: gr.update(interactive=False),whoami_output: gr.update(value=None, visible=False)}# Clear username but keep the invalid token for read-only API callsreturn (token, "", *update_dict.values())def list_repos(token, author, repo_type):"""Lists repositories for a given author and type."""if not author:gr.Info("Please enter an author (username or organization) to list repositories.")return gr.update(choices=[], value=None), gr.update(visible=False)try:api = get_hf_api(token)repos = api.list_repos(author=author, repo_type=repo_type)repo_ids = [repo.id for repo in repos]return gr.update(choices=repo_ids, value=None), gr.update(visible=False)except HfHubHTTPError as e:gr.Error(f"Could not list repositories: {e}")return gr.update(choices=[], value=None), gr.update(visible=False)def handle_repo_selection(repo_id):"""Called when a repo is selected. Makes action buttons visible."""if repo_id:return gr.update(visible=True), gr.update(visible=False) # Show actions, hide editorreturn gr.update(visible=False), gr.update(visible=False) # Hide everythingdef delete_repo(token, repo_id, repo_type):"""Deletes the selected repository."""if not token:gr.Error("A write-enabled Hugging Face token is required to delete a repository.")returnif not repo_id:gr.Warning("No repository selected to delete.")returntry:api = get_hf_api(token)api.delete_repo(repo_id=repo_id, repo_type=repo_type)gr.Info(f"Successfully deleted '{repo_id}'. Please re-list repositories.")# Clear selection and hide action/editor panelsreturn None, gr.update(visible=False), gr.update(visible=False)except HfHubHTTPError as e:gr.Error(f"Failed to delete repository: {e}")return repo_id, gr.update(visible=True), gr.update(visible=False) # Keep state on failure# --- File Editor Functions ---def show_file_manager(token, repo_id, repo_type):"""Lists files in the selected repo and shows the editor panel."""if not repo_id:gr.Warning("No repository selected.")return gr.update(visible=False)try:api = get_hf_api(token)repo_files = api.list_repo_files(repo_id=repo_id, repo_type=repo_type)# Don't show .gitattributes or other hidden files by defaultfiltered_files = [f for f in repo_files if not f.startswith('.')]# Update UI components for the editorreturn (gr.update(visible=True), # Show editor panelgr.update(choices=filtered_files, value=None), # Update file dropdowngr.update(value=f"## Select a file from the dropdown to view or edit its content.", language=None), # Clear code view"" # Clear commit message)except RepositoryNotFoundError:gr.Error(f"Repository '{repo_id}' not found. It might be private and require a token.")return gr.update(visible=False), gr.update(), gr.update(), gr.update()except Exception as e:gr.Error(f"Could not list files: {e}")return gr.update(visible=False), gr.update(), gr.update(), gr.update()def load_file_content(token, repo_id, repo_type, filepath):"""Downloads and displays the content of a selected file."""if not filepath:return gr.update(value="## Select a file to view its content.", language='markdown')try:api = get_hf_api(token)# Download the file to a temporary local pathlocal_path = api.hf_hub_download(repo_id=repo_id,repo_type=repo_type,filename=filepath,token=token,)with open(local_path, 'r', encoding='utf-8') as f:content = f.read()# Determine language for syntax highlightinglanguage = os.path.splitext(filepath)[1].lstrip('.')if language in ['py', 'js', 'html', 'css', 'json', 'md']:return gr.update(value=content, language=language)else:return gr.update(value=content, language='plaintext')except Exception as e:gr.Error(f"Could not load file '{filepath}': {e}")return gr.update(value=f"Error loading file: {e}", language='plaintext')def commit_file(token, repo_id, repo_type, filepath, content, commit_message):"""Commits the edited file content back to the repository."""if not token:gr.Error("A write-enabled token is required to commit changes.")returnif not filepath:gr.Warning("No file is selected to commit.")returnif not commit_message:gr.Warning("Commit message cannot be empty.")returntry:# Write content to a temporary file to upload ittemp_dir = "hf_temp_files"os.makedirs(temp_dir, exist_ok=True)# Use a unique filename to avoid conflictstemp_file_path = os.path.join(temp_dir, f"{uuid.uuid4()}_{os.path.basename(filepath)}")with open(temp_file_path, "w", encoding="utf-8") as f:f.write(content)api = get_hf_api(token)api.upload_file(path_or_fileobj=temp_file_path,path_in_repo=filepath,repo_id=repo_id,repo_type=repo_type,commit_message=commit_message,)# Clean up the temporary fileos.remove(temp_file_path)gr.Info(f"Successfully committed '{filepath}' to '{repo_id}'!")except Exception as e:gr.Error(f"Failed to commit file: {e}")# --- Gradio UI Layout ---with gr.Blocks(theme=gr.themes.Soft(), title="Hugging Face Hub Toolkit") as demo:# State managementhf_token_state = gr.State(None)username_state = gr.State("")selected_repo_id = gr.State(None)selected_repo_type = gr.State("space") # Default to spacesgr.Markdown("# Hugging Face Hub Dashboard")gr.Markdown("An intuitive interface to manage your Hugging Face repositories. **Enter a write-token for full access.**")with gr.Row():hf_token = gr.Textbox(label="Hugging Face API Token (write permission recommended)",type="password",placeholder="hf_...",scale=3,)whoami_output = gr.JSON(label="Authenticated User", visible=False, scale=1)with gr.Row():# PANEL 1: List and Select Reposwith gr.Column(scale=1):gr.Markdown("### 1. Select a Repository")author_input = gr.Textbox(label="Author (Username or Org)")with gr.Tabs() as repo_type_tabs:# This helper function creates the list button and radio selector for a repo typedef create_repo_lister(repo_type, label):with gr.Tab(label, id=repo_type):gr.Button(f"List {label}").click(fn=list_repos,inputs=[hf_token_state, author_input, gr.State(repo_type)],outputs=[repo_selector, editor_panel])create_repo_lister("space", "Spaces")create_repo_lister("model", "Models")create_repo_lister("dataset", "Datasets")repo_selector = gr.Radio(label="Select a Repository", interactive=True)# PANEL 2 & 3: Actions and Editorwith gr.Column(scale=3):with gr.Row():# PANEL 2: Action Buttonswith gr.Column(scale=1, visible=False) as action_panel:gr.Markdown("### 2. Choose an Action")manage_files_btn = gr.Button("Manage Files", interactive=False)delete_repo_btn = gr.Button("Delete this Repo", variant="stop", interactive=False)# PANEL 3: File Editorwith gr.Column(scale=3, visible=False) as editor_panel:gr.Markdown("### 3. Edit Files")file_selector = gr.Dropdown(label="Select File", interactive=True)code_editor = gr.Code(label="File Content", language="markdown", interactive=True)commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Update README.md", interactive=True)commit_btn = gr.Button("Commit Changes", variant="primary", interactive=False)# --- Event Wiring ---# When token changes, update auth state and UIhf_token.change(fn=handle_token_change,inputs=hf_token,outputs=[hf_token_state,username_state,manage_files_btn,delete_repo_btn,commit_btn,author_input,whoami_output])# When repo type tab is changed, store the new type and clear selectiondef on_tab_change(repo_type):return repo_type, None, gr.update(choices=[], value=None), gr.update(visible=False), gr.update(visible=False)repo_type_tabs.select(fn=on_tab_change,inputs=repo_type_tabs,outputs=[selected_repo_type, selected_repo_id, repo_selector, action_panel, editor_panel])# When a repo is selected, update state and show the action panelrepo_selector.select(fn=lambda repo_id: (repo_id, *handle_repo_selection(repo_id)),inputs=repo_selector,outputs=[selected_repo_id, action_panel, editor_panel])# Action button clicksmanage_files_btn.click(fn=show_file_manager,inputs=[hf_token_state, selected_repo_id, selected_repo_type],outputs=[editor_panel, file_selector, code_editor, commit_message_input])delete_repo_btn.click(fn=delete_repo,inputs=[hf_token_state, selected_repo_id, selected_repo_type],outputs=[selected_repo_id, action_panel, editor_panel],# Add a confirmation popup before deletingjs="() => confirm('Are you sure you want to permanently delete this repository? This action cannot be undone.')")# Editor interactionsfile_selector.change(fn=load_file_content,inputs=[hf_token_state, selected_repo_id, selected_repo_type, file_selector],outputs=code_editor)commit_btn.click(fn=commit_file,inputs=[hf_token_state, selected_repo_id, selected_repo_type, file_selector, code_editor, commit_message_input],outputs=[])if __name__ == "__main__":demo.launch(debug=True)
app.py+280-135