seawolf2357 commited on
Commit
b29883b
ยท
verified ยท
1 Parent(s): d3b3b22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -123
app.py CHANGED
@@ -1,128 +1,143 @@
1
- import discord
2
- import logging
3
- import os
4
- from huggingface_hub import InferenceClient
5
  import requests
6
- import asyncio
7
- import subprocess
8
- from dotenv import load_dotenv
9
 
10
- # Load environment variables
11
- load_dotenv()
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
- logging.debug(f'Extracting keywords from user input: {user_input}')
89
-
90
- messages = [{"role": "system", "content": system_prompt + user_input}]
91
- logging.debug(f'Messages to be sent to the model: {messages}')
92
-
93
- loop = asyncio.get_event_loop()
94
- response = await loop.run_in_executor(None, lambda: hf_client.chat_completion(
95
- messages, max_tokens=10, temperature=0.7, top_p=0.85))
96
-
97
- # Parse Hugging Face response
98
- if response.choices and response.choices[0].message:
99
- keywords = response.choices[0].message['content'].strip()
100
- else:
101
- keywords = ""
102
- logging.debug(f'Extracted keywords: {keywords}')
103
- return keywords
104
-
105
- async def search_videos(keywords):
106
- params = {
107
- "key": PIXABAY_API_KEY,
108
- "q": keywords,
109
- "per_page": 40 # Get up to 40 videos
110
- }
111
- response = requests.get(PIXABAY_API_URL, params=params)
112
- if response.status_code == 200:
113
- data = response.json()
114
- return [video['videos']['medium']['url'] for video in data['hits'] if 'videos' in video]
115
- logging.error(f"Pixabay API error: {response.status_code}, {response.text}")
116
- return None
117
-
118
- async def create_thread_and_send_videos(message, keywords, video_urls):
119
- # Create a thread
120
- thread = await message.channel.create_thread(name=f"{message.author.name}์˜ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ", message=message)
121
- message_content = f"**{keywords}**์— ๋Œ€ํ•œ ๋น„๋””์˜ค {len(video_urls)}๊ฐœ๋ฅผ ์ฐพ์•˜์Šต๋‹ˆ๋‹ค:"
122
- await thread.send(message_content)
123
- for url in video_urls:
124
- await thread.send(url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  if __name__ == "__main__":
127
- discord_client = MyClient(intents=intents)
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()