Spaces:
Sleeping
Sleeping
Update app.py
Browse files22 unmodified lines232425262728292 unmodified lines3233343536373839404142434445467 unmodified lines545556575859606162631 unmodified line6566676869707136 unmodified lines10810911011111211311411519 unmodified lines1351361371381391401411421434 unmodified lines1481491501511521531548 unmodified lines1631641651661671681691 unmodified line1711721731741751761771781791801811821831841852 unmodified lines1881891901911921931941 unmodified line1961971981992002012022032042052062072082092102112122132142152162172182192202212222233 unmodified lines22722822923023123223311 unmodified lines245246247248249250251556 unmodified lines80880981081181281381481581681781881982082182282382482582682710 unmodified lines8388398408418428438448458468478488498508519 unmodified lines86186286386486586686786817 unmodified lines886887888889890891892339 unmodified lines123212331234123512361237123812 unmodified lines12511252125312541255125612573 unmodified lines12611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091 unmodified line13111312131313141315131613171318131913206 unmodified lines132713281329133013311332133342 unmodified lines1376137713781379138013811382138337 unmodified lines1421142214231424142514261427142814291430143114321433143414351436143717 unmodified lines145514561457145814591460146148 unmodified lines15101511151215131514151515161517151815191520152122 unmodified lines'createdAt': '2023-01-01T00:00:00.000Z','hardware': 'cpu','user': {'avatar_url': None, # 어차피 안 쓰임 (이모지 대체)'name': 'dummyUser'}})2 unmodified lines# Function to fetch Zero-GPU (CPU-based) Spaces from Huggingface with paginationdef fetch_trending_spaces(offset=0, limit=72):"""hardware=cpu & sort=trending 파라미터로:- GPU 없는 스페이스만, 트렌딩 순 정렬로 최대 10000개"""try:url = "https://huggingface.co/api/spaces"params = {"limit": 10000,"hardware": "cpu","sort": "trending" # 트렌딩 기준}response = requests.get(url, params=params, timeout=30)7 unmodified linesand space.get('id', '').split('/', 1)[0] != 'None']start = min(offset, len(filtered_spaces))end = min(offset + limit, len(filtered_spaces))print(f"[fetch_trending_spaces] CPU기반 스페이스 총 {len(filtered_spaces)}개(트렌딩 정렬), "f"요청 구간 {start}~{end-1} 반환")return {1 unmodified line'total': len(filtered_spaces),'offset': offset,'limit': limit,'all_spaces': filtered_spaces # 통계용 (전체)}else:print(f"Error fetching spaces: {response.status_code}")36 unmodified lines# Get space detailsdef get_space_details(space_data, index, offset):"""Zero-GPU 스페이스 상세 정보 추출(description, user info 등) + rank 계산"""try:if '/' in space_data.get('id', ''):19 unmodified lines# Descriptionshort_desc = space_data.get('description', '')# User infouser_info = space_data.get('user', {})# avatar_url = user_info.get('avatar_url', '') # <-- 사용하지 않음 (이모지로 대체)author_name = user_info.get('name') or ownerreturn {4 unmodified lines'name': name,'likes_count': likes_count,'description': short_desc,# 'avatar_url': avatar_url, # 이모지로 대체'author_name': author_name,'rank': offset + index + 1}8 unmodified lines'name': 'error','likes_count': 0,'description': '',# 'avatar_url': '','author_name': 'huggingface','rank': offset + index + 1}1 unmodified line# Get owner statistics from all spacesdef get_owner_stats(all_spaces):"""all_spaces는 이미 트렌딩 순으로 정렬된 상태.-> 상위 1000개만 골라서(owner) 개수를 세어상위 30명을 산출."""# TOP 1000만 추려서 rank<=1000로 간주top_1000_spaces = all_spaces[:1000]owners = []for space in top_1000_spaces:if '/' in space.get('id', ''):owner, _ = space.get('id', '').split('/', 1)else:2 unmodified linesif owner != 'None':owners.append(owner)owner_counts = Counter(owners)top_owners = owner_counts.most_common(30)return top_owners1 unmodified line# Homepage route@app.route('/')def home():return render_template('index.html')# Zero-GPU spaces API@app.route('/api/trending-spaces', methods=['GET'])def trending_spaces():"""hardware=cpu & sort=trending 로 가져온 리스트에서검색, 페이징 적용 + top 1000 집계"""search_query = request.args.get('search', '').lower()offset = int(request.args.get('offset', 0))limit = int(request.args.get('limit', 72)) # Default 72spaces_data = fetch_trending_spaces(offset, limit)results = []for index, space_data in enumerate(spaces_data['spaces']):space_info = get_space_details(space_data, index, offset)if not space_info:continue# 검색 필터if search_query:if (search_query not in space_info['title'].lower()and search_query not in space_info['owner'].lower()3 unmodified linesresults.append(space_info)# 상위 1000 기준 top 30 owner 집계top_owners = get_owner_stats(spaces_data.get('all_spaces', []))return jsonify({11 unmodified lines# Create templates folder if not existsos.makedirs('templates', exist_ok=True)# index.html 전체 작성 (이모지로 대체, 상위 1000 랭크 통계)with open('templates/index.html', 'w', encoding='utf-8') as f:f.write('''<!DOCTYPE html><html lang="en">556 unmodified lines}}/* 이모지로 대체하기 위한 클래스 (아바타 대신) */.emoji-avatar {font-size: 1.5rem;border: 1px solid #ccc;width: 32px;height: 32px;border-radius: 50%;display: flex;align-items: center;justify-content: center;margin-right: 8px;}/* 기존 아바타 관련 CSS는 제거/미사용 */</style></head><body>10 unmodified lines<div class="mac-content"><div class="header"><h1>ZeroGPU Spaces Leaderboard</h1><p>Discover CPU-based (No GPU) spaces from Hugging Face</p></div><!-- Tab Navigation --><div class="tab-nav"><button id="tabTrendingButton" class="tab-button active">Trending</button><button id="tabFixedButton" class="tab-button">Picks</button></div><!-- Trending(Zero GPU) Tab Content -->9 unmodified lines</div><div class="mac-content"><div class="stats-header"><!-- 변경된 타이틀(Top 30 Creators by Count Number of TOP 1000 RANK) --><div class="stats-title">Top 30 Creators by Count Number of TOP 1000 Rank</div><button id="statsToggle" class="stats-toggle">Show Stats</button></div><div id="statsContent" class="stats-content">17 unmodified lines<div id="pagination" class="pagination"></div></div><!-- Fixed Tab Content --><div id="fixedTab" class="tab-content"><div id="fixedGrid" class="grid-container"></div></div>339 unmodified linescontainer.appendChild(errorPlaceholder);}// (1) Trending Tab(Zero GPU) - 이모지로 대체function renderGrid(spaces) {elements.gridContainer.innerHTML = '';12 unmodified linestry {const {url, title, likes_count, owner, name, rank,description, author_name, embedUrl} = item;const gridItem = document.createElement('div');3 unmodified linesconst headerDiv = document.createElement('div');headerDiv.className = 'grid-header';// 첫줄: 이모지 아바타 + 제목 + ZERO GPU 배지// => 이 코드에서는 ZERO GPU 배지 대신, 본래 코드를 약간 단순화const headerTop = document.createElement('div');headerTop.className = 'grid-header-top';// 왼쪽: 이모지const leftWrapper = document.createElement('div');leftWrapper.style.display = 'flex';leftWrapper.style.alignItems = 'center';const emojiAvatar = document.createElement('div');emojiAvatar.className = 'emoji-avatar';emojiAvatar.textContent = '🤖'; // 이모지leftWrapper.appendChild(emojiAvatar);const titleEl = document.createElement('h3');titleEl.textContent = title;titleEl.title = title;leftWrapper.appendChild(titleEl);headerTop.appendChild(leftWrapper);// 오른쪽: rankconst rankBadge = document.createElement('div');rankBadge.className = 'rank-badge';rankBadge.textContent = `#${rank}`;headerTop.appendChild(rankBadge);headerDiv.appendChild(headerTop);// 둘째줄: owner + likesconst metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';const ownerEl = document.createElement('div');ownerEl.className = 'owner-info';ownerEl.textContent = `by ${author_name}`;metaInfo.appendChild(ownerEl);const likesCounter = document.createElement('div');likesCounter.className = 'likes-counter';likesCounter.innerHTML = `♥ <span>${likes_count}</span>`;metaInfo.appendChild(likesCounter);headerDiv.appendChild(metaInfo);gridItem.appendChild(headerDiv);1 unmodified line// descriptionif (description) {const descP = document.createElement('p');descP.style.padding = '0 15px';descP.style.fontSize = '0.85rem';descP.style.color = '#444';descP.style.marginTop = '6px';descP.textContent = description;gridItem.appendChild(descP);}6 unmodified linesiframeContainer.className = 'iframe-container';const iframe = document.createElement('iframe');iframe.src = embedUrl;iframe.title = title;iframe.allow = 'accelerometer; camera; encrypted-media; geolocation; gyroscope;';iframe.setAttribute('allowfullscreen', '');42 unmodified lines});}// (2) Fixed Tab - 이모지로 대체function renderFixedGrid() {fixedGridContainer.innerHTML = '';const staticSpaces = [37 unmodified linesstaticSpaces.forEach((item) => {try {const { url, title, likes_count, owner, name, rank } = item;const gridItem = document.createElement('div');gridItem.className = 'grid-item';const header = document.createElement('div');header.className = 'grid-header';// 첫줄(top): 이모지 + 제목 + rankconst headerTop = document.createElement('div');headerTop.className = 'grid-header-top';const leftWrapper = document.createElement('div');leftWrapper.style.display = 'flex';leftWrapper.style.alignItems = 'center';17 unmodified linesheader.appendChild(headerTop);// 둘째줄(meta): owner + likesconst metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';48 unmodified lineslinkEl.target = '_blank';linkEl.className = 'open-link';linkEl.textContent = 'Open in new window';actions.appendChild(linkEl);gridItem.appendChild(content);gridItem.appendChild(actions);fixedGridContainer.appendChild(gridItem);} catch (error) {console.error('Fixed tab rendering error:', error);}22 unmodified lines232425262728292 unmodified lines3233343536373839404142434445467 unmodified lines54555657585960616263641 unmodified line6667686970717236 unmodified lines10911011111211311411511619 unmodified lines1361371381391401411421431444 unmodified lines1491501511521531541558 unmodified lines1641651661671681691701 unmodified line1721731741751761771781791801812 unmodified lines1841851861871881891901911921931 unmodified line1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252263 unmodified lines23023123223323423523611 unmodified lines248249250251252253254556 unmodified lines81181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789810 unmodified lines9099109119129139149159169179189199209219229239 unmodified lines93393493593693793893917 unmodified lines957958959960961962963339 unmodified lines130313041305130613071308130912 unmodified lines13221323132413251326132713283 unmodified lines13321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951 unmodified line13971398139914001401140214036 unmodified lines141014111412141314141415141642 unmodified lines1459146014611462146314641465146637 unmodified lines150415051506150715081509151015111512151315141515151615171518151917 unmodified lines15371538153915401541154248 unmodified lines159115921593159415951596159715981599160016011602160322 unmodified lines'createdAt': '2023-01-01T00:00:00.000Z','hardware': 'cpu','user': {'avatar_url': 'https://huggingface.co/front/thumbnails/huggingface/default-avatar.svg','name': 'dummyUser'}})2 unmodified lines# Function to fetch Zero-GPU (CPU-based) Spaces from Huggingface with paginationdef fetch_trending_spaces(offset=0, limit=72):"""원본 코드에서 수정: hardware=cpu 파라미터를 추가하여GPU가 없는(=CPU 전용) 스페이스만 필터링"""try:url = "https://huggingface.co/api/spaces"params = {"limit": 10000, # 더 많이 가져오기"hardware": "cpu" # <-- Zero GPU(=CPU) 필터 적용# "sort": "trending", # 필요시 추가 (HF API 지원 여부에 따라)}response = requests.get(url, params=params, timeout=30)7 unmodified linesand space.get('id', '').split('/', 1)[0] != 'None']# Slice according to requested offset and limitstart = min(offset, len(filtered_spaces))end = min(offset + limit, len(filtered_spaces))print(f"[fetch_trending_spaces] CPU기반 스페이스 총 {len(filtered_spaces)}개, "f"요청 구간 {start}~{end-1} 반환")return {1 unmodified line'total': len(filtered_spaces),'offset': offset,'limit': limit,'all_spaces': filtered_spaces # 통계 산출용}else:print(f"Error fetching spaces: {response.status_code}")36 unmodified lines# Get space detailsdef get_space_details(space_data, index, offset):"""원본 코드에서 수정:- description, avatar_url, author_name 등 추가 필드를 추출"""try:if '/' in space_data.get('id', ''):19 unmodified lines# Descriptionshort_desc = space_data.get('description', '')# User info (avatar, name)user_info = space_data.get('user', {})avatar_url = user_info.get('avatar_url', '')author_name = user_info.get('name') or ownerreturn {4 unmodified lines'name': name,'likes_count': likes_count,'description': short_desc,'avatar_url': avatar_url,'author_name': author_name,'rank': offset + index + 1}8 unmodified lines'name': 'error','likes_count': 0,'description': '','avatar_url': '','author_name': 'huggingface','rank': offset + index + 1}1 unmodified line# Get owner statistics from all spacesdef get_owner_stats(all_spaces):"""모든 스페이스에서 owner 등장 빈도 상위 30명 추출"""owners = []for space in all_spaces:if '/' in space.get('id', ''):owner, _ = space.get('id', '').split('/', 1)else:2 unmodified linesif owner != 'None':owners.append(owner)# Count occurrences of each ownerowner_counts = Counter(owners)# Get top 30 owners by counttop_owners = owner_counts.most_common(30)return top_owners1 unmodified line# Homepage route@app.route('/')def home():"""index.html 템플릿 렌더링 (���인 페이지)"""return render_template('index.html')# Zero-GPU spaces API (원본: 'trending-spaces' -> 이제 CPU only)@app.route('/api/trending-spaces', methods=['GET'])def trending_spaces():"""hardware=cpu 스페이스 목록을 불러와 검색, 페이징, 통계 등을 적용"""search_query = request.args.get('search', '').lower()offset = int(request.args.get('offset', 0))limit = int(request.args.get('limit', 72)) # Default 72# Fetch zero-gpu (cpu) spacesspaces_data = fetch_trending_spaces(offset, limit)# Process and filter spacesresults = []for index, space_data in enumerate(spaces_data['spaces']):space_info = get_space_details(space_data, index, offset)if not space_info:continue# Apply search filter if neededif search_query:if (search_query not in space_info['title'].lower()and search_query not in space_info['owner'].lower()3 unmodified linesresults.append(space_info)# Get owner statistics for all spacestop_owners = get_owner_stats(spaces_data.get('all_spaces', []))return jsonify({11 unmodified lines# Create templates folder if not existsos.makedirs('templates', exist_ok=True)# index.html 전체를 새로 작성with open('templates/index.html', 'w', encoding='utf-8') as f:f.write('''<!DOCTYPE html><html lang="en">556 unmodified lines}}.error-emoji-detector {position: fixed;top: -9999px;left: -9999px;z-index: -1;opacity: 0;}/* 추가 레이아웃 수정(아바타, ZERO GPU 뱃지 등)을 위해아래 클래스들을 일부 추가/수정해도 좋지만예시는 위 영역에서 이미 충분히 처리하므로 생략 *//* 다음 부분은 Zero GPU Spaces용 카드 구조에서 활용 */.space-header {display: flex;align-items: center;gap: 10px;margin-bottom: 4px;}.avatar-img {width: 32px;height: 32px;border-radius: 50%;object-fit: cover;border: 1px solid #ccc;}.space-title {font-size: 1rem;font-weight: 600;margin: 0;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;max-width: 200px;}.zero-gpu-badge {font-size: 0.7rem;background-color: #e6fffa;color: #319795;border: 1px solid #81e6d9;border-radius: 6px;padding: 2px 6px;font-weight: 600;margin-left: 8px;}.desc-text {font-size: 0.85rem;color: #444;margin: 4px 0;line-clamp: 2;display: -webkit-box;-webkit-box-orient: vertical;overflow: hidden;}.author-name {font-size: 0.8rem;color: #666;}.likes-wrapper {display: flex;align-items: center;gap: 4px;color: #e53e3e;font-weight: bold;font-size: 0.85rem;}.likes-heart {font-size: 1rem;line-height: 1rem;color: #f56565;}/* 이모지 전용 스타일 (선택사항) */.emoji-avatar {font-size: 1.2rem;width: 32px;height: 32px;border-radius: 50%;border: 1px solid #ccc;display: flex;align-items: center;justify-content: center;}</style></head><body>10 unmodified lines<div class="mac-content"><div class="header"><!-- 첫 번째 탭 제목을 Zero GPU Spaces로 변경 --><h1>Zero GPU Spaces</h1><p>Discover 'TOP 1,000' Zero GPU(Shared A100) spaces from Hugging Face</p></div><!-- Tab Navigation --><div class="tab-nav"><button id="tabTrendingButton" class="tab-button active">Zero GPU Spaces</button><button id="tabFixedButton" class="tab-button">Fixed Tab</button></div><!-- Trending(Zero GPU) Tab Content -->9 unmodified lines</div><div class="mac-content"><div class="stats-header"><div class="stats-title">Top 30 Creators by Count Number of TOP 1000 RANK</div><button id="statsToggle" class="stats-toggle">Show Stats</button></div><div id="statsContent" class="stats-content">17 unmodified lines<div id="pagination" class="pagination"></div></div><!-- Fixed Tab Content (기존 예시 유지) --><div id="fixedTab" class="tab-content"><div id="fixedGrid" class="grid-container"></div></div>339 unmodified linescontainer.appendChild(errorPlaceholder);}// 여기서부터 카드 HTML 구조 (Zero-GPU 전용) 렌더링function renderGrid(spaces) {elements.gridContainer.innerHTML = '';12 unmodified linestry {const {url, title, likes_count, owner, name, rank,description, avatar_url, author_name, embedUrl} = item;const gridItem = document.createElement('div');3 unmodified linesconst headerDiv = document.createElement('div');headerDiv.className = 'grid-header';// space-header (로봇 이모지 + 제목 + Zero GPU 배지)const spaceHeader = document.createElement('div');spaceHeader.className = 'space-header';// 로봇 이모지 대체const emojiAvatar = document.createElement('div');emojiAvatar.className = 'emoji-avatar';emojiAvatar.textContent = '🤖';spaceHeader.appendChild(emojiAvatar);// 제목+배지const titleWrapper = document.createElement('div');titleWrapper.style.display = 'flex';titleWrapper.style.alignItems = 'center';const titleEl = document.createElement('h3');titleEl.className = 'space-title';titleEl.textContent = title;titleEl.title = title;titleWrapper.appendChild(titleEl);const zeroGpuBadge = document.createElement('span');zeroGpuBadge.className = 'zero-gpu-badge';zeroGpuBadge.textContent = 'ZERO GPU';titleWrapper.appendChild(zeroGpuBadge);spaceHeader.appendChild(titleWrapper);headerDiv.appendChild(spaceHeader);// rank + author + likesconst metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';metaInfo.style.display = 'flex';metaInfo.style.justifyContent = 'space-between';metaInfo.style.alignItems = 'center';metaInfo.style.marginTop = '6px';// 왼쪽: rank + authorconst leftMeta = document.createElement('div');const rankBadge = document.createElement('div');rankBadge.className = 'rank-badge';rankBadge.textContent = `#${rank}`;leftMeta.appendChild(rankBadge);const authorSpan = document.createElement('span');authorSpan.className = 'author-name';authorSpan.style.marginLeft = '8px';authorSpan.textContent = `by ${author_name}`;leftMeta.appendChild(authorSpan);metaInfo.appendChild(leftMeta);// 오른쪽: likesconst likesDiv = document.createElement('div');likesDiv.className = 'likes-wrapper';likesDiv.innerHTML = `<span class="likes-heart">♥</span><span>${likes_count}</span>`;metaInfo.appendChild(likesDiv);headerDiv.appendChild(metaInfo);gridItem.appendChild(headerDiv);1 unmodified line// descriptionif (description) {const descP = document.createElement('p');descP.className = 'desc-text';descP.textContent = description;gridItem.appendChild(descP);}6 unmodified linesiframeContainer.className = 'iframe-container';const iframe = document.createElement('iframe');iframe.src = embedUrl; // transformed direct URLiframe.title = title;iframe.allow = 'accelerometer; camera; encrypted-media; geolocation; gyroscope;';iframe.setAttribute('allowfullscreen', '');42 unmodified lines});}function renderFixedGrid() {// Fixed Tab 예시용 (원본 코드 예시 유지)fixedGridContainer.innerHTML = '';const staticSpaces = [37 unmodified linesstaticSpaces.forEach((item) => {try {const { url, title, likes_count, owner, name, rank } = item;const gridItem = document.createElement('div');gridItem.className = 'grid-item';const header = document.createElement('div');header.className = 'grid-header';const headerTop = document.createElement('div');headerTop.className = 'grid-header-top';// 로봇 이모지 + 타이틀 함께 표시const leftWrapper = document.createElement('div');leftWrapper.style.display = 'flex';leftWrapper.style.alignItems = 'center';17 unmodified linesheader.appendChild(headerTop);const metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';48 unmodified lineslinkEl.target = '_blank';linkEl.className = 'open-link';linkEl.textContent = 'Open in new window';actions.appendChild(linkEl);gridItem.appendChild(content);gridItem.appendChild(actions);fixedGridContainer.appendChild(gridItem);} catch (error) {console.error('Fixed tab rendering error:', error);}
app.py+162-80