spaces-research-think / app-backup4.py
ginipick's picture
Rename app.py to app-backup4.py
cdde9f2 verified
raw
history blame
6.84 kB
import gradio as gr
from huggingface_hub import InferenceClient
import os
import requests
from typing import List, Dict, Union
import concurrent.futures
import base64
import traceback
# ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ ํ† ํฐ ๊ฐ€์ ธ์˜ค๊ธฐ
HF_TOKEN = os.getenv("HF_TOKEN")
# ์ถ”๋ก  API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=HF_TOKEN)
def get_headers():
if not HF_TOKEN:
raise ValueError("Hugging Face token not found in environment variables")
return {"Authorization": f"Bearer {HF_TOKEN}"}
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, headers=get_headers())
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, headers=get_headers())
if response.status_code == 200:
return base64.b64encode(response.content).decode('utf-8')
except requests.RequestException:
pass
return ""
def get_app_py_content(space_id: str) -> str:
app_py_url = f"https://huggingface.co/spaces/{space_id}/raw/main/app.py"
try:
response = requests.get(app_py_url, headers=get_headers())
if response.status_code == 200:
return response.text
else:
return f"app.py file not found or inaccessible for space: {space_id}"
except requests.RequestException:
return f"Error fetching app.py content for space: {space_id}"
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 {
"id": space_id,
"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))
def summarize_space(space: Dict) -> str:
system_message = "๋‹น์‹ ์€ Hugging Face Space์˜ ๋‚ด์šฉ์„ ์š”์•ฝํ•˜๋Š” AI ์กฐ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ณ  ๋ช…ํ™•ํ•œ ์š”์•ฝ์„ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”."
user_message = f"๋‹ค์Œ Hugging Face Space๋ฅผ ์š”์•ฝํ•ด์ฃผ์„ธ์š”: {space['name']} by {space['author']}. ์ข‹์•„์š” ์ˆ˜: {space['likes']}. URL: {space['url']}"
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message}
]
response = hf_client.chat_completion(messages, max_tokens=150, temperature=0.7)
return response.choices[0].message.content
def create_ui():
spaces_list = get_most_liked_spaces()
formatted_spaces = format_spaces(spaces_list)
print(f"Total spaces loaded: {len(formatted_spaces)}") # ๋””๋ฒ„๊น… ์ถœ๋ ฅ
space_choices = {f"{space['name']} by {space['author']} (Likes: {space['likes']})": space['id'] for space in formatted_spaces}
with gr.Blocks() as demo:
gr.Markdown("# Hugging Face Most Liked Spaces")
with gr.Row():
with gr.Column(scale=1):
space_radio = gr.Radio(
choices=list(space_choices.keys()),
label="Select a Space"
)
summarize_btn = gr.Button("์š”์•ฝ")
with gr.Column(scale=2):
output = gr.Textbox(label="Space ์ •๋ณด", lines=10)
app_py_content = gr.Code(language="python", label="app.py ๋‚ด์šฉ")
def on_select(choice):
try:
print(f"Selected: {choice}") # ๋””๋ฒ„๊น… ์ถœ๋ ฅ
selected_id = space_choices[choice]
selected_space = next((space for space in formatted_spaces if space['id'] == selected_id), None)
if selected_space:
app_content = get_app_py_content(selected_id)
print(f"Selected space: {selected_space['name']} (ID: {selected_id})") # ๋””๋ฒ„๊น… ์ถœ๋ ฅ
return f"์„ ํƒ๋œ Space: {selected_space['name']} (ID: {selected_id})\nURL: {selected_space['url']}", app_content
else:
print(f"Space not found for ID: {selected_id}") # ๋””๋ฒ„๊น… ์ถœ๋ ฅ
return "์„ ํƒ๋œ space๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", ""
except Exception as e:
print(f"Error in on_select: {str(e)}")
print(traceback.format_exc()) # ์ƒ์„ธํ•œ ์˜ค๋ฅ˜ ์ •๋ณด ์ถœ๋ ฅ
return f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}", ""
def on_summarize(choice):
try:
if choice:
selected_id = space_choices[choice]
selected_space = next((space for space in formatted_spaces if space['id'] == selected_id), None)
if selected_space:
summary = summarize_space(selected_space)
print(f"Summarizing space: {selected_space['name']}") # ๋””๋ฒ„๊น… ์ถœ๋ ฅ
return summary
print("No space selected for summarization") # ๋””๋ฒ„๊น… ์ถœ๋ ฅ
return "์„ ํƒ๋œ space๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋จผ์ € ๋ฆฌ์ŠคํŠธ์—์„œ space๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”."
except Exception as e:
print(f"Error in on_summarize: {str(e)}")
print(traceback.format_exc()) # ์ƒ์„ธํ•œ ์˜ค๋ฅ˜ ์ •๋ณด ์ถœ๋ ฅ
return f"์š”์•ฝ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
space_radio.change(on_select, space_radio, [output, app_py_content])
summarize_btn.click(on_summarize, space_radio, output)
return demo
if __name__ == "__main__":
demo = create_ui()
demo.launch()