Spaces:
Running
Running
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 = """ | |
<script src="https://cdn.tailwindcss.com"></script> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> | |
<link rel="preconnect" href="https://fonts.googleapis.com"> | |
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&display=swap" rel="stylesheet"> | |
<style> | |
body, .gradio-container { | |
font-family: 'Fira Code', monospace !important; | |
background: linear-gradient(135deg, #0a0a1a 0%, #0d1128 100%) !important; | |
} | |
footer {visibility: hidden} | |
@keyframes scanline { 0% { background-position: 0 0; } 100% { background-position: 0 100vh; } } | |
@keyframes glitch { 0%{text-shadow:.05em 0 0 #00fffc,-.05em -.025em 0 #fc00ff}14%{text-shadow:.05em 0 0 #00fffc,-.05em -.025em 0 #fc00ff}15%{text-shadow:-.05em -.025em 0 #00fffc,.025em .025em 0 #fc00ff}49%{text-shadow:-.05em -.025em 0 #00fffc,.025em .025em 0 #fc00ff}50%{text-shadow:.025em .05em 0 #00fffc,.05em 0 0 #fc00ff}99%{text-shadow:.025em .05em 0 #00fffc,.05em 0 0 #fc00ff}100%{text-shadow:-.025em 0 0 #00fffc,-.025em -.025em 0 #fc00ff} } | |
@keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } } | |
@keyframes circuit { 0% { stroke-dashoffset: 1000; } 100% { stroke-dashoffset: 0; } } | |
.like-animation { animation: pulse 0.5s ease-in-out; } | |
.holo-card { transition: all 0.3s ease; box-shadow: 0 0 20px rgba(0, 255, 252, 0.3); border: 1px solid rgba(0, 255, 252, 0.2); background: rgba(5, 5, 15, 0.75) !important; backdrop-filter: blur(10px); position: relative; overflow: hidden; border-radius: 16px; } | |
.holo-card:hover { transform: translateY(-10px) scale(1.02); box-shadow: 0 0 30px rgba(0, 255, 252, 0.6), 0 0 50px rgba(255, 0, 255, 0.4); border-color: rgba(255, 0, 255, 0.6); } | |
.holo-card:hover .card-image { transform: scale(1.05); } | |
.card-image { transition: transform 0.5s ease; } | |
.header-glow { color: #00fffc; text-shadow: 0 0 5px #00fffc, 0 0 10px #00fffc, 0 0 20px #00fffc; animation: glitch 3s infinite; } | |
.grid-overlay { background-image: linear-gradient(rgba(0, 255, 252, 0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(0, 255, 252, 0.1) 1px, transparent 1px); background-size: 50px 50px; } | |
.circuit-border { position: absolute; top: 0; left: 0; width: 100%; height: 100%; stroke: rgba(0, 255, 252, 0.3); stroke-width: 2; stroke-dasharray: 1000; stroke-dashoffset: 1000; animation: circuit 10s linear infinite; fill: none; pointer-events: none; } | |
/* --- Custom text-color-300 styles for used colors --- */ | |
.text-blue-300 { color: #93c5fd !important; } | |
.text-green-300 { color: #86efac !important; } | |
.text-red-300 { color: #fca5a5 !important; } | |
.text-yellow-300 { color: #fde68a !important; } | |
.text-purple-300 { color: #c4b5fd !important; } | |
.text-pink-300 { color: #f9a8d4 !important; } | |
.text-indigo-300 { color: #a5b4fc !important; } | |
.text-teal-300 { color: #5eead4 !important; } | |
.text-cyan-300 { color: #67e8f9 !important; } | |
.text-gray-300 { color: #d1d5db !important; } | |
.text-red-500 { color: #ef4444 !important; } | |
.mb-4 { margin-bottom: 1rem !important;} | |
</style> | |
""" | |
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""" | |
<div class="holo-card rounded-xl overflow-hidden"> | |
<div class="relative overflow-hidden"> | |
<a href="{screenshot["link"]}" target="_blank" rel="noopener noreferrer" class="z-20"> | |
<img src="{screenshot["image"]}" alt="{screenshot["title"]}" class="w-full h-full object-cover card-image" style="object-fit: cover !important;" loading="lazy" decoding="async"> | |
</a> | |
<div class="absolute top-4 right-4 bg-black/70 rounded-full px-3 py-1 flex items-center text-xs border text-{color}-300/30"> | |
<i class="fas fa-calendar-alt text-{color}-300 mr-2"></i> | |
<span>{screenshot["date"]}</span> | |
</div> | |
</div> | |
<div class="p-5 relative z-10"> | |
<div class="flex justify-between items-center mb-3"> | |
<h3 class="text-xl font-semibold text-{color}-300 truncate" title="{screenshot["title"]}">{screenshot["title"]}</h3> | |
<button class="like-btn bg-transparent border-none cursor-pointer transition-transform flex items-center gap-2 group" onclick="likePost(this)"> | |
<i class="fas fa-heart text-red-500"></i> | |
<span class="like-count text-sm text-gray-300">{screenshot["likeCount"]}</span> | |
</button> | |
</div> | |
<p class="text-gray-300 mb-4 text-sm">{screenshot["description"]}</p> | |
<div class="flex justify-between items-center text-xs"> | |
<div class="flex items-center gap-2 text-{color}-300"> | |
<img src="{screenshot["user_avatar"]}" alt="avatar" class="w-6 h-6 rounded-full border border-{color}-300" style="display:inline-block;"> | |
<a href="{screenshot["user_link"]}" target="_blank" rel="noopener noreferrer" class="font-semibold text-{color}-300 hover:underline">Forged by {screenshot["user"]}</a> | |
</div> | |
</div> | |
</div> | |
<svg class="circuit-border" viewBox="0 0 100 100" preserveAspectRatio="none"><path d="M0,0 L100,0 L100,100 L0,100 Z" /></svg> | |
</div> | |
""" | |
return gallery_html | |
# --- GRADIO APP DEFINITION --- | |
# The main HTML structure of the page, with a placeholder for our dynamic gallery. | |
main_html_template = """ | |
<body class="min-h-screen text-white relative overflow-x-hidden"> | |
<!--div class="absolute inset-0 -z-10 overflow-hidden"> | |
<div class="absolute inset-0 grid-overlay opacity-40" style="animation: scanline 15s linear infinite; mix-blend-mode: overlay;"></div> | |
<div class="absolute inset-0 opacity-20" style="background: radial-gradient(circle at 20% 30%, rgba(150, 0, 200, 0.6), transparent 30%), radial-gradient(circle at 80% 70%, rgba(0, 150, 200, 0.6), transparent 30%);"></div> | |
</div--> | |
<div class="relative"> | |
<div class="container mx-auto px-4 py-8"> | |
<header class="text-center mb-12"> | |
<div class="relative inline-block"> | |
<h1 class="text-5xl md:text-7xl font-bold mb-4 header-glow tracking-widest">DeepSite Gallery</h1> | |
<p class="text-center text-lg text-blue-300/80 mb-10 mx-auto">Upload a screenshot to join: {{username}}---{{spacename}}.png (1200 x 800).</p> | |
</div> | |
<!-- --- HEADER ENHANCEMENT --- | |
<div class="flex flex-wrap justify-center items-center gap-4"> | |
<div class="flex items-center gap-2 bg-black/50 border border-blue-500/50 rounded-full px-4 py-2 text-sm hover:bg-blue-900/50 hover:shadow-[0_0_15px_rgba(0,150,255,0.6)] transition-all duration-300"> | |
<i class="fas fa-trophy text-yellow-300"></i> | |
<span class="font-bold text-gray-200">Featured Streams</span> | |
<span class="text-xs bg-yellow-400/20 text-yellow-300 rounded-full px-2 py-0.5">16</span> | |
</div> | |
<div class="flex items-center gap-2 bg-black/50 border border-purple-500/50 rounded-full px-4 py-2 text-sm hover:bg-purple-900/50 hover:shadow-[0_0_15px_rgba(200,50,255,0.6)] transition-all duration-300"> | |
<i class="fas fa-fire text-orange-400"></i> | |
<span class="font-bold text-gray-200">Trending Now</span> | |
<span class="text-xs bg-orange-400/20 text-orange-300 rounded-full px-2 py-0.5">99+</span> | |
</div> | |
<div class="flex items-center gap-2 bg-black/50 border border-green-500/50 rounded-full px-4 py-2 text-sm hover:bg-green-900/50 hover:shadow-[0_0_15px_rgba(50,255,150,0.6)] transition-all duration-300"> | |
<i class="fas fa-bolt text-green-300"></i> | |
<span class="font-bold text-gray-200">New Arrivals</span> | |
<span class="text-xs bg-green-400/20 text-green-300 rounded-full px-2 py-0.5 animate-pulse">LIVE</span> | |
</div> | |
</div>--> | |
</header> | |
<!-- DYNAMIC GALLERY WILL BE INSERTED HERE BY GRADIO --> | |
<div id="gallery" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8"> | |
{gallery_placeholder} | |
</div> | |
</div> | |
</div> | |
<!-- JAVASCRIPT FOR INTERACTIVITY --> | |
<script> | |
function likePost(button) {{ | |
if (button.classList.contains('liked')) return; // Prevent multiple clicks | |
button.classList.add('like-animation', 'liked'); | |
const countSpan = button.querySelector('.like-count'); | |
let currentCount = parseInt(countSpan.textContent, 10); | |
countSpan.textContent = currentCount + 1; | |
setTimeout(() => {{ button.classList.remove('like-animation'); }}, 500); | |
}} | |
</script> | |
</body> | |
""" | |
# The function that Gradio will call to update the UI | |
def update_ui(): | |
gallery_content = generate_gallery_html() | |
return main_html_template.format(gallery_placeholder=gallery_content) | |
with gr.Blocks(head=head_html, fill_height=True, theme=gr.themes.Base()) as demo: | |
# We only need one component to render the entire page | |
main_page = gr.HTML() | |
# Load the content when the app starts | |
demo.load(fn=update_ui, inputs=None, outputs=main_page) | |
if __name__ == "__main__": | |
demo.launch() |