Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112133 unmodified lines17181920212223244 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451468 unmodified lines1551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602 unmodified lines2632642652662672682692702711 unmodified line2732742752762772782792802812822832842852862872882892902912922932942952962973 unmodified lines3013023033043053063073083093103113123133 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029038 unmodified lines91291391491591691791891992092192292392492592692792892993093193216 unmodified lines9499509519529539549551 unmodified line9579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879885 unmodified lines99499599699799899910004 unmodified lines10051006100710081009101010113 unmodified lines10151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210633 unmodified lines1067106810691070107110721073107410751076107710781079108010811082108310844 unmodified lines1089109010911092109310941095109610971098109911 unmodified lines1111111211131114111511161117111811191120112111221 unmodified line11241125112611271128112911301131113211331134113511361137113811391140114111421143114411455 unmodified lines115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851 unmodified line11871188118911901191119211931194119511961197119811991200120112027 unmodified lines1210121112121213121412151216121714 unmodified lines1232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612975 unmodified lines13031304130513061307130813091310131113121313131413151316131713183 unmodified lines132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213539 unmodified lines136313641365136613671368136913701371137213731 unmodified line1375137613771378137913801381138213831384138513861387138813891390139113922 unmodified lines1395139613971398139914001401140214031404140514061407140814091 unmodified line141114121413141414151416141714181419142014217 unmodified lines14291430143114321433143414352 unmodified lines14381439144014411442144314446 unmodified lines145114521453145414551456145714581459146014611462146314641465146614671468146914701471147210 unmodified lines1483148414851486148714881489149014911492149314941495149614971498149915003 unmodified lines150415051506150715081509151015111 unmodified line1513151415151516151715181519152015211522152315241525152615273 unmodified lines15311532153315341535153615372 unmodified lines154015411542154315441545154612 unmodified lines15591560156115621563156415651 unmodified line156715681569157015711572157315744 unmodified lines15791580158115821583158415853 unmodified lines15891590159115921593159415953 unmodified lines15991600160116021603160416051606160716081609161016111612161316148 unmodified lines16231624162516261627162816291630163116321633163416353 unmodified lines163916401641164216431644164515 unmodified lines166116621663166416651666166711 unmodified lines1679168016811682168316841685from flask import Flask, render_template, request, jsonifyimport requestsimport osimport timeimport randomfrom collections import Counterapp = Flask(__name__)# Generate dummy spaces in case of errordef generate_dummy_spaces(count):"""API 호출 실패 시 예시용 더미 스페이스 생성3 unmodified linesspaces.append({'id': f'dummy/space-{i}','owner': 'dummy','title': f'Example Space {i+1}','description': 'Dummy space for fallback','likes': 100 - i,'createdAt': '2023-01-01T00:00:00.000Z','hardware': 'cpu',4 unmodified lines})return spaces# Function to fetch Zero-GPU (CPU-based) Spaces from Huggingface with paginationdef fetch_trending_spaces(offset=0, limit=24):"""hardware=cpu 파라미터를 추가하여GPU가 없는(=CPU 전용) 스페이스만 필터링"""try:url = "https://huggingface.co/api/spaces"params = {"limit": 1000, # 더 많이 가져오기"hardware": "cpu" # <-- Zero GPU(=CPU) 필터 적용}response = requests.get(url, params=params, timeout=30)if response.status_code == 200:spaces = response.json()# owner나 id가 'None'인 경우 제외filtered_spaces = [space for space in spacesif space.get('owner') != 'None'and space.get('id', '').split('/', 1)[0] != 'None']# 전체 목록에 대해 "글로벌 랭크"를 매긴다 (1부터 시작)for i, sp in enumerate(filtered_spaces):sp['global_rank'] = i + 1# 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 {'spaces': filtered_spaces[start:end],'total': len(filtered_spaces),'offset': offset,'limit': limit,'all_spaces': filtered_spaces # 통계 산출용}else:print(f"Error fetching spaces: {response.status_code}")# 실패 시 더미 데이터 생성return {'spaces': generate_dummy_spaces(limit),'total': 200,'offset': offset,'limit': limit,'all_spaces': generate_dummy_spaces(500)}except Exception as e:print(f"Exception when fetching spaces: {e}")# 실패 시 더미 데이터 생성return {'spaces': generate_dummy_spaces(limit),'total': 200,'offset': offset,'limit': limit,'all_spaces': generate_dummy_spaces(500)}# Transform Huggingface URL to direct space URLdef transform_url(owner, name):"""Hugging Face Space -> 서브도메인 접근 URL예) huggingface.co/spaces/owner/spaceName -> owner-spacename.hf.space"""# 1. Replace '.' with '-'name = name.replace('.', '-')# 2. Replace '_' with '-'name = name.replace('_', '-')# 3. Convert to lowercaseowner = owner.lower()name = name.lower()return f"https://{owner}-{name}.hf.space"# Get space detailsdef get_space_details(space_data, index, offset):"""- description, avatar_url, author_name 등 추가 필드를 추출- rank는 현재 페이지 내 offset 기반으로 계산(단, Top 500 계산은 global_rank 사용)"""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', '')# Ignore if contains Noneif owner == 'None' or name == 'None':return None# Construct URLsoriginal_url = f"https://huggingface.co/spaces/{owner}/{name}"embed_url = transform_url(owner, name)# Likes countlikes_count = space_data.get('likes', 0)# Titletitle = space_data.get('title') or name# 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 owner8 unmodified lines'description': short_desc,'avatar_url': avatar_url,'author_name': author_name,'rank': offset + index + 1 # 현재 페이지에서의 표시용 랭크}except Exception as e:print(f"Error processing space data: {e}")# Return basic object even if error occursreturn {'url': 'https://huggingface.co/spaces','embedUrl': 'https://huggingface.co/spaces','title': 'Error Loading Space','owner': 'huggingface','name': 'error','likes_count': 0,'description': '','avatar_url': '','author_name': 'huggingface','rank': offset + index + 1}# Get owner statistics from all spacesdef get_owner_stats(all_spaces):"""상위 500위(global_rank <= 500) 이내에 배치된 스페이스들의 owner를 추출해,각 owner가 몇 번 등장했는지 센 뒤 상위 30명만 반환"""# Top 500top_500 = [s for s in all_spaces if s.get('global_rank', 999999) <= 500]owners = []for space in top_500:if '/' in space.get('id', ''):owner, _ = space.get('id', '').split('/', 1)else:owner = space.get('owner', '')if owner and owner != 'None':owners.append(owner)# Count occurrences of each owner in top 500owner_counts = Counter(owners)# Get top 30 owners by counttop_owners = owner_counts.most_common(30)return top_owners# Homepage route@app.route('/')def home():"""index.html 템플릿 렌더링 (메인 페이지)"""return render_template('index.html')# Zero-GPU spaces API@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', 24)) # Default changed to 24# 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()and search_query not in space_info['url'].lower()and search_query not in space_info['description'].lower()):continueresults.append(space_info)# Get owner statistics (Top 500 → Top 30)top_owners = get_owner_stats(spaces_data.get('all_spaces', []))return jsonify({'spaces': results,'total': spaces_data['total'],'offset': offset,'limit': limit,'top_owners': top_owners})if __name__ == '__main__':"""서버 구동 시, templates/index.html 파일을 생성 후 Flask 실행"""# 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">2 unmodified lines<title>Huggingface Zero-GPU Spaces</title><script src="https://cdn.jsdelivr.net/npm/chart.js"></script><style>/* Google Fonts & Base Styling */@import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;500;600;700&display=swap');:root {--pastel-pink: #FFD6E0;--pastel-blue: #C5E8FF;1 unmodified line--pastel-yellow: #FFF2CC;--pastel-green: #C7F5D9;--pastel-orange: #FFE0C3;--mac-window-bg: rgba(250, 250, 250, 0.85);--mac-toolbar: #F5F5F7;--mac-border: #E2E2E2;--mac-button-red: #FF5F56;--mac-button-yellow: #FFBD2E;--mac-button-green: #27C93F;--text-primary: #333;--text-secondary: #666;--box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);}* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;line-height: 1.6;3 unmodified linesmin-height: 100vh;padding: 2rem;}.container {max-width: 1600px;margin: 0 auto;}/* Mac OS Window Styling */.mac-window {background-color: var(--mac-window-bg);border-radius: 10px;3 unmodified linesmargin-bottom: 2rem;border: 1px solid var(--mac-border);}.mac-toolbar {display: flex;align-items: center;padding: 10px 15px;background-color: var(--mac-toolbar);border-bottom: 1px solid var(--mac-border);}.mac-buttons {display: flex;gap: 8px;margin-right: 15px;}.mac-button {width: 12px;height: 12px;border-radius: 50%;cursor: default;}.mac-close {background-color: var(--mac-button-red);}.mac-minimize {background-color: var(--mac-button-yellow);}.mac-maximize {background-color: var(--mac-button-green);}.mac-title {flex-grow: 1;text-align: center;font-size: 0.9rem;color: var(--text-secondary);}.mac-content {padding: 20px;}/* Header Styling */.header {text-align: center;margin-bottom: 1.5rem;position: relative;}.header h1 {font-size: 2.2rem;font-weight: 700;margin: 0;color: #2d3748;letter-spacing: -0.5px;}.header p {color: var(--text-secondary);margin-top: 0.5rem;font-size: 1.1rem;}/* Tabs Styling */.tab-nav {display: flex;justify-content: center;margin-bottom: 1.5rem;}.tab-button {border: none;background-color: #edf2f7;color: var(--text-primary);padding: 10px 20px;margin: 0 5px;cursor: pointer;border-radius: 5px;font-size: 1rem;font-weight: 600;}.tab-button.active {background-color: var(--pastel-purple);color: #fff;}.tab-content {display: none;}.tab-content.active {display: block;}/* Controls Styling */.search-bar {display: flex;align-items: center;margin-bottom: 1.5rem;background-color: white;border-radius: 30px;padding: 5px;box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);max-width: 600px;margin-left: auto;margin-right: auto;}.search-bar input {flex-grow: 1;border: none;padding: 12px 20px;font-size: 1rem;outline: none;background: transparent;border-radius: 30px;}.search-bar .refresh-btn {background-color: var(--pastel-green);color: #1a202c;border: none;border-radius: 30px;padding: 10px 20px;font-size: 1rem;font-weight: 600;cursor: pointer;transition: all 0.2s;display: flex;align-items: center;gap: 8px;}.search-bar .refresh-btn:hover {background-color: #9ee7c0;box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);}.refresh-icon {display: inline-block;width: 16px;height: 16px;border: 2px solid #1a202c;border-top-color: transparent;border-radius: 50%;animation: none;}.refreshing .refresh-icon {animation: spin 1s linear infinite;}@keyframes spin {0% { transform: rotate(0deg); }100% { transform: rotate(360deg); }}/* Grid Styling */.grid-container {display: grid;grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));gap: 1.5rem;margin-bottom: 2rem;}.grid-item {height: 500px;position: relative;overflow: hidden;transition: all 0.3s ease;border-radius: 15px;}.grid-item:nth-child(6n+1) { background-color: var(--pastel-pink); }.grid-item:nth-child(6n+2) { background-color: var(--pastel-blue); }.grid-item:nth-child(6n+3) { background-color: var(--pastel-purple); }.grid-item:nth-child(6n+4) { background-color: var(--pastel-yellow); }.grid-item:nth-child(6n+5) { background-color: var(--pastel-green); }.grid-item:nth-child(6n+6) { background-color: var(--pastel-orange); }.grid-item:hover {transform: translateY(-5px);box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);}.grid-header {padding: 15px;display: flex;flex-direction: column;background-color: rgba(255, 255, 255, 0.7);backdrop-filter: blur(5px);border-bottom: 1px solid rgba(0, 0, 0, 0.05);}.grid-header-top {display: flex;justify-content: space-between;align-items: center;margin-bottom: 8px;}.rank-badge {background-color: #1a202c;color: white;font-size: 0.8rem;font-weight: 600;padding: 4px 8px;border-radius: 50px;display: inline-block;}.grid-header h3 {margin: 0;font-size: 1.2rem;font-weight: 700;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}.grid-meta {display: flex;justify-content: space-between;align-items: center;font-size: 0.9rem;}.owner-info {color: var(--text-secondary);font-weight: 500;}.likes-counter {display: flex;align-items: center;color: #e53e3e;font-weight: 600;}.likes-counter span {margin-left: 4px;}.grid-actions {padding: 10px 15px;text-align: right;background-color: rgba(255, 255, 255, 0.7);backdrop-filter: blur(5px);position: absolute;bottom: 0;left: 0;right: 0;z-index: 10;display: flex;justify-content: flex-end;}.open-link {text-decoration: none;color: #2c5282;font-weight: 600;padding: 5px 10px;border-radius: 5px;transition: all 0.2s;background-color: rgba(237, 242, 247, 0.8);}.open-link:hover {background-color: #e2e8f0;}.grid-content {position: absolute;top: 0;left: 0;width: 100%;height: 100%;padding-top: 85px; /* Header height */padding-bottom: 45px; /* Actions height */}.iframe-container {width: 100%;height: 100%;overflow: hidden;position: relative;}/* Apply 70% scaling to iframes */.grid-content iframe {transform: scale(0.7);transform-origin: top left;width: 142.857%;height: 142.857%;border: none;border-radius: 0;}.error-placeholder {position: absolute;top: 0;left: 0;width: 100%;height: 100%;display: flex;flex-direction: column;justify-content: center;align-items: center;padding: 20px;background-color: rgba(255, 255, 255, 0.9);text-align: center;}.error-emoji {font-size: 6rem;margin-bottom: 1.5rem;animation: bounce 1s infinite alternate;text-shadow: 0 10px 20px rgba(0,0,0,0.1);}@keyframes bounce {from {transform: translateY(0px) scale(1);}to {transform: translateY(-15px) scale(1.1);}}/* Pagination Styling */.pagination {display: flex;justify-content: center;align-items: center;gap: 10px;margin: 2rem 0;}.pagination-button {background-color: white;border: none;padding: 10px 20px;border-radius: 10px;font-size: 1rem;font-weight: 600;cursor: pointer;transition: all 0.2s;color: var(--text-primary);box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);}.pagination-button:hover {background-color: #f8f9fa;box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);}.pagination-button.active {background-color: var(--pastel-purple);color: #4a5568;}.pagination-button:disabled {background-color: #edf2f7;color: #a0aec0;cursor: default;box-shadow: none;}/* Loading Indicator */.loading {position: fixed;top: 0;left: 0;right: 0;bottom: 0;background-color: rgba(255, 255, 255, 0.8);backdrop-filter: blur(5px);display: flex;justify-content: center;align-items: center;z-index: 1000;}.loading-content {text-align: center;}.loading-spinner {width: 60px;height: 60px;border: 5px solid #e2e8f0;border-top-color: var(--pastel-purple);border-radius: 50%;animation: spin 1s linear infinite;margin: 0 auto 15px;}.loading-text {font-size: 1.2rem;font-weight: 600;color: #4a5568;}.loading-error {display: none;margin-top: 10px;color: #e53e3e;font-size: 0.9rem;}/* Stats window styling */.stats-window {margin-top: 2rem;margin-bottom: 2rem;}.stats-header {display: flex;justify-content: space-between;align-items: center;margin-bottom: 1rem;}.stats-title {font-size: 1.5rem;font-weight: 700;color: #2d3748;}.stats-toggle {background-color: var(--pastel-blue);border: none;padding: 8px 16px;border-radius: 20px;font-weight: 600;cursor: pointer;transition: all 0.2s;}.stats-toggle:hover {background-color: var(--pastel-purple);}.stats-content {background-color: white;border-radius: 10px;padding: 20px;box-shadow: var(--box-shadow);max-height: 0;overflow: hidden;transition: max-height 0.5s ease-out;}.stats-content.open {max-height: 600px;}.chart-container {width: 100%;height: 500px;}/* Responsive Design */@media (max-width: 768px) {body {padding: 1rem;}.grid-container {grid-template-columns: 1fr;}.search-bar {flex-direction: column;padding: 10px;}.search-bar input {width: 100%;margin-bottom: 10px;}.search-bar .refresh-btn {width: 100%;justify-content: center;}.pagination {flex-wrap: wrap;}.chart-container {height: 300px;}}.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>8 unmodified lines</div><div class="mac-title">Huggingface Explorer</div></div><div class="mac-content"><div class="header"><!-- 첫 번째 탭 제목을 Zero GPU Spaces로 변경 --><h1>ZeroGPU Spaces Leaderboard</h1><p>Discover Zero GPU(Shared A100) 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 --><div id="trendingTab" class="tab-content active"><div class="stats-window mac-window"><div class="mac-toolbar">16 unmodified lines</div></div></div><div class="search-bar"><input type="text" id="searchInput" placeholder="Search by name, owner, or description..." /><button id="refreshButton" class="refresh-btn">1 unmodified lineRefresh</button></div><div id="gridContainer" class="grid-container"></div><div id="pagination" class="pagination"></div></div><!-- Fixed Tab Content (기존 예시 유지) --><div id="fixedTab" class="tab-content"><div id="fixedGrid" class="grid-container"></div></div></div></div></div><div id="loadingIndicator" class="loading"><div class="loading-content"><div class="loading-spinner"></div><div class="loading-text">Loading Zero-GPU spaces...</div><div id="loadingError" class="loading-error">If this takes too long, try refreshing the page.</div></div></div><script>// DOM Elementsconst elements = {gridContainer: document.getElementById('gridContainer'),loadingIndicator: document.getElementById('loadingIndicator'),5 unmodified linesstatsContent: document.getElementById('statsContent'),creatorStatsChart: document.getElementById('creatorStatsChart')};const tabTrendingButton = document.getElementById('tabTrendingButton');const tabFixedButton = document.getElementById('tabFixedButton');const trendingTab = document.getElementById('trendingTab');4 unmodified linesisLoading: false,spaces: [],currentPage: 0,itemsPerPage: 24, // Changed from 72 to 24totalItems: 0,loadingTimeout: null,staticModeAttempted: {},3 unmodified linesiframeStatuses: {}};// Advanced iframe loader for better error detectionconst iframeLoader = {checkQueue: {},maxAttempts: 5,checkInterval: 5000,startChecking: function(iframe, owner, name, title, spaceKey) {this.checkQueue[spaceKey] = {iframe: iframe,owner: owner,name: name,title: title,attempts: 0,status: 'loading'};this.checkIframeStatus(spaceKey);},checkIframeStatus: function(spaceKey) {if (!this.checkQueue[spaceKey]) return;const item = this.checkQueue[spaceKey];if (item.status !== 'loading') {delete this.checkQueue[spaceKey];return;}item.attempts++;try {if (!item.iframe || !item.iframe.parentNode) {delete this.checkQueue[spaceKey];return;}// Check if content loadedtry {const hasContent = item.iframe.contentWindow &&item.iframe.contentWindow.document &&item.iframe.contentWindow.document.body;if (hasContent && item.iframe.contentWindow.document.body.innerHTML.length > 100) {const bodyText = item.iframe.contentWindow.document.body.textContent.toLowerCase();if (bodyText.includes('forbidden') || bodyText.includes('404') ||bodyText.includes('not found') || bodyText.includes('error')) {item.status = 'error';handleIframeError(item.iframe, item.owner, item.name, item.title);} else {3 unmodified linesreturn;}} catch(e) {// Cross-origin issues can happen; not always an error}// Check if iframe is visibleconst rect = item.iframe.getBoundingClientRect();if (rect.width > 50 && rect.height > 50 && item.attempts > 2) {item.status = 'success';delete this.checkQueue[spaceKey];return;}// If max attempts reachedif (item.attempts >= this.maxAttempts) {if (item.iframe.offsetWidth > 0 && item.iframe.offsetHeight > 0) {item.status = 'success';4 unmodified linesdelete this.checkQueue[spaceKey];return;}// Re-check after some delayconst nextDelay = this.checkInterval * Math.pow(1.5, item.attempts - 1);setTimeout(() => this.checkIframeStatus(spaceKey), nextDelay);} catch (e) {console.error('Error checking iframe status:', e);if (item.attempts >= this.maxAttempts) {11 unmodified linesstate.statsVisible = !state.statsVisible;elements.statsContent.classList.toggle('open', state.statsVisible);elements.statsToggle.textContent = state.statsVisible ? 'Hide Stats' : 'Show Stats';if (state.statsVisible && state.topOwners.length > 0) {renderCreatorStats();}}function renderCreatorStats() {if (state.chartInstance) {state.chartInstance.destroy();1 unmodified lineconst ctx = elements.creatorStatsChart.getContext('2d');const labels = state.topOwners.map(item => item[0]);const data = state.topOwners.map(item => item[1]);const colors = [];for (let i = 0; i < labels.length; i++) {const hue = (i * 360 / labels.length) % 360;colors.push(`hsla(${hue}, 70%, 80%, 0.7)`);}state.chartInstance = new Chart(ctx, {type: 'bar',data: {labels: labels,datasets: [{label: 'Number of Spaces in Top 500',data: data,backgroundColor: colors,borderColor: colors.map(color => color.replace('0.7', '1')),borderWidth: 1}]},5 unmodified lineslegend: { display: false },tooltip: {callbacks: {title: function(tooltipItems) {return tooltipItems[0].label;},label: function(context) {return `Spaces: ${context.raw}`;}}}},scales: {x: {beginAtZero: true,title: {display: true,text: 'Number of Spaces'}},y: {title: {display: true,text: 'Creator ID'},ticks: {autoSkip: false,font: function(context) {const defaultSize = 11;return {size: labels.length > 20 ? defaultSize - 1 : defaultSize};}}}1 unmodified line}});}async function loadSpaces(page = 0) {setLoading(true);try {const searchText = elements.searchInput.value;const offset = page * state.itemsPerPage;const timeoutPromise = new Promise((_, reject) =>setTimeout(() => reject(new Error('Request timeout')), 30000));const fetchPromise = fetch(`/api/trending-spaces?search=${encodeURIComponent(searchText)}&offset=${offset}&limit=${state.itemsPerPage}`);7 unmodified linesrenderGrid(state.spaces);renderPagination();if (state.statsVisible && state.topOwners.length > 0) {renderCreatorStats();}} catch (error) {14 unmodified linessetLoading(false);}}function renderPagination() {elements.pagination.innerHTML = '';const totalPages = Math.ceil(state.totalItems / state.itemsPerPage);// Previous pageconst prevButton = document.createElement('button');prevButton.className = 'pagination-button';prevButton.textContent = 'Previous';prevButton.disabled = (state.currentPage === 0);prevButton.addEventListener('click', () => {if (state.currentPage > 0) {loadSpaces(state.currentPage - 1);}});elements.pagination.appendChild(prevButton);const maxButtons = 7;let startPage = Math.max(0, state.currentPage - Math.floor(maxButtons / 2));let endPage = Math.min(totalPages - 1, startPage + maxButtons - 1);if (endPage - startPage + 1 < maxButtons) {startPage = Math.max(0, endPage - maxButtons + 1);}for (let i = startPage; i <= endPage; i++) {const pageButton = document.createElement('button');pageButton.className = 'pagination-button' + (i === state.currentPage ? ' active' : '');pageButton.textContent = (i + 1);pageButton.addEventListener('click', () => {if (i !== state.currentPage) {loadSpaces(i);}});elements.pagination.appendChild(pageButton);}// Next pageconst nextButton = document.createElement('button');nextButton.className = 'pagination-button';nextButton.textContent = 'Next';nextButton.disabled = (state.currentPage >= totalPages - 1);nextButton.addEventListener('click', () => {if (state.currentPage < totalPages - 1) {loadSpaces(state.currentPage + 1);}});elements.pagination.appendChild(nextButton);}function handleIframeError(iframe, owner, name, title) {const container = iframe.parentNode;const errorPlaceholder = document.createElement('div');errorPlaceholder.className = 'error-placeholder';const errorMessage = document.createElement('p');errorMessage.textContent = `"${title}" space couldn't be loaded`;errorPlaceholder.appendChild(errorMessage);const directLink = document.createElement('a');directLink.href = `https://huggingface.co/spaces/${owner}/${name}`;directLink.target = '_blank';5 unmodified linesdirectLink.style.background = '#ebf8ff';directLink.style.borderRadius = '5px';directLink.style.fontWeight = '600';errorPlaceholder.appendChild(directLink);iframe.style.display = 'none';container.appendChild(errorPlaceholder);}function renderGrid(spaces) {elements.gridContainer.innerHTML = '';if (!spaces || spaces.length === 0) {const noResultsMsg = document.createElement('p');noResultsMsg.textContent = 'No zero-gpu spaces found matching your search.';noResultsMsg.style.padding = '2rem';3 unmodified lineselements.gridContainer.appendChild(noResultsMsg);return;}spaces.forEach((item) => {try {const {url, title, likes_count, owner, name, rank,description, avatar_url, author_name, embedUrl} = item;const gridItem = document.createElement('div');gridItem.className = 'grid-item';// 상단 헤더const headerDiv = document.createElement('div');headerDiv.className = 'grid-header';// space-header (순위 + 제목 + Zero GPU 배지)const spaceHeader = document.createElement('div');spaceHeader.className = 'space-header';// 1) 상단 순위 뱃지const rankBadge = document.createElement('div');rankBadge.className = 'rank-badge';rankBadge.textContent = `#${rank}`;spaceHeader.appendChild(rankBadge);// 제목+배지const titleWrapper = document.createElement('div');titleWrapper.style.display = 'flex';titleWrapper.style.alignItems = 'center';9 unmodified lineszeroGpuBadge.className = 'zero-gpu-badge';zeroGpuBadge.textContent = 'ZERO GPU';titleWrapper.appendChild(zeroGpuBadge);spaceHeader.appendChild(titleWrapper);headerDiv.appendChild(spaceHeader);// 하단 메타 정보const metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';metaInfo.style.display = 'flex';1 unmodified linemetaInfo.style.alignItems = 'center';metaInfo.style.marginTop = '6px';// 왼쪽: (중복 rank 제거)const leftMeta = document.createElement('div');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>`;2 unmodified linesheaderDiv.appendChild(metaInfo);gridItem.appendChild(headerDiv);// descriptionif (description) {const descP = document.createElement('p');descP.className = 'desc-text';descP.textContent = description;gridItem.appendChild(descP);}// iframe containerconst content = document.createElement('div');content.className = 'grid-content';1 unmodified lineiframeContainer.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', '');iframe.setAttribute('frameborder', '0');iframe.loading = 'lazy';const spaceKey = `${owner}/${name}`;7 unmodified linesstate.iframeStatuses[spaceKey] = 'error';};setTimeout(() => {if (state.iframeStatuses[spaceKey] === 'loading') {handleIframeError(iframe, owner, name, title);state.iframeStatuses[spaceKey] = 'error';}2 unmodified linesiframeContainer.appendChild(iframe);content.appendChild(iframeContainer);// actionsconst actions = document.createElement('div');actions.className = 'grid-actions';6 unmodified linesactions.appendChild(linkEl);gridItem.appendChild(content);gridItem.appendChild(actions);elements.gridContainer.appendChild(gridItem);} catch (err) {console.error('Item rendering error:', err);}});}############# Picks URL 입력function renderFixedGrid() {// Fixed Tab 예시용 (원본 코드 예시 유지)fixedGridContainer.innerHTML = '';const staticSpaces = [{url: "https://huggingface.co/spaces/VIDraft/SanaSprint",10 unmodified linesowner: "VIDraft",name: "SanaSprint",rank: 2},{url: "https://huggingface.co/spaces/VIDraft/SanaSprint",title: "SanaSprint",likes_count: 0,owner: "VIDraft",name: "SanaSprint",rank: 3}];if (!staticSpaces || staticSpaces.length === 0) {const noResultsMsg = document.createElement('p');noResultsMsg.textContent = 'No spaces to display.';noResultsMsg.style.padding = '2rem';3 unmodified linesfixedGridContainer.appendChild(noResultsMsg);return;}staticSpaces.forEach((item) => {try {const { url, title, likes_count, owner, name, rank } = item;const gridItem = document.createElement('div');1 unmodified lineconst 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';const emojiAvatar = document.createElement('div');emojiAvatar.className = 'emoji-avatar';emojiAvatar.textContent = '🤖';3 unmodified linestitleEl.textContent = title;titleEl.title = title;leftWrapper.appendChild(titleEl);headerTop.appendChild(leftWrapper);const rankBadge = document.createElement('div');2 unmodified linesheaderTop.appendChild(rankBadge);header.appendChild(headerTop);const metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';12 unmodified linesconst content = document.createElement('div');content.className = 'grid-content';const iframeContainer = document.createElement('div');iframeContainer.className = 'iframe-container';1 unmodified lineiframe.src = "https://" + owner.toLowerCase() + "-" + name.toLowerCase() + ".hf.space";iframe.title = title;iframe.allow = 'accelerometer; camera; encrypted-media; geolocation; gyroscope;';iframe.setAttribute('allowfullscreen', '');iframe.setAttribute('frameborder', '0');iframe.loading = 'lazy';const spaceKey = `${owner}/${name}`;4 unmodified lineshandleIframeError(iframe, owner, name, title);};setTimeout(() => {if (iframe.offsetWidth === 0 || iframe.offsetHeight === 0) {handleIframeError(iframe, owner, name, title);}}, 30000);3 unmodified linesconst actions = document.createElement('div');actions.className = 'grid-actions';const linkEl = document.createElement('a');linkEl.href = url;linkEl.target = '_blank';3 unmodified linesgridItem.appendChild(content);gridItem.appendChild(actions);fixedGridContainer.appendChild(gridItem);} catch (error) {console.error('Fixed tab rendering error:', error);}});}// Tab switchingtabTrendingButton.addEventListener('click', () => {tabTrendingButton.classList.add('active');tabFixedButton.classList.remove('active');8 unmodified linestrendingTab.classList.remove('active');renderFixedGrid();});elements.searchInput.addEventListener('input', () => {clearTimeout(state.searchTimeout);state.searchTimeout = setTimeout(() => loadSpaces(0), 300);});elements.searchInput.addEventListener('keyup', (event) => {if (event.key === 'Enter') {loadSpaces(0);}});3 unmodified lineswindow.addEventListener('load', function() {setTimeout(() => loadSpaces(0), 500);});setTimeout(() => {if (state.isLoading) {setLoading(false);15 unmodified linesfunction setLoading(isLoading) {state.isLoading = isLoading;elements.loadingIndicator.style.display = isLoading ? 'flex' : 'none';if (isLoading) {elements.refreshButton.classList.add('refreshing');clearTimeout(state.loadingTimeout);11 unmodified lines</html>''')# Flask 앱 실행 (포트 7860)app.run(host='0.0.0.0', port=7860)12345678910111213143 unmodified lines18192021222324254 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131148 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282 unmodified lines2312322332342352362372381 unmodified line2402412422432442452462472482492502512522532542552563 unmodified lines2602612622632642652663 unmodified lines2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335348 unmodified lines54354454554654754854955055155255355455555655716 unmodified lines5745755765775785791 unmodified line5815825835845855865875885895905915925935945955965975985996006016026036045 unmodified lines6106116126136146154 unmodified lines6206216226236246256263 unmodified lines6306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706713 unmodified lines6756766776786796806816826836846856866876884 unmodified lines69369469569669769869970011 unmodified lines7127137147157167177187197207211 unmodified line7237247257267277287297307317327337347357367377387397407417425 unmodified lines7487497507517527537547557567577587597607617627637647657667677687697701 unmodified line7727737747757767777787797807817827837847857 unmodified lines79379479579679779879914 unmodified lines8148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648655 unmodified lines8718728738748758768778788798808818828838843 unmodified lines8888898908918928938948958968978988999009019029039049059069079089 unmodified lines9189199209219229239249259261 unmodified line9289299309319329339349359369379389399409412 unmodified lines9449459469479489499509519529539549551 unmodified line9579589599609619629639649659669677 unmodified lines9759769779789799809812 unmodified lines9849859869879889896 unmodified lines99699799899910001001100210031004100510061007100810091010101110 unmodified lines1022102310241025102610271028102910303 unmodified lines10341035103610371038103910401 unmodified line1042104310441045104610471048104910501051105210533 unmodified lines1057105810591060106110622 unmodified lines10651066106710681069107012 unmodified lines1083108410851086108710881 unmodified line109010911092109310941095109610974 unmodified lines11021103110411051106110711083 unmodified lines1112111311141115111611173 unmodified lines11211122112311241125112611271128112911301131113211338 unmodified lines1142114311441145114611471148114911501151115211533 unmodified lines11571158115911601161116215 unmodified lines11781179118011811182118311 unmodified lines11951196119711981199120012011202from flask import Flask, render_template, request, jsonifyimport requestsimport osfrom collections import Counterapp = Flask(__name__)# --------------------- 전역 캐시 ---------------------SPACE_CACHE = [] # 서버 시작 시 한 번만 로딩된 스페이스 목록을 저장# --------------------- 더미 데이터 생성 함수 ---------------------def generate_dummy_spaces(count):"""API 호출 실패 시 예시용 더미 스페이스 생성3 unmodified linesspaces.append({'id': f'dummy/space-{i}','owner': 'dummy','title': f'Dummy Space {i+1}','description': 'This is a fallback dummy space.','likes': 100 - i,'createdAt': '2023-01-01T00:00:00.000Z','hardware': 'cpu',4 unmodified lines})return spaces# --------------------- 서버 시작 시 한 번만 호출하여 CACHE 채우기 ---------------------def fetch_zero_gpu_spaces_once():"""Hugging Face API에서 hardware=cpu 스페이스 목록을 가져옴 (limit을 작게 설정)"""try:url = "https://huggingface.co/api/spaces"params = {"limit": 500, # limit을 작게 하여 빠른 응답 유도"hardware": "cpu"}resp = requests.get(url, params=params, timeout=30)if resp.status_code == 200:raw_spaces = resp.json()# owner나 id가 'None'인 경우 제외filtered = [sp for sp in raw_spacesif sp.get('owner') != 'None'and sp.get('id', '').split('/', 1)[0] != 'None']# 글로벌 랭크 부여for i, sp in enumerate(filtered):sp['global_rank'] = i + 1print(f"[fetch_zero_gpu_spaces_once] 성공적으로 {len(filtered)}개 로드")return filteredelse:print(f"[fetch_zero_gpu_spaces_once] API 에러: {resp.status_code}")except Exception as e:print(f"[fetch_zero_gpu_spaces_once] 예외 발생: {e}")# 실패 시 더미 데이터 리턴print("[fetch_zero_gpu_spaces_once] 실패 → 더미 데이터 사용")return generate_dummy_spaces(100)@app.before_first_requestdef load_cache():"""Flask가 첫 요청을 받기 전(서버 시작 직후) 한 번만 실행.전역 변수 SPACE_CACHE에 CPU 전용 스페이스 정보를 로딩한다."""global SPACE_CACHESPACE_CACHE = fetch_zero_gpu_spaces_once()print(f"[load_cache] Loaded {len(SPACE_CACHE)} CPU-based Spaces into cache.")# --------------------- URL 변환 함수 ---------------------def transform_url(owner, name):"""huggingface.co/spaces/owner/spaceName -> owner-spacename.hf.space"""owner = owner.lower()# '.'나 '_' 등을 '-'로 변환name = name.replace('.', '-').replace('_', '-').lower()return f"https://{owner}-{name}.hf.space"# --------------------- space_details 생성 함수 ---------------------def get_space_details(space_data, index, offset):"""스페이스의 상세 정보를 추출하고, 페이지 offset+index에 따라 순위(rank)를 부여"""try:space_id = space_data.get('id', '')if '/' in space_id:owner, name = space_id.split('/', 1)else:owner = space_data.get('owner', '')name = space_idif owner == 'None' or name == 'None':return Noneoriginal_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') or nameshort_desc = space_data.get('description', '')user_info = space_data.get('user', {})avatar_url = user_info.get('avatar_url', '')author_name = user_info.get('name') or owner8 unmodified lines'description': short_desc,'avatar_url': avatar_url,'author_name': author_name,'rank': offset + index + 1}except Exception as e:print(f"[get_space_details] 예외 발생: {e}")return None# --------------------- owner 통계 함수 ---------------------def get_owner_stats(all_spaces):"""상위 500(global_rank <= 500)에 있는 스페이스들의 owner를 추출,각 owner별 등장 횟수를 구한 뒤 상위 30인만 반환"""top_500 = [s for s in all_spaces if s.get('global_rank', 999999) <= 500]owners = []for sp in top_500:sp_id = sp.get('id', '')if '/' in sp_id:o, _ = sp_id.split('/', 1)else:o = sp.get('owner', '')if o and o != 'None':owners.append(o)counts = Counter(owners)return counts.most_common(30)# --------------------- 캐시에 있는 스페이스에서 페이지네이션 처리 ---------------------def fetch_trending_spaces(offset=0, limit=24):global SPACE_CACHEtotal = len(SPACE_CACHE)start = min(offset, total)end = min(offset + limit, total)sliced = SPACE_CACHE[start:end]return {'spaces': sliced,'total': total,'offset': offset,'limit': limit,'all_spaces': SPACE_CACHE}# --------------------- 라우트: 메인 페이지 ---------------------@app.route('/')def home():"""index.html 템플릿을 렌더링"""return render_template('index.html')# --------------------- 라우트: Zero-GPU 스페이스 API ---------------------@app.route('/api/trending-spaces', methods=['GET'])def trending_spaces():"""- GET 파라미터 search, offset, limit 처리- 캐시된 스페이스 목록에서 페이지네이션- 검색어 검색- 통계(owner) 계산"""search_query = request.args.get('search', '').lower()offset = int(request.args.get('offset', 0))limit = int(request.args.get('limit', 24))data = fetch_trending_spaces(offset, limit)results = []for idx, sp in enumerate(data['spaces']):info = get_space_details(sp, idx, offset)if not info:continue# 검색어 필터if search_query:text_block = " ".join([info['title'].lower(),info['owner'].lower(),info['url'].lower(),info['description'].lower()])if search_query not in text_block:continueresults.append(info)top_owners = get_owner_stats(data['all_spaces'])return jsonify({'spaces': results,'total': data['total'],'offset': offset,'limit': limit,'top_owners': top_owners})# --------------------- 서버 실행 ---------------------if __name__ == '__main__':"""실행 시 templates/index.html 파일을 자동 생성 후 Flask 서버 시작"""os.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">2 unmodified lines<title>Huggingface Zero-GPU Spaces</title><script src="https://cdn.jsdelivr.net/npm/chart.js"></script><style>/* (질문 본문에 주어진 CSS 전부 삽입) */@import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;500;600;700&display=swap');:root {--pastel-pink: #FFD6E0;--pastel-blue: #C5E8FF;1 unmodified line--pastel-yellow: #FFF2CC;--pastel-green: #C7F5D9;--pastel-orange: #FFE0C3;--mac-window-bg: rgba(250, 250, 250, 0.85);--mac-toolbar: #F5F5F7;--mac-border: #E2E2E2;--mac-button-red: #FF5F56;--mac-button-yellow: #FFBD2E;--mac-button-green: #27C93F;--text-primary: #333;--text-secondary: #666;--box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);}* { margin: 0; padding: 0; box-sizing: border-box; }body {font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;line-height: 1.6;3 unmodified linesmin-height: 100vh;padding: 2rem;}.container { max-width: 1600px; margin: 0 auto; }.mac-window {background-color: var(--mac-window-bg);border-radius: 10px;3 unmodified linesmargin-bottom: 2rem;border: 1px solid var(--mac-border);}.mac-toolbar {display: flex; align-items: center; padding: 10px 15px;background-color: var(--mac-toolbar);border-bottom: 1px solid var(--mac-border);}.mac-buttons {display: flex; gap: 8px; margin-right: 15px;}.mac-button {width: 12px; height: 12px; border-radius: 50%; cursor: default;}.mac-close { background-color: var(--mac-button-red); }.mac-minimize { background-color: var(--mac-button-yellow); }.mac-maximize { background-color: var(--mac-button-green); }.mac-title {flex-grow: 1; text-align: center; font-size: 0.9rem; color: var(--text-secondary);}.mac-content { padding: 20px; }.header {text-align: center; margin-bottom: 1.5rem; position: relative;}.header h1 {font-size: 2.2rem; font-weight: 700; margin: 0; color: #2d3748; letter-spacing: -0.5px;}.header p {color: var(--text-secondary); margin-top: 0.5rem; font-size: 1.1rem;}.tab-nav {display: flex; justify-content: center; margin-bottom: 1.5rem;}.tab-button {border: none; background-color: #edf2f7; color: var(--text-primary);padding: 10px 20px; margin: 0 5px; cursor: pointer; border-radius: 5px;font-size: 1rem; font-weight: 600;}.tab-button.active {background-color: var(--pastel-purple); color: #fff;}.tab-content { display: none; }.tab-content.active { display: block; }.search-bar {display: flex; align-items: center; margin-bottom: 1.5rem;background-color: white; border-radius: 30px; padding: 5px;box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);max-width: 600px; margin-left: auto; margin-right: auto;}.search-bar input {flex-grow: 1; border: none; padding: 12px 20px; font-size: 1rem;outline: none; background: transparent; border-radius: 30px;}.search-bar .refresh-btn {background-color: var(--pastel-green); color: #1a202c; border: none;border-radius: 30px; padding: 10px 20px; font-size: 1rem; font-weight: 600;cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 8px;}.search-bar .refresh-btn:hover {background-color: #9ee7c0; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);}.refresh-icon {display: inline-block; width: 16px; height: 16px;border: 2px solid #1a202c; border-top-color: transparent; border-radius: 50%;animation: none;}.refreshing .refresh-icon {animation: spin 1s linear infinite;}@keyframes spin {0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); }}.grid-container {display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));gap: 1.5rem; margin-bottom: 2rem;}.grid-item {height: 500px; position: relative; overflow: hidden;transition: all 0.3s ease; border-radius: 15px;}.grid-item:nth-child(6n+1) { background-color: var(--pastel-pink); }.grid-item:nth-child(6n+2) { background-color: var(--pastel-blue); }.grid-item:nth-child(6n+3) { background-color: var(--pastel-purple); }.grid-item:nth-child(6n+4) { background-color: var(--pastel-yellow); }.grid-item:nth-child(6n+5) { background-color: var(--pastel-green); }.grid-item:nth-child(6n+6) { background-color: var(--pastel-orange); }.grid-item:hover {transform: translateY(-5px); box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);}.grid-header {padding: 15px; display: flex; flex-direction: column;background-color: rgba(255, 255, 255, 0.7); backdrop-filter: blur(5px);border-bottom: 1px solid rgba(0, 0, 0, 0.05);}.grid-header-top {display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;}.rank-badge {background-color: #1a202c; color: white; font-size: 0.8rem; font-weight: 600;padding: 4px 8px; border-radius: 50px; display: inline-block;}.grid-header h3 {margin: 0; font-size: 1.2rem; font-weight: 700; white-space: nowrap;overflow: hidden; text-overflow: ellipsis;}.grid-meta {display: flex; justify-content: space-between; align-items: center; font-size: 0.9rem;}.owner-info { color: var(--text-secondary); font-weight: 500; }.likes-counter {display: flex; align-items: center; color: #e53e3e; font-weight: 600;}.likes-counter span { margin-left: 4px; }.grid-actions {padding: 10px 15px; text-align: right;background-color: rgba(255, 255, 255, 0.7); backdrop-filter: blur(5px);position: absolute; bottom: 0; left: 0; right: 0; z-index: 10;display: flex; justify-content: flex-end;}.open-link {text-decoration: none; color: #2c5282; font-weight: 600; padding: 5px 10px;border-radius: 5px; transition: all 0.2s;background-color: rgba(237, 242, 247, 0.8);}.open-link:hover {background-color: #e2e8f0;}.grid-content {position: absolute; top: 0; left: 0; width: 100%; height: 100%;padding-top: 85px; padding-bottom: 45px;}.iframe-container {width: 100%; height: 100%; overflow: hidden; position: relative;}.grid-content iframe {transform: scale(0.7); transform-origin: top left;width: 142.857%; height: 142.857%; border: none; border-radius: 0;}.error-placeholder {position: absolute; top: 0; left: 0; width: 100%; height: 100%;display: flex; flex-direction: column; justify-content: center; align-items: center;padding: 20px; background-color: rgba(255, 255, 255, 0.9); text-align: center;}.error-emoji {font-size: 6rem; margin-bottom: 1.5rem; animation: bounce 1s infinite alternate;text-shadow: 0 10px 20px rgba(0,0,0,0.1);}@keyframes bounce {from { transform: translateY(0px) scale(1); }to { transform: translateY(-15px) scale(1.1); }}.pagination {display: flex; justify-content: center; align-items: center; gap: 10px; margin: 2rem 0;}.pagination-button {background-color: white; border: none; padding: 10px 20px; border-radius: 10px;font-size: 1rem; font-weight: 600; cursor: pointer; transition: all 0.2s;color: var(--text-primary); box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);}.pagination-button:hover {background-color: #f8f9fa; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);}.pagination-button.active {background-color: var(--pastel-purple); color: #4a5568;}.pagination-button:disabled {background-color: #edf2f7; color: #a0aec0; cursor: default; box-shadow: none;}.loading {position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(255, 255, 255, 0.8);backdrop-filter: blur(5px); display: flex; justify-content: center; align-items: center;z-index: 1000;}.loading-content { text-align: center; }.loading-spinner {width: 60px; height: 60px; border: 5px solid #e2e8f0;border-top-color: var(--pastel-purple); border-radius: 50%;animation: spin 1s linear infinite;margin: 0 auto 15px;}.loading-text {font-size: 1.2rem; font-weight: 600; color: #4a5568;}.loading-error {display: none; margin-top: 10px; color: #e53e3e; font-size: 0.9rem;}.stats-window {margin-top: 2rem; margin-bottom: 2rem;}.stats-header {display: flex; justify-content: space-between; align-items: center;margin-bottom: 1rem;}.stats-title {font-size: 1.5rem; font-weight: 700; color: #2d3748;}.stats-toggle {background-color: var(--pastel-blue); border: none; padding: 8px 16px;border-radius: 20px; font-weight: 600; cursor: pointer; transition: all 0.2s;}.stats-toggle:hover {background-color: var(--pastel-purple);}.stats-content {background-color: white; border-radius: 10px; padding: 20px; box-shadow: var(--box-shadow);max-height: 0; overflow: hidden; transition: max-height 0.5s ease-out;}.stats-content.open {max-height: 600px;}.chart-container {width: 100%; height: 500px;}@media (max-width: 768px) {body { padding: 1rem; }.grid-container { grid-template-columns: 1fr; }.search-bar {flex-direction: column; padding: 10px;}.search-bar input {width: 100%; margin-bottom: 10px;}.search-bar .refresh-btn {width: 100%; justify-content: center;}.pagination { flex-wrap: wrap; }.chart-container { height: 300px; }}.error-emoji-detector {position: fixed; top: -9999px; left: -9999px; z-index: -1; opacity: 0;}.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>8 unmodified lines</div><div class="mac-title">Huggingface Explorer</div></div><div class="mac-content"><div class="header"><h1>ZeroGPU Spaces Leaderboard</h1><p>Discover Zero GPU(Shared A100) spaces from Hugging Face</p></div><div class="tab-nav"><button id="tabTrendingButton" class="tab-button active">Trending</button><button id="tabFixedButton" class="tab-button">Picks</button></div><div id="trendingTab" class="tab-content active"><div class="stats-window mac-window"><div class="mac-toolbar">16 unmodified lines</div></div></div><div class="search-bar"><input type="text" id="searchInput" placeholder="Search by name, owner, or description..." /><button id="refreshButton" class="refresh-btn">1 unmodified lineRefresh</button></div><div id="gridContainer" class="grid-container"></div><div id="pagination" class="pagination"></div></div><div id="fixedTab" class="tab-content"><div id="fixedGrid" class="grid-container"></div></div></div></div></div><div id="loadingIndicator" class="loading"><div class="loading-content"><div class="loading-spinner"></div><div class="loading-text">Loading Zero-GPU spaces...</div><div id="loadingError" class="loading-error">If this takes too long, try refreshing the page.</div></div></div><script>// ------------------- Front-End JS (동일) -------------------const elements = {gridContainer: document.getElementById('gridContainer'),loadingIndicator: document.getElementById('loadingIndicator'),5 unmodified linesstatsContent: document.getElementById('statsContent'),creatorStatsChart: document.getElementById('creatorStatsChart')};const tabTrendingButton = document.getElementById('tabTrendingButton');const tabFixedButton = document.getElementById('tabFixedButton');const trendingTab = document.getElementById('trendingTab');4 unmodified linesisLoading: false,spaces: [],currentPage: 0,itemsPerPage: 24,totalItems: 0,loadingTimeout: null,staticModeAttempted: {},3 unmodified linesiframeStatuses: {}};// iframe 로딩 및 에러 감지const iframeLoader = {checkQueue: {},maxAttempts: 5,checkInterval: 5000,startChecking(iframe, owner, name, title, spaceKey) {this.checkQueue[spaceKey] = {iframe, owner, name, title,attempts: 0, status: 'loading'};this.checkIframeStatus(spaceKey);},checkIframeStatus(spaceKey) {if (!this.checkQueue[spaceKey]) return;const item = this.checkQueue[spaceKey];if (item.status !== 'loading') {delete this.checkQueue[spaceKey];return;}item.attempts++;try {if (!item.iframe || !item.iframe.parentNode) {delete this.checkQueue[spaceKey];return;}try {const hasContent = item.iframe.contentWindow &&item.iframe.contentWindow.document &&item.iframe.contentWindow.document.body;if (hasContent &&item.iframe.contentWindow.document.body.innerHTML.length > 100) {const bodyText = item.iframe.contentWindow.document.body.textContent.toLowerCase();if (bodyText.includes('forbidden') ||bodyText.includes('404') ||bodyText.includes('not found') ||bodyText.includes('error')) {item.status = 'error';handleIframeError(item.iframe, item.owner, item.name, item.title);} else {3 unmodified linesreturn;}} catch(e) {// 크로스 도메인 에러는 단순무시}const rect = item.iframe.getBoundingClientRect();if (rect.width > 50 && rect.height > 50 && item.attempts > 2) {item.status = 'success';delete this.checkQueue[spaceKey];return;}if (item.attempts >= this.maxAttempts) {if (item.iframe.offsetWidth > 0 && item.iframe.offsetHeight > 0) {item.status = 'success';4 unmodified linesdelete this.checkQueue[spaceKey];return;}const nextDelay = this.checkInterval * Math.pow(1.5, item.attempts - 1);setTimeout(() => this.checkIframeStatus(spaceKey), nextDelay);} catch (e) {console.error('Error checking iframe status:', e);if (item.attempts >= this.maxAttempts) {11 unmodified linesstate.statsVisible = !state.statsVisible;elements.statsContent.classList.toggle('open', state.statsVisible);elements.statsToggle.textContent = state.statsVisible ? 'Hide Stats' : 'Show Stats';if (state.statsVisible && state.topOwners.length > 0) {renderCreatorStats();}}function renderCreatorStats() {if (state.chartInstance) {state.chartInstance.destroy();1 unmodified lineconst ctx = elements.creatorStatsChart.getContext('2d');const labels = state.topOwners.map(item => item[0]);const data = state.topOwners.map(item => item[1]);const colors = [];for (let i=0; i<labels.length; i++) {const hue = (i*360/labels.length) % 360;colors.push(`hsla(${hue}, 70%, 80%, 0.7)`);}state.chartInstance = new Chart(ctx, {type: 'bar',data: {labels,datasets: [{label: 'Number of Spaces in Top 500',data,backgroundColor: colors,borderColor: colors.map(c => c.replace('0.7', '1')),borderWidth: 1}]},5 unmodified lineslegend: { display: false },tooltip: {callbacks: {title(tooltipItems) { return tooltipItems[0].label; },label(context) { return `Spaces: ${context.raw}`; }}}},scales: {x: {beginAtZero: true,title: { display: true, text: 'Number of Spaces' }},y: {title: { display: true, text: 'Creator ID' },ticks: {autoSkip: false,font(context) {const defaultSize = 11;return { size: labels.length>20 ? defaultSize-1 : defaultSize };}}}1 unmodified line}});}async function loadSpaces(page=0) {setLoading(true);try {const searchText = elements.searchInput.value;const offset = page * state.itemsPerPage;const timeoutPromise = new Promise((_, reject) => {setTimeout(() => reject(new Error('Request timeout')), 30000);});const fetchPromise = fetch(`/api/trending-spaces?search=${encodeURIComponent(searchText)}&offset=${offset}&limit=${state.itemsPerPage}`);7 unmodified linesrenderGrid(state.spaces);renderPagination();if (state.statsVisible && state.topOwners.length>0) {renderCreatorStats();}} catch (error) {14 unmodified linessetLoading(false);}}function renderPagination() {elements.pagination.innerHTML = '';const totalPages = Math.ceil(state.totalItems / state.itemsPerPage);const prevButton = document.createElement('button');prevButton.className = 'pagination-button';prevButton.textContent = 'Previous';prevButton.disabled = (state.currentPage === 0);prevButton.addEventListener('click', () => {if (state.currentPage>0) loadSpaces(state.currentPage-1);});elements.pagination.appendChild(prevButton);const maxButtons = 7;let startPage = Math.max(0, state.currentPage - Math.floor(maxButtons/2));let endPage = Math.min(totalPages-1, startPage + maxButtons -1);if (endPage-startPage+1 < maxButtons) {startPage = Math.max(0, endPage-maxButtons+1);}for (let i=startPage; i<=endPage; i++) {const pageButton = document.createElement('button');pageButton.className = 'pagination-button' + (i===state.currentPage ? ' active' : '');pageButton.textContent = (i+1);pageButton.addEventListener('click', () => {if (i!==state.currentPage) loadSpaces(i);});elements.pagination.appendChild(pageButton);}const nextButton = document.createElement('button');nextButton.className = 'pagination-button';nextButton.textContent = 'Next';nextButton.disabled = (state.currentPage >= totalPages-1);nextButton.addEventListener('click', () => {if (state.currentPage < totalPages-1) {loadSpaces(state.currentPage+1);}});elements.pagination.appendChild(nextButton);}function handleIframeError(iframe, owner, name, title) {const container = iframe.parentNode;const errorPlaceholder = document.createElement('div');errorPlaceholder.className = 'error-placeholder';const errorMessage = document.createElement('p');errorMessage.textContent = `"${title}" space couldn't be loaded`;errorPlaceholder.appendChild(errorMessage);const directLink = document.createElement('a');directLink.href = `https://huggingface.co/spaces/${owner}/${name}`;directLink.target = '_blank';5 unmodified linesdirectLink.style.background = '#ebf8ff';directLink.style.borderRadius = '5px';directLink.style.fontWeight = '600';errorPlaceholder.appendChild(directLink);iframe.style.display = 'none';container.appendChild(errorPlaceholder);}function renderGrid(spaces) {elements.gridContainer.innerHTML = '';if (!spaces || spaces.length===0) {const noResultsMsg = document.createElement('p');noResultsMsg.textContent = 'No zero-gpu spaces found matching your search.';noResultsMsg.style.padding = '2rem';3 unmodified lineselements.gridContainer.appendChild(noResultsMsg);return;}spaces.forEach(item => {try {const { url, title, likes_count, owner, name, rank, description, avatar_url, author_name, embedUrl } = item;const gridItem = document.createElement('div');gridItem.className = 'grid-item';const headerDiv = document.createElement('div');headerDiv.className = 'grid-header';const spaceHeader = document.createElement('div');spaceHeader.className = 'space-header';const rankBadge = document.createElement('div');rankBadge.className = 'rank-badge';rankBadge.textContent = `#${rank}`;spaceHeader.appendChild(rankBadge);const titleWrapper = document.createElement('div');titleWrapper.style.display = 'flex';titleWrapper.style.alignItems = 'center';9 unmodified lineszeroGpuBadge.className = 'zero-gpu-badge';zeroGpuBadge.textContent = 'ZERO GPU';titleWrapper.appendChild(zeroGpuBadge);spaceHeader.appendChild(titleWrapper);headerDiv.appendChild(spaceHeader);const metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';metaInfo.style.display = 'flex';1 unmodified linemetaInfo.style.alignItems = 'center';metaInfo.style.marginTop = '6px';const leftMeta = document.createElement('div');const authorSpan = document.createElement('span');authorSpan.className = 'author-name';authorSpan.style.marginLeft = '8px';authorSpan.textContent = `by ${author_name}`;leftMeta.appendChild(authorSpan);metaInfo.appendChild(leftMeta);const likesDiv = document.createElement('div');likesDiv.className = 'likes-wrapper';likesDiv.innerHTML = `<span class="likes-heart">♥</span><span>${likes_count}</span>`;2 unmodified linesheaderDiv.appendChild(metaInfo);gridItem.appendChild(headerDiv);if (description) {const descP = document.createElement('p');descP.className = 'desc-text';descP.textContent = description;gridItem.appendChild(descP);}const content = document.createElement('div');content.className = 'grid-content';1 unmodified lineiframeContainer.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','');iframe.setAttribute('frameborder','0');iframe.loading = 'lazy';const spaceKey = `${owner}/${name}`;7 unmodified linesstate.iframeStatuses[spaceKey] = 'error';};setTimeout(() => {if (state.iframeStatuses[spaceKey]==='loading') {handleIframeError(iframe, owner, name, title);state.iframeStatuses[spaceKey] = 'error';}2 unmodified linesiframeContainer.appendChild(iframe);content.appendChild(iframeContainer);const actions = document.createElement('div');actions.className = 'grid-actions';6 unmodified linesactions.appendChild(linkEl);gridItem.appendChild(content);gridItem.appendChild(actions);elements.gridContainer.appendChild(gridItem);} catch (err) {console.error('Item rendering error:', err);}});}function renderFixedGrid() {// 예시 PicksfixedGridContainer.innerHTML = '';const staticSpaces = [{url: "https://huggingface.co/spaces/VIDraft/SanaSprint",10 unmodified linesowner: "VIDraft",name: "SanaSprint",rank: 2}];if (!staticSpaces || staticSpaces.length===0) {const noResultsMsg = document.createElement('p');noResultsMsg.textContent = 'No spaces to display.';noResultsMsg.style.padding = '2rem';3 unmodified linesfixedGridContainer.appendChild(noResultsMsg);return;}staticSpaces.forEach(item => {try {const { url, title, likes_count, owner, name, rank } = item;const gridItem = document.createElement('div');1 unmodified lineconst 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';const emojiAvatar = document.createElement('div');emojiAvatar.className = 'emoji-avatar';emojiAvatar.textContent = '🤖';3 unmodified linestitleEl.textContent = title;titleEl.title = title;leftWrapper.appendChild(titleEl);headerTop.appendChild(leftWrapper);const rankBadge = document.createElement('div');2 unmodified linesheaderTop.appendChild(rankBadge);header.appendChild(headerTop);const metaInfo = document.createElement('div');metaInfo.className = 'grid-meta';12 unmodified linesconst content = document.createElement('div');content.className = 'grid-content';const iframeContainer = document.createElement('div');iframeContainer.className = 'iframe-container';1 unmodified lineiframe.src = "https://" + owner.toLowerCase() + "-" + name.toLowerCase() + ".hf.space";iframe.title = title;iframe.allow = 'accelerometer; camera; encrypted-media; geolocation; gyroscope;';iframe.setAttribute('allowfullscreen','');iframe.setAttribute('frameborder','0');iframe.loading = 'lazy';const spaceKey = `${owner}/${name}`;4 unmodified lineshandleIframeError(iframe, owner, name, title);};setTimeout(() => {if (iframe.offsetWidth===0 || iframe.offsetHeight===0) {handleIframeError(iframe, owner, name, title);}}, 30000);3 unmodified linesconst actions = document.createElement('div');actions.className = 'grid-actions';const linkEl = document.createElement('a');linkEl.href = url;linkEl.target = '_blank';3 unmodified linesgridItem.appendChild(content);gridItem.appendChild(actions);fixedGridContainer.appendChild(gridItem);} catch (error) {console.error('Fixed tab rendering error:', error);}});}tabTrendingButton.addEventListener('click', () => {tabTrendingButton.classList.add('active');tabFixedButton.classList.remove('active');8 unmodified linestrendingTab.classList.remove('active');renderFixedGrid();});elements.searchInput.addEventListener('input', () => {clearTimeout(state.searchTimeout);state.searchTimeout = setTimeout(() => loadSpaces(0), 300);});elements.searchInput.addEventListener('keyup', (event) => {if (event.key==='Enter') {loadSpaces(0);}});3 unmodified lineswindow.addEventListener('load', function() {setTimeout(() => loadSpaces(0), 500);});setTimeout(() => {if (state.isLoading) {setLoading(false);15 unmodified linesfunction setLoading(isLoading) {state.isLoading = isLoading;elements.loadingIndicator.style.display = isLoading ? 'flex' : 'none';if (isLoading) {elements.refreshButton.classList.add('refreshing');clearTimeout(state.loadingTimeout);11 unmodified lines</html>''')# Flask 실행app.run(host='0.0.0.0', port=7860)
app.py+287-770