import gradio as gr import os from datetime import datetime, timezone from time import sleep import math from huggingface_hub import HfApi import threading import requests from bs4 import BeautifulSoup api = HfApi() screenshots = [] screenshots_folder = "screenshots" def calculate_trending_score(total_likes: int, age_seconds: int) -> float: age_in_hours = age_seconds / 3600.0 DECAY_EXPONENT = 1.8 BASE_TIME_HOURS = 2.0 effective_age_for_decay = max(1.0, age_in_hours + BASE_TIME_HOURS) likes_score = math.log10(max(1, total_likes + 1)) trending_score = likes_score / (effective_age_for_decay ** DECAY_EXPONENT) return trending_score def load_screenshots(): global screenshots for filename in os.listdir(screenshots_folder): file_path = os.path.join(screenshots_folder, filename) name_part = os.path.splitext(filename)[0] # Split on the first hyphen to separate owner/repo parts = name_part.split("---", 1) if len(parts) == 2 and parts[0] and parts[1]: username = parts[0] spacename = parts[1] link = f"https://huggingface.co/spaces/{username}/{spacename}" try: space_info = api.space_info(f"{username}/{spacename}") print(f"Link: {link}", space_info.likes, space_info.created_at, space_info.card_data.title, space_info.card_data.get("short_description", "")) screenshots.append({"link": link, "username": username, "spacename": spacename, "image": f"https://huggingface.co/spaces/Arial311/DeepSite-Gallery/resolve/main/screenshots/{filename}"}) except Exception as e: print(f"### No space found", filename, e) os.remove(file_path) continue load_screenshots() def get_user_link(username): hf_user_link = f"https://huggingface.co/{username}" try: response = requests.get(hf_user_link) if response.status_code == 200: soup = BeautifulSoup(response.text, "html.parser") nofollow_link_tag = soup.find('a', attrs={'rel': 'nofollow'}) if nofollow_link_tag: first_nofollow_link = nofollow_link_tag.get('href') return first_nofollow_link except Exception as e: print(f"### User link error", username, e) return hf_user_link def update_screenshot_info(): print("--- Updating Screenshots Meta ---") global screenshots new_screenshots = screenshots.copy() color_list = ["blue", "green", "red", "yellow", "purple", "pink", "indigo", "teal", "cyan"] for i, screenshot in enumerate(new_screenshots): try: space_info = api.space_info(f"{screenshot['username']}/{screenshot['spacename']}") user_info = api.get_user_overview(space_info.author) user_link = get_user_link(space_info.author) avatar_url = user_info.avatar_url if user_info.avatar_url.startswith("http") else "https://huggingface.co" + user_info.avatar_url new_screenshots[i].update({ "likeCount": f"{space_info.likes}", "date": space_info.created_at.strftime("%Y-%m-%d"), "title": space_info.card_data.title if space_info.card_data.title else screenshot["spacename"], "description": space_info.card_data.get("short_description", ""), "user": user_info.fullname, "user_avatar": avatar_url, "user_link": user_link, "color": color_list[i % len(color_list)], "rate": calculate_trending_score(space_info.likes, (datetime.now(timezone.utc) - space_info.created_at).total_seconds()) }) print("Updated:", new_screenshots[i]["user"], new_screenshots[i]["user_link"]) except Exception as e: print(f"### No space found during update", screenshot, e) continue screenshots = sorted(new_screenshots, key=lambda x: x.get("rate", 0), reverse=True) print("--- Updating Screenshots Meta Done ---") update_screenshot_info() def update_screenshots(): while True: sleep(600) update_screenshot_info() update_screenshots_thread = threading.Thread(target=update_screenshots, daemon=True) update_screenshots_thread.start() head_html = """ """ def generate_gallery_html(): """Scans the screenshots folder and generates the HTML for the image cards.""" print("--- Refreshing Screenshots Gallery ---") global screenshots gallery_html = "" for screenshot in screenshots: color = screenshot.get("color", "blue") gallery_html += f"""
Upload a screenshot to join: {{username}}---{{spacename}}.png (1200 x 800).