Spaces:
Runtime error
Runtime error
seawolf2357
commited on
Commit
β’
4a98e80
1
Parent(s):
b183030
Update app.py
Browse files
app.py
CHANGED
@@ -43,110 +43,70 @@ MAX_RETRIES = 3
|
|
43 |
class MyClient(discord.Client):
|
44 |
def __init__(self, *args, **kwargs):
|
45 |
super().__init__(*args, **kwargs)
|
46 |
-
self.is_processing = False
|
47 |
self.session = None
|
|
|
48 |
|
49 |
async def on_ready(self):
|
50 |
logging.info(f'{self.user}λ‘ λ‘κ·ΈμΈλμμ΅λλ€!')
|
51 |
-
|
52 |
-
# web.py νμΌ μ€ν
|
53 |
subprocess.Popen(["python", "web.py"])
|
54 |
logging.info("Web.py μλ²κ° μμλμμ΅λλ€.")
|
55 |
-
|
56 |
-
# aiohttp ν΄λΌμ΄μΈνΈ μΈμ
μμ±
|
57 |
self.session = aiohttp.ClientSession()
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
async def on_message(self, message):
|
65 |
-
|
66 |
-
return
|
67 |
-
if not self.is_message_in_specific_channel(message):
|
68 |
-
return
|
69 |
-
if self.is_processing:
|
70 |
-
return
|
71 |
-
self.is_processing = True
|
72 |
-
try:
|
73 |
-
video_id = extract_video_id(message.content)
|
74 |
-
if video_id:
|
75 |
-
transcript = await get_best_available_transcript(video_id)
|
76 |
-
comments = await get_video_comments(video_id)
|
77 |
-
if comments and transcript:
|
78 |
-
replies = await generate_replies(comments, transcript)
|
79 |
-
await create_thread_and_send_replies(message, video_id, comments, replies, self.session)
|
80 |
-
else:
|
81 |
-
await message.channel.send("μλ§μ΄λ λκΈμ κ°μ Έμ¬ μ μμ΅λλ€.")
|
82 |
-
else:
|
83 |
-
await message.channel.send("μ ν¨ν μ νλΈ λΉλμ€ URLμ μ κ³΅ν΄ μ£ΌμΈμ.")
|
84 |
-
finally:
|
85 |
-
self.is_processing = False
|
86 |
-
|
87 |
-
def is_message_in_specific_channel(self, message):
|
88 |
-
return message.channel.id == SPECIFIC_CHANNEL_ID or (
|
89 |
-
isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
|
90 |
-
)
|
91 |
|
92 |
async def close(self):
|
93 |
-
# aiohttp ν΄λΌμ΄μΈνΈ μΈμ
μ’
λ£
|
94 |
if self.session:
|
95 |
await self.session.close()
|
96 |
await super().close()
|
97 |
|
98 |
def extract_video_id(url):
|
99 |
-
video_id = None
|
100 |
youtube_regex = (
|
101 |
r'(https?://)?(www\.)?'
|
102 |
'(youtube|youtu|youtube-nocookie)\.(com|be)/'
|
103 |
'(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})')
|
104 |
-
|
105 |
match = re.match(youtube_regex, url)
|
106 |
if match:
|
107 |
-
|
108 |
-
|
109 |
-
return video_id
|
110 |
|
111 |
async def get_best_available_transcript(video_id):
|
112 |
try:
|
113 |
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['ko'])
|
|
|
|
|
114 |
except Exception as e:
|
115 |
-
logging.
|
116 |
-
|
117 |
-
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])
|
118 |
-
except Exception as e:
|
119 |
-
logging.warning(f'μμ΄ μλ§ κ°μ Έμ€κΈ° μ€λ₯: {e}')
|
120 |
-
try:
|
121 |
-
transcripts = YouTubeTranscriptApi.list_transcripts(video_id)
|
122 |
-
transcript = transcripts.find_manually_created_transcript().fetch()
|
123 |
-
except Exception as e:
|
124 |
-
logging.error(f'λ체 μλ§ κ°μ Έμ€κΈ° μ€λ₯: {e}')
|
125 |
-
return None
|
126 |
-
|
127 |
-
formatter = TextFormatter()
|
128 |
-
transcript_text = formatter.format_transcript(transcript)
|
129 |
-
logging.debug(f'κ°μ Έμ¨ μλ§: {transcript_text}')
|
130 |
-
return transcript_text
|
131 |
|
132 |
async def get_video_comments(video_id):
|
133 |
comments = []
|
134 |
-
response = youtube_service.commentThreads().list(
|
135 |
-
part='snippet',
|
136 |
-
videoId=video_id,
|
137 |
-
maxResults=100 # μ΅λ 100κ°μ λκΈ κ°μ Έμ€κΈ°
|
138 |
-
).execute()
|
139 |
-
|
140 |
for item in response.get('items', []):
|
141 |
comment = item['snippet']['topLevelComment']['snippet']['textOriginal']
|
142 |
comment_id = item['snippet']['topLevelComment']['id']
|
143 |
comments.append((comment, comment_id))
|
144 |
-
|
145 |
-
logging.debug(f'κ°μ Έμ¨ λκΈ: {comments}')
|
146 |
return comments
|
147 |
|
148 |
-
async def
|
149 |
-
replies = []
|
150 |
system_prompt = """
|
151 |
λλ μ νλΈ λκΈμ λ΅κΈμ μμ±νλ μν μ΄λ€. λλ μμ£Ό μΉμ νκ³ μ¬μ΄ λ΄μ©μΌλ‘ μ λ¬Έμ μΈ κΈμ '300 ν ν° μ΄λ΄'λ‘ μμ±νμ¬μΌ νλ€.
|
152 |
μμμμ μΆμΆν 'μλ§'μ κΈ°λ°μΌλ‘ μμ λ΄μ©μ κΈ°λ°ν λ΅κΈμ μμ±νλΌ.
|
@@ -155,74 +115,32 @@ async def generate_replies(comments, transcript):
|
|
155 |
λ°λμ νκΈλ‘ λ΅λ³νμμμ€.
|
156 |
μμ±λ κΈμ λ§μ§λ§μ λ°λμ μΈμΏλ§κ³Ό OpenFreeAI λΌκ³ μμ μ λ°νλΌ.
|
157 |
"""
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
return replies
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
async def send_webhook_data(session, chunk_data, chunk_number):
|
180 |
-
max_retries = 3 # μ΅λ μ¬μλ νμ
|
181 |
-
retry_delay = 1 # μ¬μλ μ¬μ΄μ λκΈ° μκ° (μ΄)
|
182 |
-
|
183 |
-
for attempt in range(max_retries):
|
184 |
try:
|
185 |
-
async with session.post(WEBHOOK_URL, json=
|
186 |
if response.status == 200:
|
187 |
-
logging.info(
|
188 |
-
return True # μ±κ³΅ μ μ’
λ£
|
189 |
else:
|
190 |
-
logging.error(f"
|
191 |
except aiohttp.ClientError as e:
|
192 |
-
logging.error(f"
|
193 |
-
except Exception as e:
|
194 |
-
logging.error(f"μΉν
μ μ‘ μ€ μ μ μλ μ€λ₯ λ°μ: {e}, μ²ν¬ {chunk_number}, μλ {attempt+1}")
|
195 |
-
|
196 |
-
await asyncio.sleep(retry_delay) # μ¬μλ μ μ 1μ΄ λκΈ°
|
197 |
-
|
198 |
-
logging.error(f"μΉν
λ°μ΄ν° μ μ‘ μ€ν¨, λͺ¨λ μ¬μλ μμ§: μ²ν¬ {chunk_number}")
|
199 |
-
return False # μ¬μλ νμ μ΄κ³Ό μ μ€ν¨λ‘ κ°μ£Ό
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
async def create_thread_and_send_replies(message, video_id, comments, replies, session):
|
204 |
-
thread = await message.channel.create_thread(name=f"{message.author.name}μ λκΈ λ΅κΈ", message=message)
|
205 |
-
webhook_data = {"video_id": video_id, "replies": []}
|
206 |
-
|
207 |
-
for (comment, comment_id), reply in zip(comments, replies):
|
208 |
-
embed = discord.Embed(description=f"**λκΈ**: {comment}\n**λ΅κΈ**: {reply}")
|
209 |
-
await thread.send(embed=embed)
|
210 |
-
|
211 |
-
# μΉν
λ°μ΄ν° μ€λΉ (comment id ν¬ν¨)
|
212 |
-
webhook_data["replies"].append({"comment": comment, "reply": reply, "comment_id": comment_id})
|
213 |
-
|
214 |
-
# λ°μ΄ν°λ₯Ό μ¬λ¬ λ² λλμ΄ μ μ‘
|
215 |
-
chunk_size = 1 # μ μ‘ν λ°μ΄ν°μ κ°μλ₯Ό 1λ‘ μ€μ νμ¬ κ° λ°μ΄ν°λ₯Ό λ³λλ‘ μ μ‘
|
216 |
-
for i in range(0, len(webhook_data["replies"]), chunk_size):
|
217 |
-
chunk = webhook_data["replies"][i:i+chunk_size]
|
218 |
-
chunk_data = {"video_id": video_id, "replies": chunk}
|
219 |
-
|
220 |
-
success = await send_webhook_data(session, chunk_data, i // chunk_size + 1)
|
221 |
-
if not success:
|
222 |
-
logging.error(f"λ°μ΄ν° μ μ‘ μ€ν¨: {i // chunk_size + 1} λ²μ§Έ μ²ν¬")
|
223 |
|
224 |
if __name__ == "__main__":
|
225 |
discord_client = MyClient(intents=intents)
|
226 |
discord_client.run(os.getenv('DISCORD_TOKEN'))
|
227 |
-
|
228 |
-
|
|
|
43 |
class MyClient(discord.Client):
|
44 |
def __init__(self, *args, **kwargs):
|
45 |
super().__init__(*args, **kwargs)
|
|
|
46 |
self.session = None
|
47 |
+
self.last_comments = {}
|
48 |
|
49 |
async def on_ready(self):
|
50 |
logging.info(f'{self.user}λ‘ λ‘κ·ΈμΈλμμ΅λλ€!')
|
|
|
|
|
51 |
subprocess.Popen(["python", "web.py"])
|
52 |
logging.info("Web.py μλ²κ° μμλμμ΅λλ€.")
|
|
|
|
|
53 |
self.session = aiohttp.ClientSession()
|
54 |
+
self.loop.create_task(self.check_for_new_comments())
|
55 |
+
|
56 |
+
async def check_for_new_comments(self):
|
57 |
+
while True:
|
58 |
+
channel = self.get_channel(SPECIFIC_CHANNEL_ID)
|
59 |
+
if channel:
|
60 |
+
async for message in channel.history(limit=10):
|
61 |
+
video_id = extract_video_id(message.content)
|
62 |
+
if video_id:
|
63 |
+
new_comments = await get_video_comments(video_id)
|
64 |
+
old_comments = self.last_comments.get(video_id, [])
|
65 |
+
for comment in new_comments:
|
66 |
+
if comment not in old_comments:
|
67 |
+
transcript = await get_best_available_transcript(video_id)
|
68 |
+
reply = await generate_reply(comment[0], transcript)
|
69 |
+
await create_thread_and_send_reply(message, video_id, comment, reply, self.session)
|
70 |
+
self.last_comments[video_id] = new_comments
|
71 |
+
await asyncio.sleep(5)
|
72 |
|
73 |
async def on_message(self, message):
|
74 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
async def close(self):
|
|
|
77 |
if self.session:
|
78 |
await self.session.close()
|
79 |
await super().close()
|
80 |
|
81 |
def extract_video_id(url):
|
|
|
82 |
youtube_regex = (
|
83 |
r'(https?://)?(www\.)?'
|
84 |
'(youtube|youtu|youtube-nocookie)\.(com|be)/'
|
85 |
'(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})')
|
|
|
86 |
match = re.match(youtube_regex, url)
|
87 |
if match:
|
88 |
+
return match.group(6)
|
89 |
+
return None
|
|
|
90 |
|
91 |
async def get_best_available_transcript(video_id):
|
92 |
try:
|
93 |
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['ko'])
|
94 |
+
formatter = TextFormatter()
|
95 |
+
return formatter.format_transcript(transcript)
|
96 |
except Exception as e:
|
97 |
+
logging.error(f"Failed to retrieve transcript: {e}")
|
98 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
100 |
async def get_video_comments(video_id):
|
101 |
comments = []
|
102 |
+
response = youtube_service.commentThreads().list(part='snippet', videoId=video_id, maxResults=100).execute()
|
|
|
|
|
|
|
|
|
|
|
103 |
for item in response.get('items', []):
|
104 |
comment = item['snippet']['topLevelComment']['snippet']['textOriginal']
|
105 |
comment_id = item['snippet']['topLevelComment']['id']
|
106 |
comments.append((comment, comment_id))
|
|
|
|
|
107 |
return comments
|
108 |
|
109 |
+
async def generate_reply(comment, transcript):
|
|
|
110 |
system_prompt = """
|
111 |
λλ μ νλΈ λκΈμ λ΅κΈμ μμ±νλ μν μ΄λ€. λλ μμ£Ό μΉμ νκ³ μ¬μ΄ λ΄μ©μΌλ‘ μ λ¬Έμ μΈ κΈμ '300 ν ν° μ΄λ΄'λ‘ μμ±νμ¬μΌ νλ€.
|
112 |
μμμμ μΆμΆν 'μλ§'μ κΈ°λ°μΌλ‘ μμ λ΄μ©μ κΈ°λ°ν λ΅κΈμ μμ±νλΌ.
|
|
|
115 |
λ°λμ νκΈλ‘ λ΅λ³νμμμ€.
|
116 |
μμ±λ κΈμ λ§μ§λ§μ λ°λμ μΈμΏλ§κ³Ό OpenFreeAI λΌκ³ μμ μ λ°νλΌ.
|
117 |
"""
|
118 |
+
prompt = f"{system_prompt}\nλκΈ: {comment}\nλΉλμ€ μλ§: {transcript}"
|
119 |
+
response = await hf_client(text=prompt, max_tokens=150)
|
120 |
+
return response['choices'][0]['text']
|
121 |
+
|
122 |
+
async def create_thread_and_send_reply(message, video_id, comment, reply, session):
|
123 |
+
thread = await message.channel.create_thread(name=f"{message.author.name}μ λκΈ λ΅κΈ", message=message)
|
124 |
+
embed = discord.Embed(description=f"**λκΈ**: {comment[0]}\n**λ΅κΈ**: {reply}")
|
125 |
+
await thread.send(embed=embed)
|
126 |
+
webhook_data = {"video_id": video_id, "replies": [{"comment": comment[0], "reply": reply, "comment_id": comment[1]}]}
|
127 |
+
await send_webhook_data(session, webhook_data)
|
128 |
+
|
129 |
+
async def send_webhook_data(session, data):
|
130 |
+
# λ°μ΄ν° λΆν μ μ‘ λ‘μ§ μΆκ°
|
131 |
+
MAX_CHUNK_SIZE = 2000
|
132 |
+
data_json = json.dumps(data)
|
133 |
+
for i in range(0, len(data_json), MAX_CHUNK_SIZE):
|
134 |
+
chunk = data_json[i:i+MAX_CHUNK_SIZE]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
try:
|
136 |
+
async with session.post(WEBHOOK_URL, json=json.loads(chunk)) as response:
|
137 |
if response.status == 200:
|
138 |
+
logging.info("Webhook data sent successfully.")
|
|
|
139 |
else:
|
140 |
+
logging.error(f"Failed to send webhook data: HTTP {response.status}")
|
141 |
except aiohttp.ClientError as e:
|
142 |
+
logging.error(f"HTTP error occurred while sending webhook data: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
|
144 |
if __name__ == "__main__":
|
145 |
discord_client = MyClient(intents=intents)
|
146 |
discord_client.run(os.getenv('DISCORD_TOKEN'))
|
|
|
|