from flask import Flask, render_template, request, jsonify import requests import os import json import time app = Flask(__name__) # Function to fetch trending spaces from Huggingface def fetch_trending_spaces(limit=100): try: url = "https://huggingface.co/api/spaces" params = { "limit": limit, "sort": "trending", "direction": -1 } response = requests.get(url, params=params, timeout=10) if response.status_code == 200: return response.json() else: print(f"Error fetching trending spaces: {response.status_code}") return [] except Exception as e: print(f"Exception when fetching trending spaces: {e}") return [] # Transform Huggingface URL to direct space URL def transform_url(owner, name): return f"https://{owner}-{name}.hf.space" # Get space details def get_space_details(space_data): try: # Basic info owner = space_data.get('owner') name = space_data.get('id') title = space_data.get('title') or name # URL construction original_url = f"https://huggingface.co/spaces/{owner}/{name}" embed_url = transform_url(owner, name) # Get likes count likes_count = space_data.get('likes', 0) # Tags tags = space_data.get('tags', []) return { 'url': original_url, 'embedUrl': embed_url, 'title': title, 'owner': owner, 'likes_count': likes_count, 'tags': tags } except Exception as e: print(f"Error processing space data: {e}") return None # Homepage route @app.route('/') def home(): return render_template('index.html') # Trending spaces API @app.route('/api/trending-spaces', methods=['GET']) def trending_spaces(): search_query = request.args.get('search', '').lower() limit = int(request.args.get('limit', 100)) # Fetch trending spaces spaces_data = fetch_trending_spaces(limit) # Process and filter spaces results = [] for space_data in spaces_data: space_info = get_space_details(space_data) if not space_info: continue # Apply search filter if needed if search_query: title = space_info['title'].lower() owner = space_info['owner'].lower() url = space_info['url'].lower() tags = ' '.join(space_info.get('tags', [])).lower() if (search_query not in title and search_query not in owner and search_query not in url and search_query not in tags): continue results.append(space_info) return jsonify(results) if __name__ == '__main__': # Create templates folder os.makedirs('templates', exist_ok=True) # Create index.html file with open('templates/index.html', 'w', encoding='utf-8') as f: f.write('''