ginipick's picture
Update app.py
b9f48c0 verified
raw
history blame
3.46 kB
import requests
import concurrent.futures
from flask import Flask, render_template_string
from typing import List, Dict, Union
import base64
app = Flask(__name__)
def get_most_liked_spaces(limit: int = 100) -> Union[List[Dict], str]:
url = "https://huggingface.co/api/spaces"
params = {
"sort": "likes",
"direction": -1,
"limit": limit,
"full": "true"
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
if isinstance(data, list):
return data
else:
return f"Unexpected API response format: {type(data)}"
except requests.RequestException as e:
return f"API request error: {str(e)}"
except ValueError as e:
return f"JSON decoding error: {str(e)}"
def capture_thumbnail(space_id: str) -> str:
screenshot_url = f"https://huggingface.co/spaces/{space_id}/screenshot.jpg"
try:
response = requests.get(screenshot_url)
if response.status_code == 200:
return base64.b64encode(response.content).decode('utf-8')
except requests.RequestException:
pass
return ""
def format_space(space: Dict) -> Dict:
space_id = space.get('id', 'Unknown')
space_name = space_id.split('/')[-1] if '/' in space_id else space_id
space_author = space.get('author', 'Unknown')
if isinstance(space_author, dict):
space_author = space_author.get('user', space_author.get('name', 'Unknown'))
space_likes = space.get('likes', 'N/A')
space_url = f"https://huggingface.co/spaces/{space_id}"
thumbnail = capture_thumbnail(space_id)
return {
"name": space_name,
"author": space_author,
"likes": space_likes,
"url": space_url,
"thumbnail": thumbnail
}
def format_spaces(spaces: Union[List[Dict], str]) -> List[Dict]:
if isinstance(spaces, str):
return [{"error": spaces}]
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
return list(executor.map(format_space, spaces))
@app.route('/')
def index():
spaces_list = get_most_liked_spaces()
formatted_spaces = format_spaces(spaces_list)
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hugging Face Most Liked Spaces</title>
<style>
body { font-family: Arial, sans-serif; }
.space-item { margin-bottom: 20px; }
.space-item img { max-width: 200px; max-height: 200px; }
</style>
</head>
<body>
<h1>Hugging Face Most Liked Spaces</h1>
<ol>
{% for space in spaces %}
<li class="space-item">
<a href="{{ space.url }}" target="_blank">
{{ space.name }} by {{ space.author }} (Likes: {{ space.likes }})
</a>
{% if space.thumbnail %}
<br>
<img src="data:image/jpeg;base64,{{ space.thumbnail }}" alt="{{ space.name }} thumbnail">
{% endif %}
</li>
{% endfor %}
</ol>
</body>
</html>
"""
return render_template_string(html_template, spaces=formatted_spaces)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=7860)