# GRADIO HF SPACE import gradio as gr import requests import pandas as pd from datetime import datetime, timedelta import urllib.parse def get_hf_models_by_category(): """ Fetch top 3 models from each Hugging Face category ranked by likes7d """ # Hugging Face API endpoint api_url = "https://huggingface.co/api/models" # Common model categories on Hugging Face categories = [ "text-generation", "text-classification", "token-classification", "question-answering", "fill-mask", "summarization", "translation", "text2text-generation", "image-classification", "object-detection", "image-segmentation", "text-to-image", "image-to-text", "automatic-speech-recognition", "audio-classification", "text-to-speech", "audio-to-audio", "voice-activity-detection", "depth-estimation", "image-feature-extraction", "other" ] results = {} for category in categories: try: # Fetch models for this category, sorted by likes in the last 7 days params = { "pipeline_tag": category, "sort": "likes7d", "direction": -1, "limit": 3, "full": True # Get full model info including downloads } response = requests.get(api_url, params=params, timeout=10) if response.status_code == 200: models = response.json() category_models = [] for model in models: # Try different field names for model ID model_id = model.get("id") or model.get("modelId") or model.get("_id", "Unknown") # Get likes (might be in different fields) likes = (model.get("likes") or model.get("likesRecent") or model.get("likes7d") or 0) # Get downloads (different possible field names) downloads = (model.get("downloads") or model.get("downloadsAllTime") or model.get("downloads_all_time") or model.get("downloads_last_month", 0)) # Get last modified date last_modified = (model.get("lastModified") or model.get("last_modified") or model.get("createdAt") or model.get("updatedAt") or "Unknown") model_info = { "name": model_id, "likes": likes, "downloads": downloads, "updated": last_modified, "url": f"https://huggingface.co/{model_id}" } category_models.append(model_info) if category_models: # Only add if we found models results[category] = category_models except Exception as e: print(f"Error fetching {category}: {str(e)}") continue return results def format_number(num): """Format large numbers in a readable way""" if num >= 1000000: return f"{num/1000000:.1f}M" elif num >= 1000: return f"{num/1000:.1f}k" else: return str(num) def format_date(date_str): """Format date string to be more readable""" if date_str == "Unknown" or not date_str: return "Unknown" try: # Parse the ISO date string and format it if "T" in date_str: date_obj = datetime.fromisoformat(date_str.replace("Z", "+00:00")) return date_obj.strftime("%Y-%m-%d") else: return date_str[:10] # Just take the date part except: return "Unknown" def format_model_display(models_data): """ Format the models data into a nice display format """ if not models_data: return "No models found or API unavailable." html_content = """

🤗 Top 3 Hugging Face Models by Category (Last 7 Days)

""" for category, models in models_data.items(): if not models: continue # Format category name category_display = category.replace("-", " ").title() html_content += f"""

🏆 {category_display}

""" for i, model in enumerate(models[:3], 1): medal = "đŸĨ‡" if i == 1 else "đŸĨˆ" if i == 2 else "đŸĨ‰" # Format the numbers and date likes_formatted = format_number(model['likes']) downloads_formatted = format_number(model['downloads']) date_formatted = format_date(model['updated']) author = model['name'].split("/")[0] model_name = model['name'].split("/")[-1] model_normal_name = model_name.replace("-", " ").title() # Create YouTube search URL youtube_search_query = urllib.parse.quote(f"{model_normal_name} {author} AI") youtube_url = f"https://www.youtube.com/results?search_query={youtube_search_query}" html_content += f"""
{medal}

#{i}

{model['name']}

â¤ī¸
Likes
{likes_formatted}
đŸ“Ĩ
Downloads
{downloads_formatted}
🕒
Updated
{date_formatted}
🤗 View Model đŸ“ē Find on YouTube
""" html_content += """
""" html_content += f"""

📊 Data fetched from Hugging Face API â€ĸ Updated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} UTC

Rankings based on likes received in the last 7 days â€ĸ Found {len(models_data)} categories with active models

""" return html_content def refresh_models(): """ Refresh and get the latest model data """ models_data = get_hf_models_by_category() formatted_display = format_model_display(models_data) return formatted_display # Create Gradio interface def create_interface(): with gr.Blocks( title="🤗 Top HF Models by Category", theme=gr.themes.Soft(), css=""" .gradio-container { max-width: 1400px !important; } .gr-button { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; border: none !important; color: white !important; } """ ) as demo: gr.Markdown(""" # 🤗 Hugging Face Model Explorer Discover the most popular models across different categories on Hugging Face! This space shows the **top 3 models** in each category ranked by **likes received in the last 7 days**. Click the refresh button to get the latest rankings! """) with gr.Row(): refresh_btn = gr.Button( "🔄 Refresh Rankings", variant="primary", size="lg" ) with gr.Row(): gr.Markdown(""" **đŸŽ¯ What you'll see:** - â¤ī¸ **Likes**: Community appreciation in the last 7 days - đŸ“Ĩ **Downloads**: Total download count (all-time) - 🕒 **Updated**: Last modification date - 🤗 **View Model**: Direct link to model page - đŸ“ē **Find on YouTube**: Search for tutorials and demos """) output_html = gr.HTML( value=refresh_models(), # Load initial data label="Top Models by Category" ) refresh_btn.click( fn=refresh_models, outputs=output_html ) gr.Markdown(""" --- ### â„šī¸ About This Space - **Data Source**: Hugging Face Models API (`/api/models`) - **Ranking Metric**: Likes received in the last 7 days (`sort=likes7d`) - **Categories**: All major model types (text, image, audio, multimodal, etc.) - **Update Frequency**: Real-time (when you click refresh) **Note**: Only categories with available models are displayed. Some specialized categories might not appear if no models are currently trending. 🚀 **Pro tip**: Use the YouTube button to find tutorials, demos, and implementation guides for each model! """) return demo # Launch the application if __name__ == "__main__": demo = create_interface() demo.launch( server_name="0.0.0.0", # For Hugging Face Spaces server_port=7860, # Standard port for HF Spaces share=False, debug=False )