Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,128 +1,143 @@
|
|
1 |
-
import
|
2 |
-
import logging
|
3 |
-
import os
|
4 |
-
from huggingface_hub import InferenceClient
|
5 |
import requests
|
6 |
-
import
|
7 |
-
import
|
8 |
-
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
# Set Pixabay API key
|
14 |
-
os.environ['PIXABAY_API_KEY'] = "33492762-a28a596ec4f286f84cd328b17"
|
15 |
-
|
16 |
-
# Logging setup
|
17 |
-
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', handlers=[logging.StreamHandler()])
|
18 |
-
|
19 |
-
# Intent setup
|
20 |
-
intents = discord.Intents.default()
|
21 |
-
intents.message_content = True
|
22 |
-
intents.messages = True
|
23 |
-
intents.guilds = True
|
24 |
-
intents.guild_messages = True
|
25 |
-
|
26 |
-
# Inference API client setup
|
27 |
-
hf_client = InferenceClient("meta-llama/Meta-Llama-3.1-70B-Instruct", token=os.getenv("HF_TOKEN"))
|
28 |
-
|
29 |
-
# Pixabay API setup
|
30 |
-
PIXABAY_API_KEY = os.getenv("PIXABAY_API_KEY")
|
31 |
-
PIXABAY_API_URL = "https://pixabay.com/api/videos/"
|
32 |
-
|
33 |
-
# Specific channel ID
|
34 |
-
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
|
35 |
-
|
36 |
-
# Global variable to store conversation history
|
37 |
-
conversation_history = []
|
38 |
-
|
39 |
-
class MyClient(discord.Client):
|
40 |
-
def __init__(self, *args, **kwargs):
|
41 |
-
super().__init__(*args, **kwargs)
|
42 |
-
self.is_processing = False
|
43 |
-
|
44 |
-
async def on_ready(self):
|
45 |
-
logging.info(f'{self.user}๋ก ๋ก๊ทธ์ธ๋์์ต๋๋ค!')
|
46 |
-
subprocess.Popen(["python", "web.py"])
|
47 |
-
logging.info("Web.py server has been started.")
|
48 |
-
|
49 |
-
# Send a guide message when the bot starts
|
50 |
-
channel = self.get_channel(SPECIFIC_CHANNEL_ID)
|
51 |
-
if channel:
|
52 |
-
await channel.send("์ฐพ๊ณ ์ถ์ ๋น๋์ค์ ๋ํ ์ค๋ช
์ ํ ๋ฌธ์ฅ ๋จ์๋ก ์
๋ ฅํ์ธ์. ์) ๋ฐ๋ค์์ ์ํํ๋ ์ฌ๋")
|
53 |
-
|
54 |
-
async def on_message(self, message):
|
55 |
-
if message.author == self.user:
|
56 |
-
return
|
57 |
-
if not self.is_message_in_specific_channel(message):
|
58 |
-
return
|
59 |
-
if self.is_processing:
|
60 |
-
return
|
61 |
-
self.is_processing = True
|
62 |
-
try:
|
63 |
-
# Extract English keywords from the meaning analysis
|
64 |
-
keywords = await extract_keywords(message)
|
65 |
-
if keywords:
|
66 |
-
# Search for videos using Pixabay API
|
67 |
-
video_urls = await search_videos(keywords)
|
68 |
-
if video_urls:
|
69 |
-
# Create a thread with the requester and send video links
|
70 |
-
await create_thread_and_send_videos(message, keywords, video_urls)
|
71 |
-
else:
|
72 |
-
await message.channel.send(f"**{keywords}**์ ๋ํ ๋น๋์ค๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.")
|
73 |
-
else:
|
74 |
-
await message.channel.send("ํค์๋๋ฅผ ์ถ์ถํ ์ ์์ต๋๋ค.")
|
75 |
-
finally:
|
76 |
-
self.is_processing = False
|
77 |
-
|
78 |
-
def is_message_in_specific_channel(self, message):
|
79 |
-
# Return True if the message is in the specified channel or in a thread of that channel
|
80 |
-
return message.channel.id == SPECIFIC_CHANNEL_ID or (
|
81 |
-
isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
|
82 |
-
)
|
83 |
-
|
84 |
-
async def extract_keywords(message):
|
85 |
-
user_input = message.content
|
86 |
-
system_prompt = "๋ค์ ๋ฌธ์ฅ์ ์๋ฏธ์ ๋ง๋ ์๋ฌธ ํค์๋๋ฅผ ์ถ์ถํ์ธ์: "
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
}
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
if __name__ == "__main__":
|
127 |
-
|
128 |
-
discord_client.run(os.getenv('DISCORD_TOKEN'))
|
|
|
1 |
+
import gradio as gr
|
|
|
|
|
|
|
2 |
import requests
|
3 |
+
from datetime import datetime, timedelta
|
4 |
+
import pandas as pd
|
5 |
+
import plotly.express as px
|
6 |
|
7 |
+
def get_user_spaces(token):
|
8 |
+
"""์ฌ์ฉ์์ ๋ชจ๋ Space ๋ชฉ๋ก์ ๊ฐ์ ธ์ต๋๋ค."""
|
9 |
+
headers = {"Authorization": f"Bearer {token}"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
try:
|
12 |
+
# ์ฌ์ฉ์ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ
|
13 |
+
user_info = requests.get("https://huggingface.co/api/whoami", headers=headers)
|
14 |
+
user_info.raise_for_status()
|
15 |
+
username = user_info.json().get('name')
|
16 |
+
|
17 |
+
if not username:
|
18 |
+
return None, "์ฌ์ฉ์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค."
|
19 |
+
|
20 |
+
# ์ฌ์ฉ์์ Space ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ
|
21 |
+
spaces_url = f"https://huggingface.co/api/spaces/{username}"
|
22 |
+
spaces_response = requests.get(spaces_url, headers=headers)
|
23 |
+
spaces_response.raise_for_status()
|
24 |
+
|
25 |
+
return username, spaces_response.json()
|
26 |
+
|
27 |
+
except requests.exceptions.RequestException as e:
|
28 |
+
return None, f"API ์์ฒญ ์คํจ: {str(e)}"
|
29 |
+
|
30 |
+
def get_space_visitors(owner, space_name, token):
|
31 |
+
"""ํน์ Space์ ๋ฐฉ๋ฌธ์ ํต๊ณ๋ฅผ ๊ฐ์ ธ์ต๋๋ค."""
|
32 |
+
url = f"https://huggingface.co/api/spaces/{owner}/{space_name}/metrics"
|
33 |
+
headers = {"Authorization": f"Bearer {token}"}
|
34 |
+
|
35 |
+
try:
|
36 |
+
response = requests.get(url, headers=headers)
|
37 |
+
response.raise_for_status()
|
38 |
+
|
39 |
+
# ์ต๊ทผ 7์ผ๊ฐ์ ๋ฐ์ดํฐ๋ง ํํฐ๋ง
|
40 |
+
today = datetime.now()
|
41 |
+
week_ago = today - timedelta(days=7)
|
42 |
+
|
43 |
+
daily_visits = {}
|
44 |
+
total_visits = 0
|
45 |
+
|
46 |
+
for record in response.json():
|
47 |
+
date = datetime.fromtimestamp(record['timestamp'])
|
48 |
+
if date >= week_ago:
|
49 |
+
date_str = date.strftime('%Y-%m-%d')
|
50 |
+
visits = record.get('visits', 0)
|
51 |
+
daily_visits[date_str] = daily_visits.get(date_str, 0) + visits
|
52 |
+
total_visits += visits
|
53 |
+
|
54 |
+
return {
|
55 |
+
'name': space_name,
|
56 |
+
'total_visits': total_visits,
|
57 |
+
'daily_visits': daily_visits
|
58 |
+
}
|
59 |
+
|
60 |
+
except requests.exceptions.RequestException:
|
61 |
+
return None
|
62 |
+
|
63 |
+
def analyze_spaces(token):
|
64 |
+
"""๋ชจ๋ Space์ ๋ฐฉ๋ฌธ์ ํต๊ณ๋ฅผ ๋ถ์ํฉ๋๋ค."""
|
65 |
+
if not token:
|
66 |
+
return "API ํ ํฐ์ ์
๋ ฅํด์ฃผ์ธ์.", None, None
|
67 |
+
|
68 |
+
# ์ฌ์ฉ์ ์ ๋ณด์ Space ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ
|
69 |
+
username, spaces_data = get_user_spaces(token)
|
70 |
+
|
71 |
+
if not username:
|
72 |
+
return f"์ค๋ฅ: {spaces_data}", None, None
|
73 |
+
|
74 |
+
if not isinstance(spaces_data, list):
|
75 |
+
return "Space ๋ชฉ๋ก์ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค.", None, None
|
76 |
+
|
77 |
+
# ๊ฐ Space์ ๋ฐฉ๋ฌธ์ ํต๊ณ ์์ง
|
78 |
+
all_stats = []
|
79 |
+
daily_data = []
|
80 |
+
|
81 |
+
for space in spaces_data:
|
82 |
+
space_name = space.get('id')
|
83 |
+
if space_name:
|
84 |
+
stats = get_space_visitors(username, space_name, token)
|
85 |
+
if stats:
|
86 |
+
all_stats.append(stats)
|
87 |
+
for date, visits in stats['daily_visits'].items():
|
88 |
+
daily_data.append({
|
89 |
+
'date': date,
|
90 |
+
'space': space_name,
|
91 |
+
'visits': visits
|
92 |
+
})
|
93 |
+
|
94 |
+
if not all_stats:
|
95 |
+
return "๋ฐฉ๋ฌธ์ ํต๊ณ๋ฅผ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค.", None, None
|
96 |
+
|
97 |
+
# ๊ฒฐ๊ณผ ํ
์คํธ ์์ฑ
|
98 |
+
result_text = f"๊ณ์ : {username}\n\n"
|
99 |
+
for stats in sorted(all_stats, key=lambda x: x['total_visits'], reverse=True):
|
100 |
+
result_text += f"Space: {stats['name']}\n"
|
101 |
+
result_text += f"์ด ๋ฐฉ๋ฌธ์ ์: {stats['total_visits']}๋ช
\n\n"
|
102 |
+
|
103 |
+
# ๊ทธ๋ํ ์์ฑ
|
104 |
+
if daily_data:
|
105 |
+
df = pd.DataFrame(daily_data)
|
106 |
+
fig = px.line(df, x='date', y='visits', color='space',
|
107 |
+
title=f'Space๋ณ ์ผ์ผ ๋ฐฉ๋ฌธ์ ์',
|
108 |
+
labels={'date': '๋ ์ง', 'visits': '๋ฐฉ๋ฌธ์ ์', 'space': 'Space ์ด๋ฆ'})
|
109 |
+
|
110 |
+
# ๋ง๋ ๊ทธ๋ํ ์์ฑ
|
111 |
+
summary_df = pd.DataFrame([(s['name'], s['total_visits']) for s in all_stats],
|
112 |
+
columns=['space', 'total_visits'])
|
113 |
+
summary_fig = px.bar(summary_df, x='space', y='total_visits',
|
114 |
+
title='Space๋ณ ์ด ๋ฐฉ๋ฌธ์ ์',
|
115 |
+
labels={'space': 'Space ์ด๋ฆ', 'total_visits': '์ด ๋ฐฉ๋ฌธ์ ์'})
|
116 |
+
|
117 |
+
return result_text, fig, summary_fig
|
118 |
+
|
119 |
+
return result_text, None, None
|
120 |
+
|
121 |
+
# Gradio ์ธํฐํ์ด์ค ์์ฑ
|
122 |
+
with gr.Blocks() as app:
|
123 |
+
gr.Markdown("""
|
124 |
+
# Hugging Face Space ๋ฐฉ๋ฌธ์ ํต๊ณ
|
125 |
+
API ํ ํฐ์ ์
๋ ฅํ๋ฉด ๋ชจ๋ Space์ ๋ฐฉ๋ฌธ์ ํต๊ณ๋ฅผ ํ์ธํ ์ ์์ต๋๋ค.
|
126 |
+
""")
|
127 |
+
|
128 |
+
with gr.Row():
|
129 |
+
token_input = gr.Textbox(label="API ํ ํฐ", type="password")
|
130 |
+
submit_btn = gr.Button("ํต๊ณ ํ์ธ")
|
131 |
+
|
132 |
+
stats_output = gr.Textbox(label="ํต๊ณ ์ ๋ณด", lines=10)
|
133 |
+
plot_output = gr.Plot(label="์ผ๋ณ ๋ฐฉ๋ฌธ์ ์")
|
134 |
+
summary_plot = gr.Plot(label="์ด ๋ฐฉ๋ฌธ์ ์")
|
135 |
+
|
136 |
+
submit_btn.click(
|
137 |
+
analyze_spaces,
|
138 |
+
inputs=[token_input],
|
139 |
+
outputs=[stats_output, plot_output, summary_plot]
|
140 |
+
)
|
141 |
|
142 |
if __name__ == "__main__":
|
143 |
+
app.launch()
|
|