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: # 트렌딩 스페이스 가져오기 (원래의 API 파라미터 사용) url = "https://huggingface.co/api/spaces" params = { "limit": limit, "sort": "trending" # 단순히 trending 파라미터만 사용 } response = requests.get(url, params=params, timeout=10) if response.status_code == 200: # None 값이 있는 항목 필터링 spaces = response.json() filtered_spaces = [space for space in spaces if space.get('owner') != 'None' and space.get('id', '').split('/', 1)[0] != 'None'] return filtered_spaces 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: # 공통 정보 추출 if '/' in space_data.get('id', ''): owner, name = space_data.get('id', '').split('/', 1) else: owner = space_data.get('owner', '') name = space_data.get('id', '') # None이 포함된 경우 무시 if owner == 'None' or name == 'None': return None # URL 구성 original_url = f"https://huggingface.co/spaces/{owner}/{name}" embed_url = transform_url(owner, name) # 좋아요 수 likes_count = space_data.get('likes', 0) # 제목 추출 title = space_data.get('title', name) # 태그 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 index, space_data in enumerate(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([str(tag) for tag in 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('''