Spaces:
Sleeping
Sleeping
Update app.py
Browse files31 unmodified lines323334353637383953 unmodified lines93949596979813 unmodified lines11211311411511611711811912019 unmodified lines1401411421431441451468 unmodified lines1551561571581591601611621631641657 unmodified lines17317417517617717817926 unmodified lines2062072082092102112122132142152162172182192205 unmodified lines2262272282292302312323 unmodified lines2362372382392402412424 unmodified lines247248249250251252573 unmodified lines82682782882983083183283381 unmodified lines9159169179189199209211 unmodified line92392492592692792822 unmodified lines95195295395495595695795895996096196296396496596615 unmodified lines982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102185 unmodified lines110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291 unmodified line113111321133113411351136113750 unmodified lines1188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512562 unmodified lines125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171 unmodified line131913201321132213231324132513261327132813291330133113321333133413351 unmodified line1337133813391340134113421343134413451346134713481349135013511352135313 unmodified lines13671368136913701371137213731 unmodified line137513761377137813791380138113821383138413852 unmodified lines13881389139013911392139313942 unmodified lines13971398139914001401140214031 unmodified line14051406140714081409141014111 unmodified line14131414141514161417141814191 unmodified line142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514462 unmodified lines144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472100 unmodified lines15731574157515761577157815791580158128 unmodified lines1610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016515 unmodified lines1657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168531 unmodified lines# Function to fetch Zero-GPU (CPU-based) Spaces from Huggingface with paginationdef fetch_trending_spaces(offset=0, limit=72):"""hardware=cpu ํ๋ผ๋ฏธํฐ๋ฅผ ์ถ๊ฐํ์ฌGPU๊ฐ ์๋(=CPU ์ ์ฉ) ์คํ์ด์ค๋ง ํํฐ๋ง"""try:url = "https://huggingface.co/api/spaces"53 unmodified lines'all_spaces': generate_dummy_spaces(500)}# Transform Huggingface URL to direct space URLdef transform_url(owner, name):"""13 unmodified lines# 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', ''):19 unmodified lines# Descriptionshort_desc = space_data.get('description', '')# User info (avatar, name)user_info = space_data.get('user', {})avatar_url = user_info.get('avatar_url', '')author_name = user_info.get('name') or 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',7 unmodified lines'rank': offset + index + 1}# Get owner statistics from all spacesdef get_owner_stats(all_spaces):"""์์ 500์(global_rank <= 500) ์ด๋ด์ ๋ฐฐ์น๋ ์คํ์ด์ค๋ค์ owner๋ฅผ ์ถ์ถํด,26 unmodified lines"""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', 72)) # Default 72# Fetch zero-gpu (cpu) spacesspaces_data = fetch_trending_spaces(offset, limit)5 unmodified linesif not space_info:continue# Apply search filter if neededif search_query:if (search_query not in space_info['title'].lower()and search_query not in space_info['owner'].lower()3 unmodified linesresults.append(space_info)# Get owner statistics (Top 500 โ Top 30)top_owners = get_owner_stats(spaces_data.get('all_spaces', []))return jsonify({4 unmodified lines'top_owners': top_owners})if __name__ == '__main__':"""์๋ฒ ๊ตฌ๋ ์, templates/index.html ํ์ผ์ ์์ฑ ํ Flask ์คํ573 unmodified lines}/* ์ถ๊ฐ ๋ ์ด์์ ์์ (์๋ฐํ, ZERO GPU ๋ฑ์ง ๋ฑ)์ ์ํด์๋ ํด๋์ค๋ค์ ์ผ๋ถ ์ถ๊ฐ/์์ ํด๋ ์ข์ง๋ง์์๋ ์ ์์ญ์์ ์ด๋ฏธ ์ถฉ๋ถํ ์ฒ๋ฆฌํ๋ฏ๋ก ์๋ต *//* ๋ค์ ๋ถ๋ถ์ Zero GPU Spaces์ฉ ์นด๋ ๊ตฌ์กฐ์์ ํ์ฉ */.space-header {81 unmodified lines<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>1 unmodified line<!-- Tab Navigation --><div class="tab-nav"><button id="tabTrendingButton" class="tab-button active">Trending</button><button id="tabFixedButton" class="tab-button">Picks</button></div>22 unmodified lines</div><div class="search-bar"><input type="text" id="searchInput" placeholder="Search by name, owner, or description..." /><button id="refreshButton" class="refresh-btn"><span class="refresh-icon"></span>Refresh</button></div><div id="gridContainer" class="grid-container"></div><div id="pagination" class="pagination"></div></div><!-- Fixed Tab Content (๊ธฐ์กด ์์ ์ ์ง) -->15 unmodified lines</div><script>// DOM Elementsconst elements = {gridContainer: document.getElementById('gridContainer'),loadingIndicator: document.getElementById('loadingIndicator'),loadingError: document.getElementById('loadingError'),searchInput: document.getElementById('searchInput'),refreshButton: document.getElementById('refreshButton'),pagination: document.getElementById('pagination'),statsToggle: document.getElementById('statsToggle'),statsContent: document.getElementById('statsContent'),creatorStatsChart: document.getElementById('creatorStatsChart')};const tabTrendingButton = document.getElementById('tabTrendingButton');const tabFixedButton = document.getElementById('tabFixedButton');const trendingTab = document.getElementById('trendingTab');const fixedTab = document.getElementById('fixedTab');const fixedGridContainer = document.getElementById('fixedGrid');const state = {isLoading: false,spaces: [],currentPage: 0,itemsPerPage: 72,totalItems: 0,loadingTimeout: null,staticModeAttempted: {},statsVisible: false,chartInstance: null,topOwners: [],iframeStatuses: {}};// Advanced iframe loader for better error detectionconst iframeLoader = {checkQueue: {},maxAttempts: 5,85 unmodified lines}};function toggleStats() {state.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();}const 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++) {1 unmodified linecolors.push(`hsla(${hue}, 70%, 80%, 0.7)`);}state.chartInstance = new Chart(ctx, {type: 'bar',data: {labels: labels,50 unmodified lines});}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}`);const response = await Promise.race([fetchPromise, timeoutPromise]);const data = await response.json();state.spaces = data.spaces;state.totalItems = data.total;state.currentPage = page;state.topOwners = data.top_owners || [];renderGrid(state.spaces);renderPagination();if (state.statsVisible && state.topOwners.length > 0) {renderCreatorStats();}} catch (error) {console.error('Error loading spaces:', error);elements.gridContainer.innerHTML = `<div style="grid-column: 1/-1; text-align: center; padding: 40px;"><div style="font-size: 3rem; margin-bottom: 20px;">โ ๏ธ</div><h3 style="margin-bottom: 10px;">Unable to load spaces</h3><p style="color: #666;">Please try refreshing the page. If the problem persists, try again later.</p><button id="retryButton" style="margin-top: 20px; padding: 10px 20px; background: var(--pastel-purple); border: none; border-radius: 5px; cursor: pointer;">Try Again</button></div>`;document.getElementById('retryButton')?.addEventListener('click', () => loadSpaces(0));renderPagination();} finally {setLoading(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) {2 unmodified linesfor (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';directLink.textContent = 'Visit HF Space';directLink.style.color = '#3182ce';directLink.style.marginTop = '10px';directLink.style.display = 'inline-block';directLink.style.padding = '8px 16px';directLink.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.';1 unmodified linenoResultsMsg.style.textAlign = 'center';noResultsMsg.style.fontStyle = 'italic';noResultsMsg.style.color = '#718096';elements.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';1 unmodified lineconst 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';13 unmodified linesspaceHeader.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');// โโโโโโโโโโโโโโ โ rankBadge2 ๋ถ๋ถ ์ ๊ฑฐ๋จconst authorSpan = document.createElement('span');authorSpan.className = 'author-name';authorSpan.style.marginLeft = '8px';2 unmodified linesmetaInfo.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';1 unmodified linegridItem.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', '');1 unmodified lineiframe.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);// actionsconst actions = document.createElement('div');actions.className = 'grid-actions';2 unmodified lineslinkEl.target = '_blank';linkEl.className = 'open-link';linkEl.textContent = 'Open in new window';actions.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 = [100 unmodified linesiframe.setAttribute('frameborder', '0');iframe.loading = 'lazy';const spaceKey = `${owner}/${name}`;iframe.onload = function() {iframeLoader.startChecking(iframe, owner, name, title, spaceKey);};iframe.onerror = function() {handleIframeError(iframe, owner, name, title);28 unmodified lines});}// Tab switchingtabTrendingButton.addEventListener('click', () => {tabTrendingButton.classList.add('active');tabFixedButton.classList.remove('active');trendingTab.classList.add('active');fixedTab.classList.remove('active');loadSpaces(state.currentPage);});tabFixedButton.addEventListener('click', () => {tabFixedButton.classList.add('active');tabTrendingButton.classList.remove('active');fixedTab.classList.add('active');trendingTab.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);}});elements.refreshButton.addEventListener('click', () => loadSpaces(0));elements.statsToggle.addEventListener('click', toggleStats);window.addEventListener('load', function() {setTimeout(() => loadSpaces(0), 500);});setTimeout(() => {if (state.isLoading) {setLoading(false);elements.gridContainer.innerHTML = `<div style="grid-column: 1/-1; text-align: center; padding: 40px;"><div style="font-size: 3rem; margin-bottom: 20px;">โฑ๏ธ</div><h3 style="margin-bottom: 10px;">Loading is taking longer than expected</h3>5 unmodified lines`;}}, 20000);loadSpaces(0);function setLoading(isLoading) {state.isLoading = isLoading;elements.loadingIndicator.style.display = isLoading ? 'flex' : 'none';if (isLoading) {elements.refreshButton.classList.add('refreshing');clearTimeout(state.loadingTimeout);state.loadingTimeout = setTimeout(() => {elements.loadingError.style.display = 'block';}, 10000);} else {elements.refreshButton.classList.remove('refreshing');clearTimeout(state.loadingTimeout);elements.loadingError.style.display = 'none';}}</script></body></html>''')# Flask ์ฑ ์คํ (ํฌํธ 7860)app.run(host='0.0.0.0', port=7860)31 unmodified lines3233343536373853 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016113 unmodified lines17517617717817918018118219 unmodified lines2022032042052062072088 unmodified lines2172182192202212222232242252262277 unmodified lines23523623723823924024126 unmodified lines2682692702712722732742752762772782792802812825 unmodified lines2882892902912922932943 unmodified lines2982993003013023033044 unmodified lines309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349573 unmodified lines92392492592692792892981 unmodified lines1011101210131014101510161 unmodified line101810191020102110221023102422 unmodified lines104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107715 unmodified lines1093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115785 unmodified lines124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861 unmodified line128812891290129112921293129450 unmodified lines13451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415552 unmodified lines155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461 unmodified line164816491650165116521653165416551656165716581659166016611662166316641665166616671 unmodified line1669167016711672167316741675167616771678167916801681168213 unmodified lines1696169716981699170017011 unmodified line17031704170517061707170817092 unmodified lines1712171317141715171617172 unmodified lines1720172117221723172417251 unmodified line1727172817291730173117321 unmodified line17341735173617371738173917401 unmodified line17421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517662 unmodified lines1769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841100 unmodified lines1942194319441945194619471948194928 unmodified lines19781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820595 unmodified lines20652066206720682069207020712072207331 unmodified lines# Function to fetch Zero-GPU (CPU-based) Spaces from Huggingface with paginationdef fetch_trending_spaces(offset=0, limit=72):"""Trending์ฉ CPU ์คํ์ด์ค ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ (์ ๋ ฌ์ Hugging Face ๊ธฐ๋ณธ ์ ๋ ฌ)"""try:url = "https://huggingface.co/api/spaces"53 unmodified lines'all_spaces': generate_dummy_spaces(500)}def fetch_latest_spaces(offset=0, limit=72):"""'createdAt' ๊ธฐ์ค ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ต๊ทผ ์คํ์ด์ค 500๊ฐ๋ฅผ ์ถ๋ฆฐ ๋ค,offset ~ offset+limit ๊ฐ๋ง ๋ฐํ"""try:url = "https://huggingface.co/api/spaces"params = {"limit": 10000, # ์ถฉ๋ถํ ๋ง์ด ๊ฐ์ ธ์ด"hardware": "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']# createdAt ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌ# createdAt ์: "2023-01-01T00:00:00.000Z"# ๋ฌธ์์ด ๋น๊ต๋ ๊ฐ๋ฅํ์ง๋ง, ์์ ์ฑ์ ์ํด time ํ์ฑ ํ ๋น๊ตํ ์๋ ์์def parse_time(sp):return sp.get('createdAt') or ''# ๋ด๋ฆผ์ฐจ์filtered_spaces.sort(key=parse_time, reverse=True)# ์์ 500๊ฐ๋ง ์ถ๋ฆฌ๊ธฐtruncated = filtered_spaces[:500]# ํ์ํ ๊ตฌ๊ฐ ์ฌ๋ผ์ด์ฑstart = min(offset, len(truncated))end = min(offset + limit, len(truncated))print(f"[fetch_latest_spaces] CPU๊ธฐ๋ฐ ์คํ์ด์ค ์ด {len(spaces)}๊ฐ ์ค ํํฐ ํ {len(filtered_spaces)}๊ฐ, ์์ 500๊ฐ ์ค {start}~{end-1} ๋ฐํ")return {'spaces': truncated[start:end],'total': len(truncated), # 500 ์ดํ'offset': offset,'limit': limit}else:print(f"Error fetching spaces: {response.status_code}")return {'spaces': generate_dummy_spaces(limit),'total': 500,'offset': offset,'limit': limit}except Exception as e:print(f"Exception when fetching spaces: {e}")return {'spaces': generate_dummy_spaces(limit),'total': 500,'offset': offset,'limit': limit}# Transform Huggingface URL to direct space URLdef transform_url(owner, name):"""13 unmodified lines# Get space detailsdef get_space_details(space_data, index, offset):"""์คํ์ด์ค ์์ธ ํ๋ ์ถ์ถ- rank๋ offset ๊ธฐ๋ฐ (ํ์ฌ ํ์ด์ง)"""try:if '/' in space_data.get('id', ''):19 unmodified lines# Descriptionshort_desc = space_data.get('description', '')# User infouser_info = space_data.get('user', {})avatar_url = user_info.get('avatar_url', '')author_name = user_info.get('name') or 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 {'url': 'https://huggingface.co/spaces','embedUrl': 'https://huggingface.co/spaces',7 unmodified lines'rank': offset + index + 1}# Get owner statistics from all spaces (for the "Trending" tab's top owners)def get_owner_stats(all_spaces):"""์์ 500์(global_rank <= 500) ์ด๋ด์ ๋ฐฐ์น๋ ์คํ์ด์ค๋ค์ owner๋ฅผ ์ถ์ถํด,26 unmodified lines"""return render_template('index.html')# Zero-GPU spaces API (Trending)@app.route('/api/trending-spaces', methods=['GET'])def trending_spaces():"""hardware=cpu ์คํ์ด์ค ๋ชฉ๋ก์ ๋ถ๋ฌ์ ๊ฒ์, ํ์ด์ง, ํต๊ณ ๋ฑ์ ์ ์ฉ (๊ธฐ์กด 'Trending')"""search_query = request.args.get('search', '').lower()offset = int(request.args.get('offset', 0))limit = int(request.args.get('limit', 72))# Fetch zero-gpu (cpu) spacesspaces_data = fetch_trending_spaces(offset, limit)5 unmodified linesif not space_info:continue# ๊ฒ์์ด ํํฐif search_query:if (search_query not in space_info['title'].lower()and search_query not in space_info['owner'].lower()3 unmodified linesresults.append(space_info)# ์ค๋ ํต๊ณ (Top 500 โ Top 30)top_owners = get_owner_stats(spaces_data.get('all_spaces', []))return jsonify({4 unmodified lines'top_owners': top_owners})# Zero-GPU spaces API (Latest Releases)@app.route('/api/latest-spaces', methods=['GET'])def latest_spaces():"""hardware=cpu ์คํ์ด์ค ์ค์์ createdAt ๊ธฐ์ค์ผ๋ก ์ต์ ์ 500๊ฐ๋ฅผ ํ์ด์ง, ๊ฒ์"""search_query = request.args.get('search', '').lower()offset = int(request.args.get('offset', 0))limit = int(request.args.get('limit', 72))spaces_data = fetch_latest_spaces(offset, limit)results = []for index, space_data in enumerate(spaces_data['spaces']):space_info = get_space_details(space_data, index, offset)if not space_info:continue# ๊ฒ์์ด ํํฐif search_query:if (search_query not in space_info['title'].lower()and search_query not in space_info['owner'].lower()and search_query not in space_info['url'].lower()and search_query not in space_info['description'].lower()):continueresults.append(space_info)return jsonify({'spaces': results,'total': spaces_data['total'],'offset': offset,'limit': limit})if __name__ == '__main__':"""์๋ฒ ๊ตฌ๋ ์, templates/index.html ํ์ผ์ ์์ฑ ํ Flask ์คํ573 unmodified lines}/* ์ถ๊ฐ ๋ ์ด์์ ์์ (์๋ฐํ, ZERO GPU ๋ฑ์ง ๋ฑ)์ ์ํด์๋ ํด๋์ค๋ค์ ์ผ๋ถ ์ถ๊ฐ/์์ ํ ์ ์์ผ๋ ์ฌ๊ธฐ์๋ ์๋ต *//* ๋ค์ ๋ถ๋ถ์ Zero GPU Spaces์ฉ ์นด๋ ๊ตฌ์กฐ์์ ํ์ฉ */.space-header {81 unmodified lines<div class="mac-content"><div class="header"><h1>ZeroGPU Spaces Leaderboard</h1><p>Discover Zero GPU(Shared A100) spaces from Hugging Face</p></div>1 unmodified line<!-- Tab Navigation --><div class="tab-nav"><button id="tabTrendingButton" class="tab-button active">Trending</button><button id="tabLatestButton" class="tab-button">Latest Releases</button><button id="tabFixedButton" class="tab-button">Picks</button></div>22 unmodified lines</div><div class="search-bar"><input type="text" id="searchInputTrending" placeholder="Search by name, owner, or description..." /><button id="refreshButtonTrending" class="refresh-btn"><span class="refresh-icon"></span>Refresh</button></div><div id="gridContainerTrending" class="grid-container"></div><div id="paginationTrending" class="pagination"></div></div><!-- Latest Releases Tab Content --><div id="latestTab" class="tab-content"><div class="search-bar"><input type="text" id="searchInputLatest" placeholder="Search by name, owner, or description..." /><button id="refreshButtonLatest" class="refresh-btn"><span class="refresh-icon"></span>Refresh</button></div><div id="gridContainerLatest" class="grid-container"></div><div id="paginationLatest" class="pagination"></div></div><!-- Fixed Tab Content (๊ธฐ์กด ์์ ์ ์ง) -->15 unmodified lines</div><script>// ------------------------------------// GLOBAL STATE & COMMON FUNCTIONS// ------------------------------------const globalState = {isLoading: false,loadingTimeout: null,};function setLoading(isLoading) {globalState.isLoading = isLoading;document.getElementById('loadingIndicator').style.display = isLoading ? 'flex' : 'none';const refreshButtons = document.querySelectorAll('.refresh-btn');refreshButtons.forEach(btn => {if (isLoading) {btn.classList.add('refreshing');} else {btn.classList.remove('refreshing');}});if (isLoading) {clearTimeout(globalState.loadingTimeout);globalState.loadingTimeout = setTimeout(() => {document.getElementById('loadingError').style.display = 'block';}, 10000);} else {clearTimeout(globalState.loadingTimeout);document.getElementById('loadingError').style.display = 'none';}}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';directLink.textContent = 'Visit HF Space';directLink.style.color = '#3182ce';directLink.style.marginTop = '10px';directLink.style.display = 'inline-block';directLink.style.padding = '8px 16px';directLink.style.background = '#ebf8ff';directLink.style.borderRadius = '5px';directLink.style.fontWeight = '600';errorPlaceholder.appendChild(directLink);iframe.style.display = 'none';container.appendChild(errorPlaceholder);}// ------------------------------------// IFRAME LOADER (๊ณตํต)// ------------------------------------const iframeLoader = {checkQueue: {},maxAttempts: 5,85 unmodified lines}};// ------------------------------------// TRENDING TAB// ------------------------------------const trendingState = {spaces: [],currentPage: 0,itemsPerPage: 72,totalItems: 0,topOwners: [],iframeStatuses: {}};const trendingElements = {searchInput: document.getElementById('searchInputTrending'),refreshButton: document.getElementById('refreshButtonTrending'),gridContainer: document.getElementById('gridContainerTrending'),pagination: document.getElementById('paginationTrending'),statsToggle: document.getElementById('statsToggle'),statsContent: document.getElementById('statsContent'),creatorStatsChart: document.getElementById('creatorStatsChart')};let chartInstance = null;trendingElements.statsToggle.addEventListener('click', () => {const isOpen = trendingElements.statsContent.classList.toggle('open');trendingElements.statsToggle.textContent = isOpen ? 'Hide Stats' : 'Show Stats';if (isOpen && trendingState.topOwners.length > 0) {renderCreatorStats(trendingState.topOwners);}});function renderCreatorStats(topOwners) {if (chartInstance) {chartInstance.destroy();}const ctx = trendingElements.creatorStatsChart.getContext('2d');const labels = topOwners.map(item => item[0]);const data = topOwners.map(item => item[1]);const colors = [];for (let i = 0; i < labels.length; i++) {1 unmodified linecolors.push(`hsla(${hue}, 70%, 80%, 0.7)`);}chartInstance = new Chart(ctx, {type: 'bar',data: {labels: labels,50 unmodified lines});}async function loadTrending(page=0) {setLoading(true);try {const searchText = trendingElements.searchInput.value;const offset = page * trendingState.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=${trendingState.itemsPerPage}`);const response = await Promise.race([fetchPromise, timeoutPromise]);const data = await response.json();trendingState.spaces = data.spaces || [];trendingState.totalItems = data.total || 0;trendingState.currentPage = page;trendingState.topOwners = data.top_owners || [];renderTrendingGrid(trendingState.spaces);renderTrendingPagination();// ํต๊ณ์ฐฝ ์ด๋ ค์๋ค๋ฉด ์ ๋ฐ์ดํฐ๋ก ๊ฐฑ์if (trendingElements.statsContent.classList.contains('open') && trendingState.topOwners.length > 0) {renderCreatorStats(trendingState.topOwners);}} catch (error) {console.error('Error loading trending spaces:', error);trendingElements.gridContainer.innerHTML = `<div style="grid-column: 1/-1; text-align: center; padding: 40px;"><div style="font-size: 3rem; margin-bottom: 20px;">โ ๏ธ</div><h3 style="margin-bottom: 10px;">Unable to load spaces (Trending)</h3><p style="color: #666;">Please try refreshing the page. If the problem persists, try again later.</p><button id="retryTrendingButton" style="margin-top: 20px; padding: 10px 20px; background: var(--pastel-purple); border: none; border-radius: 5px; cursor: pointer;">Try Again</button></div>`;document.getElementById('retryTrendingButton')?.addEventListener('click', () => loadTrending(0));renderTrendingPagination();} finally {setLoading(false);}}function renderTrendingGrid(spaces) {trendingElements.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';noResultsMsg.style.textAlign = 'center';noResultsMsg.style.fontStyle = 'italic';noResultsMsg.style.color = '#718096';trendingElements.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';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}`;trendingState.iframeStatuses[spaceKey] = 'loading';iframe.onload = function() {iframeLoader.startChecking(iframe, owner, name, title, spaceKey);};iframe.onerror = function() {handleIframeError(iframe, owner, name, title);trendingState.iframeStatuses[spaceKey] = 'error';};setTimeout(() => {if (trendingState.iframeStatuses[spaceKey] === 'loading') {handleIframeError(iframe, owner, name, title);trendingState.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);trendingElements.gridContainer.appendChild(gridItem);} catch (err) {console.error('Item rendering error:', err);}});}function renderTrendingPagination() {trendingElements.pagination.innerHTML = '';const totalPages = Math.ceil(trendingState.totalItems / trendingState.itemsPerPage);// Previous pageconst prevButton = document.createElement('button');prevButton.className = 'pagination-button';prevButton.textContent = 'Previous';prevButton.disabled = (trendingState.currentPage === 0);prevButton.addEventListener('click', () => {if (trendingState.currentPage > 0) {loadTrending(trendingState.currentPage - 1);}});trendingElements.pagination.appendChild(prevButton);const maxButtons = 7;let startPage = Math.max(0, trendingState.currentPage - Math.floor(maxButtons / 2));let endPage = Math.min(totalPages - 1, startPage + maxButtons - 1);if (endPage - startPage + 1 < maxButtons) {2 unmodified linesfor (let i = startPage; i <= endPage; i++) {const pageButton = document.createElement('button');pageButton.className = 'pagination-button' + (i === trendingState.currentPage ? ' active' : '');pageButton.textContent = (i + 1);pageButton.addEventListener('click', () => {if (i !== trendingState.currentPage) {loadTrending(i);}});trendingElements.pagination.appendChild(pageButton);}// Next pageconst nextButton = document.createElement('button');nextButton.className = 'pagination-button';nextButton.textContent = 'Next';nextButton.disabled = (trendingState.currentPage >= totalPages - 1);nextButton.addEventListener('click', () => {if (trendingState.currentPage < totalPages - 1) {loadTrending(trendingState.currentPage + 1);}});trendingElements.pagination.appendChild(nextButton);}// ------------------------------------// LATEST RELEASES TAB// ------------------------------------const latestState = {spaces: [],currentPage: 0,itemsPerPage: 72,totalItems: 0,iframeStatuses: {}};const latestElements = {searchInput: document.getElementById('searchInputLatest'),refreshButton: document.getElementById('refreshButtonLatest'),gridContainer: document.getElementById('gridContainerLatest'),pagination: document.getElementById('paginationLatest')};async function loadLatest(page=0) {setLoading(true);try {const searchText = latestElements.searchInput.value;const offset = page * latestState.itemsPerPage;const timeoutPromise = new Promise((_, reject) =>setTimeout(() => reject(new Error('Request timeout')), 30000));const fetchPromise = fetch(`/api/latest-spaces?search=${encodeURIComponent(searchText)}&offset=${offset}&limit=${latestState.itemsPerPage}`);const response = await Promise.race([fetchPromise, timeoutPromise]);const data = await response.json();latestState.spaces = data.spaces || [];latestState.totalItems = data.total || 0;latestState.currentPage = page;renderLatestGrid(latestState.spaces);renderLatestPagination();} catch (error) {console.error('Error loading latest spaces:', error);latestElements.gridContainer.innerHTML = `<div style="grid-column: 1/-1; text-align: center; padding: 40px;"><div style="font-size: 3rem; margin-bottom: 20px;">โ ๏ธ</div><h3 style="margin-bottom: 10px;">Unable to load spaces (Latest)</h3><p style="color: #666;">Please try refreshing the page. If the problem persists, try again later.</p><button id="retryLatestButton" style="margin-top: 20px; padding: 10px 20px; background: var(--pastel-purple); border: none; border-radius: 5px; cursor: pointer;">Try Again</button></div>`;document.getElementById('retryLatestButton')?.addEventListener('click', () => loadLatest(0));renderLatestPagination();} finally {setLoading(false);}}function renderLatestGrid(spaces) {latestElements.gridContainer.innerHTML = '';if (!spaces || spaces.length === 0) {const noResultsMsg = document.createElement('p');noResultsMsg.textContent = 'No zero-gpu spaces found matching your search.';1 unmodified linenoResultsMsg.style.textAlign = 'center';noResultsMsg.style.fontStyle = 'italic';noResultsMsg.style.color = '#718096';latestElements.gridContainer.appendChild(noResultsMsg);return;}spaces.forEach((item, index) => {try {const {url, title, likes_count, owner, name, rank,description, avatar_url, author_name, embedUrl} = item;// rank๊ฐ ์์ผ๋ฏ๋ก Latest ํญ์์๋ offset+index+1 ํํ๋ก ํ์const computedRank = latestState.currentPage * latestState.itemsPerPage + (index + 1);const gridItem = document.createElement('div');gridItem.className = 'grid-item';1 unmodified lineconst 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 = `#${computedRank}`;spaceHeader.appendChild(rankBadge);const titleWrapper = document.createElement('div');titleWrapper.style.display = 'flex';titleWrapper.style.alignItems = 'center';13 unmodified linesspaceHeader.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';2 unmodified linesmetaInfo.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';1 unmodified linegridItem.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', '');1 unmodified lineiframe.loading = 'lazy';const spaceKey = `${owner}/${name}`;latestState.iframeStatuses[spaceKey] = 'loading';iframe.onload = function() {iframeLoader.startChecking(iframe, owner, name, title, spaceKey);};iframe.onerror = function() {handleIframeError(iframe, owner, name, title);latestState.iframeStatuses[spaceKey] = 'error';};setTimeout(() => {if (latestState.iframeStatuses[spaceKey] === 'loading') {handleIframeError(iframe, owner, name, title);latestState.iframeStatuses[spaceKey] = 'error';}}, 30000);iframeContainer.appendChild(iframe);content.appendChild(iframeContainer);const actions = document.createElement('div');actions.className = 'grid-actions';2 unmodified lineslinkEl.target = '_blank';linkEl.className = 'open-link';linkEl.textContent = 'Open in new window';actions.appendChild(linkEl);gridItem.appendChild(content);gridItem.appendChild(actions);latestElements.gridContainer.appendChild(gridItem);} catch (err) {console.error('Item rendering error (Latest):', err);}});}function renderLatestPagination() {latestElements.pagination.innerHTML = '';const totalPages = Math.ceil(latestState.totalItems / latestState.itemsPerPage);// Previous pageconst prevButton = document.createElement('button');prevButton.className = 'pagination-button';prevButton.textContent = 'Previous';prevButton.disabled = (latestState.currentPage === 0);prevButton.addEventListener('click', () => {if (latestState.currentPage > 0) {loadLatest(latestState.currentPage - 1);}});latestElements.pagination.appendChild(prevButton);const maxButtons = 7;let startPage = Math.max(0, latestState.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 === latestState.currentPage ? ' active' : '');pageButton.textContent = (i + 1);pageButton.addEventListener('click', () => {if (i !== latestState.currentPage) {loadLatest(i);}});latestElements.pagination.appendChild(pageButton);}// Next pageconst nextButton = document.createElement('button');nextButton.className = 'pagination-button';nextButton.textContent = 'Next';nextButton.disabled = (latestState.currentPage >= totalPages - 1);nextButton.addEventListener('click', () => {if (latestState.currentPage < totalPages - 1) {loadLatest(latestState.currentPage + 1);}});latestElements.pagination.appendChild(nextButton);}// ------------------------------------// FIXED TAB// ------------------------------------const fixedGridContainer = document.getElementById('fixedGrid');function renderFixedGrid() {fixedGridContainer.innerHTML = '';const staticSpaces = [100 unmodified linesiframe.setAttribute('frameborder', '0');iframe.loading = 'lazy';iframe.onload = function() {iframeLoader.startChecking(iframe, owner, name, title, `${owner}/${name}`);};iframe.onerror = function() {handleIframeError(iframe, owner, name, title);28 unmodified lines});}// ------------------------------------// TAB HANDLERS// ------------------------------------const tabTrendingButton = document.getElementById('tabTrendingButton');const tabLatestButton = document.getElementById('tabLatestButton');const tabFixedButton = document.getElementById('tabFixedButton');const trendingTab = document.getElementById('trendingTab');const latestTab = document.getElementById('latestTab');const fixedTab = document.getElementById('fixedTab');tabTrendingButton.addEventListener('click', () => {tabTrendingButton.classList.add('active');tabLatestButton.classList.remove('active');tabFixedButton.classList.remove('active');trendingTab.classList.add('active');latestTab.classList.remove('active');fixedTab.classList.remove('active');loadTrending(trendingState.currentPage);});tabLatestButton.addEventListener('click', () => {tabLatestButton.classList.add('active');tabTrendingButton.classList.remove('active');tabFixedButton.classList.remove('active');latestTab.classList.add('active');trendingTab.classList.remove('active');fixedTab.classList.remove('active');loadLatest(latestState.currentPage);});tabFixedButton.addEventListener('click', () => {tabFixedButton.classList.add('active');tabTrendingButton.classList.remove('active');tabLatestButton.classList.remove('active');fixedTab.classList.add('active');trendingTab.classList.remove('active');latestTab.classList.remove('active');renderFixedGrid();});// ------------------------------------// EVENT LISTENERS// ------------------------------------trendingElements.searchInput.addEventListener('input', () => {clearTimeout(trendingState.searchTimeout);trendingState.searchTimeout = setTimeout(() => loadTrending(0), 300);});trendingElements.searchInput.addEventListener('keyup', (event) => {if (event.key === 'Enter') {loadTrending(0);}});trendingElements.refreshButton.addEventListener('click', () => loadTrending(0));latestElements.searchInput.addEventListener('input', () => {clearTimeout(latestState.searchTimeout);latestState.searchTimeout = setTimeout(() => loadLatest(0), 300);});latestElements.searchInput.addEventListener('keyup', (event) => {if (event.key === 'Enter') {loadLatest(0);}});latestElements.refreshButton.addEventListener('click', () => loadLatest(0));window.addEventListener('load', function() {// ์ฒซ ์ง์ ์ Trending ํญ ๋จผ์ ๋ก๋setTimeout(() => loadTrending(0), 500);});setTimeout(() => {if (globalState.isLoading) {setLoading(false);// ํ์์์ ์ ๋ฉ์์ง ํ์trendingElements.gridContainer.innerHTML = `<div style="grid-column: 1/-1; text-align: center; padding: 40px;"><div style="font-size: 3rem; margin-bottom: 20px;">โฑ๏ธ</div><h3 style="margin-bottom: 10px;">Loading is taking longer than expected</h3>5 unmodified lines`;}}, 20000);</script></body></html>''')app.run(host='0.0.0.0', port=7860)
app.py+575-187