Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345678916 unmodified lines26272829303132339 unmodified lines434445464748495051525354126 unmodified lines1811821831841851861876 unmodified lines19419519619719819920035 unmodified lines2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892 unmodified lines2922932942952962972982993001 unmodified line3023033043053063073083093103113123133143153163173183193203213223233243253263 unmodified lines3303313323333343353363373383393403413 unmodified lines3453463473483493503511 unmodified line3533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004011 unmodified line4034044054064074084094104114124134144154164174184194204215 unmodified lines4274284294304314324334344354364374384394404414424434444454466 unmodified lines4534544554564574584593 unmodified lines4634644654664674684698 unmodified lines4784794804814824834844854864874884893 unmodified lines4934944954964974984995005015025035045055065075085095105115125135145151 unmodified line5175185195205215225235245255265275285295305315325335345352 unmodified lines5385395405415425435445455465475485495505513 unmodified lines5555565575585595605612 unmodified lines5645655665675685695705715725735745755765775785795805815825835845855865875885895905915925937 unmodified lines6016026036046056066073 unmodified lines6116126136146156166176186196206213 unmodified lines6256266276286296306316326336346356366376383 unmodified lines6426436446456466476488 unmodified lines6576586596606616626636646656666676686696702 unmodified lines6736746756766776786792 unmodified lines6826836846856866876886 unmodified lines6956966976986997007017027037047057067077087097107117127137147157167177188 unmodified lines7277287297307317327337347357367373 unmodified lines7417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787793 unmodified lines7837847857867877887897907917927933 unmodified lines79779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584670 unmodified lines91791891992092192292312 unmodified lines93693793893994094194294394494531 unmodified lines97797897998098198298398498598698798812 unmodified lines1001100210031004100510061007100810094 unmodified lines101410151016101710181019102010211022102310241025102610271028102910301031103210338 unmodified lines104210431044104510461047104871 unmodified lines11201121112211231124112590 unmodified lines121612171218121912201221232 unmodified lines1454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616133 unmodified lines17501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117926 unmodified lines179918001801180218031804180514 unmodified lines18201821182218231824182518262 unmodified linesimport osfrom collections import Counterfrom datetime import datetimeimport dateutil.parser # ← 추가############################################################################### 1) 전역 변수 & 더미 데이터16 unmodified lines'title': f'Dummy Space {i+1}','description': 'This is a fallback dummy space.','likes': 100 - i,# createdAt도 예시로 추가 (모두 동일 날짜)'createdAt': '2023-01-01T00:00:00.000Z','hardware': 'cpu','user': {'avatar_url': 'https://huggingface.co/front/thumbnails/huggingface/default-avatar.svg',9 unmodified linesdef fetch_zero_gpu_spaces_once():"""Hugging Face API (hardware=cpu) 스페이스 목록을 가져옴limit을 작게 설정하여 응답 속도를 개선"""try:url = "https://huggingface.co/api/spaces"params = {"limit": 1000, # 너무 크게 잡으면 응답 지연 → (원래 50~200 추천, 여기선 1000)"hardware": "cpu"}resp = requests.get(url, params=params, timeout=30)126 unmodified lines}############################################################################### 4) Flask 라우트 (Trending & New Created & Picks)##############################################################################@app.route('/')6 unmodified lines@app.route('/api/trending-spaces', methods=['GET'])def trending_spaces():"""Zero-GPU 스페이스 목록 (기존 트렌딩)- Lazy Load로 캐시 로드- offset, limit 파라미터로 페이지네이션- search 파라미터로 검색35 unmodified lines'top_owners': top_owners})@app.route('/api/new-created-spaces', methods=['GET'])def new_created_spaces():"""NEW CREATED 탭용:- 전역 캐시에서 createdAt 기준 내림차순으로 정렬- 최대 100개만 반환"""ensure_cache_loaded()# createdAt이 ISO8601 형태인지 확인 후 파싱. 실패 시 datetime.min 사용def parse_created_at(space):date_str = space.get('createdAt', '')try:return dateutil.parser.isoparse(date_str)except:return datetime.min# createdAt 기준으로 파싱하여 내림차순 정렬sorted_by_new = sorted(SPACE_CACHE,key=lambda s: parse_created_at(s),reverse=True)# 최대 100개까지만newest_100 = sorted_by_new[:100]final = []for i, sp in enumerate(newest_100):# rank는 단순 i+1 로detail = get_space_details(sp, i, 0)if detail:final.append(detail)return jsonify({'spaces': final})############################################################################### 5) 서버 실행 (templates/index.html 작성)##############################################################################if __name__ == '__main__':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;1 unmodified linebackground-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;1 unmodified linecolor: #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;5 unmodified linesfont-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;6 unmodified linesmargin-left: auto;margin-right: auto;}.search-bar input {flex-grow: 1;border: none;3 unmodified linesbackground: transparent;border-radius: 30px;}.search-bar .refresh-btn {background-color: var(--pastel-green);color: #1a202c;8 unmodified linesalign-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;3 unmodified linesborder-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;1 unmodified linetransition: 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;2 unmodified linesbackdrop-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;3 unmodified linesborder-radius: 50px;display: inline-block;}.grid-header h3 {margin: 0;font-size: 1.2rem;2 unmodified linesoverflow: 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;7 unmodified linesdisplay: flex;justify-content: flex-end;}.open-link {text-decoration: none;color: #2c5282;3 unmodified linestransition: all 0.2s;background-color: rgba(237, 242, 247, 0.8);}.open-link:hover {background-color: #e2e8f0;}.grid-content {position: absolute;top: 0;3 unmodified linespadding-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);3 unmodified linesborder: none;border-radius: 0;}.error-placeholder {position: absolute;top: 0;8 unmodified linesbackground-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);2 unmodified linestransform: translateY(-15px) scale(1.1);}}/* Pagination Styling */.pagination {display: flex;2 unmodified linesgap: 10px;margin: 2rem 0;}.pagination-button {background-color: white;border: none;6 unmodified linescolor: 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;8 unmodified linesalign-items: center;z-index: 1000;}.loading-content {text-align: center;}.loading-spinner {width: 60px;height: 60px;3 unmodified linesanimation: 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;3 unmodified linescursor: pointer;transition: all 0.2s;}.stats-toggle:hover {background-color: var(--pastel-purple);}.stats-content {background-color: white;border-radius: 10px;3 unmodified linesoverflow: 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;70 unmodified linesalign-items: center;justify-content: center;}/* ==================== CSS 끝 ==================== */</style></head><body>12 unmodified lines<h1>ZeroGPU Spaces Leaderboard</h1><p>Discover Zero GPU(Shared A100) spaces from Hugging Face</p></div><!-- 탭 네비게이션: (1) Trending, (2) New Created, (3) Picks --><div class="tab-nav"><button id="tabTrendingButton" class="tab-button active">Trending</button><button id="tabNewCreatedButton" class="tab-button">New Created</button><button id="tabFixedButton" class="tab-button">Picks</button></div>31 unmodified lines<div id="pagination" class="pagination"></div></div><!-- New Created Tab Content --><div id="newCreatedTab" class="tab-content"><!-- 새로 생성된 스페이스를 표시할 그리드 --><div id="newCreatedGrid" class="grid-container"></div></div><!-- Picks Tab Content (기존) --><div id="fixedTab" class="tab-content"><div id="fixedGrid" class="grid-container"></div>12 unmodified lines</div><script>/* ==================== JS 로직 (질문 본문의 기존 로직 + New Created 탭 추가) ==================== */// DOM Elementsconst elements = {gridContainer: document.getElementById('gridContainer'),loadingIndicator: document.getElementById('loadingIndicator'),4 unmodified linesstatsToggle: document.getElementById('statsToggle'),statsContent: document.getElementById('statsContent'),creatorStatsChart: document.getElementById('creatorStatsChart'),newCreatedGrid: document.getElementById('newCreatedGrid')};// 탭const tabTrendingButton = document.getElementById('tabTrendingButton');const tabNewCreatedButton = document.getElementById('tabNewCreatedButton');const tabFixedButton = document.getElementById('tabFixedButton');// 탭 내용const trendingTab = document.getElementById('trendingTab');const newCreatedTab = document.getElementById('newCreatedTab');const fixedTab = document.getElementById('fixedTab');const state = {isLoading: false,spaces: [],8 unmodified linesiframeStatuses: {}};// iframe 에러 감지 로더const iframeLoader = {checkQueue: {},maxAttempts: 5,71 unmodified lines}};function toggleStats() {state.statsVisible = !state.statsVisible;elements.statsContent.classList.toggle('open', state.statsVisible);90 unmodified linesrenderGrid(state.spaces);renderPagination();if (state.statsVisible && state.topOwners.length > 0) {renderCreatorStats();}232 unmodified lines});}// --------------------- NEW CREATED ---------------------// 새로 생성된 스페이스(최신 순 100개) 불러오기function loadNewCreatedSpaces() {setLoading(true);fetch('/api/new-created-spaces').then(res => res.json()).then(data => {setLoading(false);renderNewCreatedGrid(data.spaces);}).catch(err => {setLoading(false);console.error('Error loading new-created spaces:', err);elements.newCreatedGrid.innerHTML = '<p style="padding:2rem;text-align:center;color:#666;">Unable to load new created spaces</p>';});}function renderNewCreatedGrid(spaces) {elements.newCreatedGrid.innerHTML = '';if (!spaces || spaces.length === 0) {const noResults = document.createElement('p');noResults.textContent = 'No newly created zero-gpu spaces found.';noResults.style.padding = '2rem';noResults.style.textAlign = 'center';noResults.style.fontStyle = 'italic';noResults.style.color = '#718096';elements.newCreatedGrid.appendChild(noResults);return;}// 최신 생성된 스페이스 100개를 표시하므로, rank는 i+1 로 단순 부여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';// Headerconst 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';titleWrapper.style.marginLeft = '8px';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);const 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';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>`;metaInfo.appendChild(likesDiv);headerDiv.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';const iframeContainer = document.createElement('div');iframeContainer.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}`;state.iframeStatuses[spaceKey] = 'loading';iframe.onload = function() {iframeLoader.startChecking(iframe, owner, name, title, spaceKey);};iframe.onerror = function() {handleIframeError(iframe, owner, name, title);state.iframeStatuses[spaceKey] = 'error';};setTimeout(() => {if (state.iframeStatuses[spaceKey] === 'loading') {handleIframeError(iframe, owner, name, title);state.iframeStatuses[spaceKey] = 'error';}}, 30000);iframeContainer.appendChild(iframe);content.appendChild(iframeContainer);const actions = document.createElement('div');actions.className = 'grid-actions';const linkEl = document.createElement('a');linkEl.href = url;linkEl.target = '_blank';linkEl.className = 'open-link';linkEl.textContent = 'Open in new window';actions.appendChild(linkEl);gridItem.appendChild(content);gridItem.appendChild(actions);elements.newCreatedGrid.appendChild(gridItem);} catch (err) {console.error('Item rendering error:', err);}});}// --------------------- PICKS (기존) ---------------------function renderFixedGrid() {// 예시용 정적 목록const fixedGridContainer = document.getElementById('fixedGrid');133 unmodified lines// --------------------- Tab Switching ---------------------tabTrendingButton.addEventListener('click', () => {tabTrendingButton.classList.add('active');tabNewCreatedButton.classList.remove('active');tabFixedButton.classList.remove('active');trendingTab.classList.add('active');newCreatedTab.classList.remove('active');fixedTab.classList.remove('active');// 기존 Trending 목록 로딩loadSpaces(state.currentPage);});tabNewCreatedButton.addEventListener('click', () => {tabTrendingButton.classList.remove('active');tabNewCreatedButton.classList.add('active');tabFixedButton.classList.remove('active');trendingTab.classList.remove('active');newCreatedTab.classList.add('active');fixedTab.classList.remove('active');// 새로 만든 New Created 목록 로딩loadNewCreatedSpaces();});tabFixedButton.addEventListener('click', () => {tabTrendingButton.classList.remove('active');tabNewCreatedButton.classList.remove('active');tabFixedButton.classList.add('active');trendingTab.classList.remove('active');newCreatedTab.classList.remove('active');fixedTab.classList.add('active');renderFixedGrid();});// 검색 입력 관련elements.searchInput.addEventListener('input', () => {clearTimeout(state.searchTimeout);state.searchTimeout = setTimeout(() => loadSpaces(0), 300);6 unmodified lineselements.refreshButton.addEventListener('click', () => loadSpaces(0));elements.statsToggle.addEventListener('click', toggleStats);// 페이지 로드 시 초기 탭(Trending) 불러오기window.addEventListener('load', function() {setTimeout(() => loadSpaces(0), 500);});14 unmodified lines}}, 20000);// 로딩 표시는 공통function setLoading(isLoading) {state.isLoading = isLoading;elements.loadingIndicator.style.display = isLoading ? 'flex' : 'none';2 unmodified lines345678916 unmodified lines262728293031329 unmodified lines4243444546474849505152126 unmodified lines1791801811821831841856 unmodified lines19219319419519619719835 unmodified lines2342352362372382392402412422432442452462 unmodified lines2492502512522532542552562571 unmodified line2592602612622632642652662672682692702712722732742752762772782792802812822833 unmodified lines2872882892902912922932942952962972983 unmodified lines3023033043053063073081 unmodified line3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573581 unmodified line3603613623633643653663673683693703713723733743753763773785 unmodified lines3843853863873883893903913923933943953963973983994004014024036 unmodified lines4104114124134144154163 unmodified lines4204214224234244254268 unmodified lines4354364374384394404414424434444454463 unmodified lines4504514524534544554564574584594604614624634644654664674684694704714721 unmodified line4744754764774784794804814824834844854864874884894904914922 unmodified lines4954964974984995005015025035045055065075083 unmodified lines5125135145155165175182 unmodified lines5215225235245255265275285295305315325335345355365375385395405415425435445455465475485495507 unmodified lines5585595605615625635643 unmodified lines5685695705715725735745755765775783 unmodified lines5825835845855865875885895905915925935945953 unmodified lines5996006016026036046058 unmodified lines6146156166176186196206216226236246256266272 unmodified lines6306316326336346356362 unmodified lines6396406416426436446456 unmodified lines6526536546556566576586596606616626636646656666676686696706716726736746758 unmodified lines6846856866876886896906916926936943 unmodified lines6986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357363 unmodified lines7407417427437447457467477487497503 unmodified lines75475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280370 unmodified lines87487587687787887912 unmodified lines89289389489589689789889990031 unmodified lines93293393493593693712 unmodified lines9509519529539549559564 unmodified lines9619629639649659669679689699709719729739749759769779788 unmodified lines98798898999099199299371 unmodified lines106510661067106810691070107190 unmodified lines1162116311641165116611671168232 unmodified lines1401140214031404140514061407133 unmodified lines15411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415656 unmodified lines157215731574157515761577157814 unmodified lines1593159415951596159715982 unmodified linesimport osfrom collections import Counterfrom datetime import datetimeimport dateutil.parser # 현재 코드에서 dateutil.parser는 쓰지 않지만, 다른 부분에 필요할 수도 있어 남김############################################################################### 1) 전역 변수 & 더미 데이터16 unmodified lines'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','user': {'avatar_url': 'https://huggingface.co/front/thumbnails/huggingface/default-avatar.svg',9 unmodified linesdef fetch_zero_gpu_spaces_once():"""Hugging Face API (hardware=cpu) 스페이스 목록을 가져옴"""try:url = "https://huggingface.co/api/spaces"params = {"limit": 1000,"hardware": "cpu"}resp = requests.get(url, params=params, timeout=30)126 unmodified lines}############################################################################### 4) Flask 라우트##############################################################################@app.route('/')6 unmodified lines@app.route('/api/trending-spaces', methods=['GET'])def trending_spaces():"""Zero-GPU 스페이스 목록 (트렌딩)- Lazy Load로 캐시 로드- offset, limit 파라미터로 페이지네이션- search 파라미터로 검색35 unmodified lines'top_owners': top_owners})############################################################################### 5) 서버 실행 (templates/index.html)##############################################################################if __name__ == '__main__':os.makedirs('templates', exist_ok=True)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;1 unmodified linebackground-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;1 unmodified linecolor: #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;5 unmodified linesfont-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;6 unmodified linesmargin-left: auto;margin-right: auto;}.search-bar input {flex-grow: 1;border: none;3 unmodified linesbackground: transparent;border-radius: 30px;}.search-bar .refresh-btn {background-color: var(--pastel-green);color: #1a202c;8 unmodified linesalign-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;3 unmodified linesborder-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;1 unmodified linetransition: 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;2 unmodified linesbackdrop-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;3 unmodified linesborder-radius: 50px;display: inline-block;}.grid-header h3 {margin: 0;font-size: 1.2rem;2 unmodified linesoverflow: 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;7 unmodified linesdisplay: flex;justify-content: flex-end;}.open-link {text-decoration: none;color: #2c5282;3 unmodified linestransition: all 0.2s;background-color: rgba(237, 242, 247, 0.8);}.open-link:hover {background-color: #e2e8f0;}.grid-content {position: absolute;top: 0;3 unmodified linespadding-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);3 unmodified linesborder: none;border-radius: 0;}.error-placeholder {position: absolute;top: 0;8 unmodified linesbackground-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);2 unmodified linestransform: translateY(-15px) scale(1.1);}}/* Pagination Styling */.pagination {display: flex;2 unmodified linesgap: 10px;margin: 2rem 0;}.pagination-button {background-color: white;border: none;6 unmodified linescolor: 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;8 unmodified linesalign-items: center;z-index: 1000;}.loading-content {text-align: center;}.loading-spinner {width: 60px;height: 60px;3 unmodified linesanimation: 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;3 unmodified linescursor: pointer;transition: all 0.2s;}.stats-toggle:hover {background-color: var(--pastel-purple);}.stats-content {background-color: white;border-radius: 10px;3 unmodified linesoverflow: 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;70 unmodified linesalign-items: center;justify-content: center;}</style></head><body>12 unmodified lines<h1>ZeroGPU Spaces Leaderboard</h1><p>Discover Zero GPU(Shared A100) spaces from Hugging Face</p></div><!-- 탭 네비게이션: (1) Trending, (2) Picks) --><div class="tab-nav"><button id="tabTrendingButton" class="tab-button active">Trending</button><button id="tabFixedButton" class="tab-button">Picks</button></div>31 unmodified lines<div id="pagination" class="pagination"></div></div><!-- Picks Tab Content (기존) --><div id="fixedTab" class="tab-content"><div id="fixedGrid" class="grid-container"></div>12 unmodified lines</div><script>// --------------------- 전역 DOM Elements ---------------------const elements = {gridContainer: document.getElementById('gridContainer'),loadingIndicator: document.getElementById('loadingIndicator'),4 unmodified linesstatsToggle: document.getElementById('statsToggle'),statsContent: document.getElementById('statsContent'),creatorStatsChart: document.getElementById('creatorStatsChart'),// second tab 제거로 newCreatedGrid는 제거};// --------------------- 탭 버튼 ---------------------const tabTrendingButton = document.getElementById('tabTrendingButton');const tabFixedButton = document.getElementById('tabFixedButton');// 탭 내용const trendingTab = document.getElementById('trendingTab');const fixedTab = document.getElementById('fixedTab');// --------------------- 상태 ---------------------const state = {isLoading: false,spaces: [],8 unmodified linesiframeStatuses: {}};// --------------------- iframe 에러 감지 로직 ---------------------const iframeLoader = {checkQueue: {},maxAttempts: 5,71 unmodified lines}};// --------------------- 통계 창 toggle ---------------------function toggleStats() {state.statsVisible = !state.statsVisible;elements.statsContent.classList.toggle('open', state.statsVisible);90 unmodified linesrenderGrid(state.spaces);renderPagination();// 통계 Visible 상태라면 업데이트if (state.statsVisible && state.topOwners.length > 0) {renderCreatorStats();}232 unmodified lines});}// --------------------- PICKS (정적) ---------------------function renderFixedGrid() {// 예시용 정적 목록const fixedGridContainer = document.getElementById('fixedGrid');133 unmodified lines// --------------------- Tab Switching ---------------------tabTrendingButton.addEventListener('click', () => {tabTrendingButton.classList.add('active');tabFixedButton.classList.remove('active');trendingTab.classList.add('active');fixedTab.classList.remove('active');loadSpaces(state.currentPage);});tabFixedButton.addEventListener('click', () => {tabTrendingButton.classList.remove('active');tabFixedButton.classList.add('active');trendingTab.classList.remove('active');fixedTab.classList.add('active');renderFixedGrid();});// 검색 입력elements.searchInput.addEventListener('input', () => {clearTimeout(state.searchTimeout);state.searchTimeout = setTimeout(() => loadSpaces(0), 300);6 unmodified lineselements.refreshButton.addEventListener('click', () => loadSpaces(0));elements.statsToggle.addEventListener('click', toggleStats);// 페이지 로드 시 첫 탭(Trending) 실행window.addEventListener('load', function() {setTimeout(() => loadSpaces(0), 500);});14 unmodified lines}}, 20000);function setLoading(isLoading) {state.isLoading = isLoading;elements.loadingIndicator.style.display = isLoading ? 'flex' : 'none';
app.py+95-323