from typing import List, Dict import httpx import gradio as gr import pandas as pd from huggingface_hub import HfApi, ModelCard, snapshot_download, login import base64 import io import zipfile import asyncio import aiohttp from pathlib import Path import emoji import tempfile import shutil import os # Search Terms example_search_terms = [ {"id": "gpt-3", "emoji": "🤖"}, {"id": "stable-diffusion", "emoji": "🎨"}, {"id": "whisper", "emoji": "🗣️"}, {"id": "bert", "emoji": "📖"}, {"id": "resnet", "emoji": "🖼️"} ] # Initialize HuggingFace with access token def init_huggingface(token: str): """Initialize HuggingFace with access token.""" try: login(token=token) return True except Exception as e: print(f"Error logging in: {str(e)}") return False def format_link(item: Dict, number: int, search_type: str) -> str: """Format a link for display in the UI.""" link = item['link'] readme_link = f"{link}/blob/main/README.md" title = f"{number}. {item['id']}" metadata = f"Author: {item['author']}" if 'downloads' in item: metadata += f", Downloads: {item['downloads']}" html = f"""
""" return html def display_results(df: pd.DataFrame): """Display search results in HTML format.""" if df is not None and not df.empty: html = "No results found.
" def SwarmyTime(data: List[Dict]) -> Dict: """Aggregates all content from the given data.""" aggregated = { "total_items": len(data), "unique_authors": set(), "total_downloads": 0, "item_types": {"Models": 0, "Datasets": 0, "Spaces": 0} } for item in data: aggregated["unique_authors"].add(item.get("author", "Unknown")) aggregated["total_downloads"] += item.get("downloads", 0) if "modelId" in item: aggregated["item_types"]["Models"] += 1 elif "dataset" in item.get("id", ""): aggregated["item_types"]["Datasets"] += 1 else: aggregated["item_types"]["Spaces"] += 1 aggregated["unique_authors"] = len(aggregated["unique_authors"]) return aggregated def search_and_aggregate(query, search_type, token, example_term): if example_term: query = example_term.split(" ")[1] # Extract the user ID from the button label df = search_hub(query, search_type, token) data = df.to_dict('records') aggregated = SwarmyTime(data) html_results = display_results(df) return [ html_results, "Status: Ready to download", "", aggregated, search_type, data ] def search_hub(query: str, search_type: str, token: str = None) -> pd.DataFrame: """Search the Hugging Face Hub for models, datasets, or spaces.""" api = HfApi(token=token) if search_type == "Models": results = api.list_models(search=query) data = [{"id": model.modelId, "author": model.author, "downloads": model.downloads, "link": f"https://huggingface.co/{model.modelId}"} for model in results] elif search_type == "Datasets": results = api.list_datasets(search=query) data = [{"id": dataset.id, "author": dataset.author, "downloads": dataset.downloads, "link": f"https://huggingface.co/datasets/{dataset.id}"} for dataset in results] elif search_type == "Spaces": results = api.list_spaces(search=query) data = [{"id": space.id, "author": space.author, "link": f"https://huggingface.co/spaces/{space.id}"} for space in results] else: data = [] for i, item in enumerate(data, 1): item['number'] = i item['formatted_link'] = format_link(item, i, search_type) return pd.DataFrame(data) async def download_readme(session: aiohttp.ClientSession, item: Dict, token: str) -> tuple[str, str]: """Download README.md file for a given item.""" item_id = item['id'] # Different base URLs for different repository types if 'datasets' in item['link']: raw_url = f"https://huggingface.co/datasets/{item_id}/raw/main/README.md" alt_url = f"https://huggingface.co/datasets/{item_id}/raw/master/README.md" elif 'spaces' in item['link']: raw_url = f"https://huggingface.co/spaces/{item_id}/raw/main/README.md" alt_url = f"https://huggingface.co/spaces/{item_id}/raw/master/README.md" else: # Models raw_url = f"https://huggingface.co/{item_id}/raw/main/README.md" alt_url = f"https://huggingface.co/{item_id}/raw/master/README.md" headers = {"Authorization": f"Bearer {token}"} if token else {} try: # Try main branch first async with session.get(raw_url, headers=headers) as response: if response.status == 200: content = await response.text() return item_id.replace('/', '_'), content # If main branch fails, try master branch if response.status in [401, 404]: async with session.get(alt_url, headers=headers) as alt_response: if alt_response.status == 200: content = await alt_response.text() return item_id.replace('/', '_'), content # If both attempts fail, return error message error_msg = f"# Error downloading README for {item_id}\n" if response.status == 401: error_msg += "Authentication required. Please provide a valid HuggingFace token." else: error_msg += f"Status code: {response.status}" return item_id.replace('/', '_'), error_msg except Exception as e: return item_id.replace('/', '_'), f"# Error downloading README for {item_id}\nError: {str(e)}" async def download_all_readmes(data: List[Dict], token: str) -> tuple[str, str]: """Download all README files and create a zip archive.""" if not data: return "", "No results to download" zip_buffer = io.BytesIO() status_message = "Downloading READMEs..." failed_downloads = [] async with aiohttp.ClientSession() as session: tasks = [download_readme(session, item, token) for item in data] results = await asyncio.gather(*tasks) with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file: for filename, content in results: if "Error downloading README" in content: failed_downloads.append(filename) zip_file.writestr(f"{filename}.md", content) zip_buffer.seek(0) base64_zip = base64.b64encode(zip_buffer.getvalue()).decode() status = "READMEs ready for download!" if failed_downloads: status += f" (Failed to download {len(failed_downloads)} READMEs)" download_link = f"""Note: Some READMEs could not be downloaded. Please check the zip file for details.
' if failed_downloads else ''}