seawolf2357's picture
Update app.py
1e3100b verified
raw
history blame
9.25 kB
import os
import google_auth_oauthlib.flow
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
import discord
import logging
import re
import asyncio
import subprocess
from huggingface_hub import InferenceClient
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api.formatters import TextFormatter
from dotenv import load_dotenv
# ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ๋กœ๋“œ
load_dotenv()
# JSON_TOKEN.json ํŒŒ์ผ์˜ ๊ฒฝ๋กœ
credentials_path = 'JSON_TOKEN.json'
token_path = 'token.json'
auth_code_path = 'auth_code.txt' # ์ธ์ฆ ์ฝ”๋“œ๋ฅผ ์ €์žฅํ•  ํŒŒ์ผ ๊ฒฝ๋กœ
# ๋กœ๊น… ์„ค์ •
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', handlers=[logging.StreamHandler()])
# ์ธํ…ํŠธ ์„ค์ •
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.guilds = True
intents.guild_messages = True
# ์ถ”๋ก  API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus", token=os.getenv("HF_TOKEN"))
# OAuth 2.0 ์ธ์ฆ ์„ค์ •
SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"]
creds = None
def authorize():
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
credentials_path, SCOPES)
auth_url, _ = flow.authorization_url(prompt='consent')
print('Please go to this URL and finish the authentication: {}'.format(auth_url))
print(f'Enter the authorization code in the file {auth_code_path} and press Enter')
input('Press Enter after saving the authorization code...')
if not os.path.exists(auth_code_path):
raise FileNotFoundError(f"'{auth_code_path}' ํŒŒ์ผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
with open(auth_code_path, 'r') as file:
code = file.read().strip()
flow.fetch_token(code=code)
creds = flow.credentials
with open(token_path, 'w') as token:
token.write(creds.to_json())
return creds
# ๊ธฐ์กด ํ† ํฐ์„ ๋กœ๋“œํ•˜๊ฑฐ๋‚˜ ์ƒˆ๋กœ ์ธ์ฆ
if os.path.exists(token_path):
creds = Credentials.from_authorized_user_file(token_path, SCOPES)
else:
creds = authorize()
# ํ† ํฐ ๊ฐฑ์‹  ๋˜๋Š” ์žฌ์ธ์ฆ
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
creds = authorize()
# YouTube API ํด๋ผ์ด์–ธํŠธ ์ƒ์„ฑ
youtube_service = build('youtube', 'v3', credentials=creds)
# ๋””์Šค์ฝ”๋“œ ๋ด‡ ์„ค์ •
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_processing = False
async def on_ready(self):
logging.info(f'{self.user}๋กœ ๋กœ๊ทธ์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!')
# web.py ํŒŒ์ผ ์‹คํ–‰
subprocess.Popen(["python", "web.py"])
logging.info("Web.py server has been started.")
# ๋ด‡์ด ์‹œ์ž‘๋  ๋•Œ ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€๋ฅผ ์ „์†ก
channel = self.get_channel(SPECIFIC_CHANNEL_ID)
if channel:
await channel.send("์œ ํŠœ๋ธŒ ๋น„๋””์˜ค URL์„ ์ž…๋ ฅํ•˜๋ฉด, ์ž๋ง‰๊ณผ ๋Œ“๊ธ€์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋‹ต๊ธ€์„ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.")
async def on_message(self, message):
if message.author == self.user:
return
if not self.is_message_in_specific_channel(message):
return
if self.is_processing:
return
self.is_processing = True
try:
video_id = extract_video_id(message.content)
if video_id:
transcript = await get_best_available_transcript(video_id)
comments = await get_video_comments(video_id)
if comments and transcript:
replies = await generate_replies(comments, transcript)
await create_thread_and_send_replies(message, video_id, comments, replies)
await post_replies_to_youtube(video_id, comments, replies)
else:
await message.channel.send("์ž๋ง‰์ด๋‚˜ ๋Œ“๊ธ€์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
else:
await message.channel.send("์œ ํšจํ•œ ์œ ํŠœ๋ธŒ ๋น„๋””์˜ค URL์„ ์ œ๊ณตํ•ด ์ฃผ์„ธ์š”.")
finally:
self.is_processing = False
def is_message_in_specific_channel(self, message):
# ๋ฉ”์‹œ์ง€๊ฐ€ ์ง€์ •๋œ ์ฑ„๋„์ด๊ฑฐ๋‚˜, ํ•ด๋‹น ์ฑ„๋„์˜ ์“ฐ๋ ˆ๋“œ์ธ ๊ฒฝ์šฐ True ๋ฐ˜ํ™˜
return message.channel.id == SPECIFIC_CHANNEL_ID or (
isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
)
def extract_video_id(url):
"""
YouTube ๋น„๋””์˜ค URL์—์„œ ๋น„๋””์˜ค ID๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
"""
video_id = None
youtube_regex = (
r'(https?://)?(www\.)?'
'(youtube|youtu|youtube-nocookie)\.(com|be)/'
'(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})')
match = re.match(youtube_regex, url)
if match:
video_id = match.group(6)
logging.debug(f'Extracted video ID: {video_id}')
return video_id
async def get_best_available_transcript(video_id):
"""
YouTube ๋น„๋””์˜ค์˜ ์ž๋ง‰์„ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.
"""
try:
# ํ•œ๊ตญ์–ด ์ž๋ง‰ ์‹œ๋„
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['ko'])
except Exception as e:
logging.warning(f'Error fetching Korean transcript: {e}')
try:
# ํ•œ๊ตญ์–ด ์ž๋ง‰์ด ์—†์œผ๋ฉด ์˜์–ด ์ž๋ง‰ ์‹œ๋„
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])
except Exception as e:
logging.warning(f'Error fetching English transcript: {e}')
try:
# ์˜์–ด ์ž๋ง‰๋„ ์—†์œผ๋ฉด ๋‹ค๋ฅธ ์–ธ์–ด ์ž๋ง‰ ์‹œ๋„
transcripts = YouTubeTranscriptApi.list_transcripts(video_id)
transcript = transcripts.find_manually_created_transcript().fetch()
except Exception as e:
logging.error(f'Error fetching alternative transcript: {e}')
return None
# ์ž๋ง‰ ํฌ๋งทํŒ…
formatter = TextFormatter()
transcript_text = formatter.format_transcript(transcript)
logging.debug(f'Fetched transcript: {transcript_text}')
return transcript_text
async def get_video_comments(video_id):
"""
YouTube ๋น„๋””์˜ค์˜ ๋Œ“๊ธ€์„ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.
"""
comments = []
response = youtube_service.commentThreads().list(
part='snippet',
videoId=video_id,
maxResults=100 # ์ตœ๋Œ€ 100๊ฐœ์˜ ๋Œ“๊ธ€ ๊ฐ€์ ธ์˜ค๊ธฐ
).execute()
for item in response.get('items', []):
comment = item['snippet']['topLevelComment']['snippet']['textOriginal']
comment_id = item['snippet']['topLevelComment']['id']
comments.append((comment, comment_id)) # ๋Œ“๊ธ€๊ณผ ๋Œ“๊ธ€ ID๋ฅผ ํ•จ๊ป˜ ์ €์žฅ
logging.debug(f'Fetched comments: {comments}')
return comments
async def generate_replies(comments, transcript):
"""
๋Œ“๊ธ€๊ณผ ์ž๋ง‰์„ ๊ธฐ๋ฐ˜์œผ๋กœ LLM ๋‹ต๊ธ€์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
"""
replies = []
for comment, _ in comments:
messages = [
{"role": "system", "content": f"๋น„๋””์˜ค ์ž๋ง‰: {transcript}"},
{"role": "user", "content": comment}
]
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(None, lambda: hf_client.chat_completion(
messages, max_tokens=400, temperature=0.7, top_p=0.85)) # max_tokens ๊ฐ’์„ ์กฐ์ •
if response.choices and response.choices[0].message:
reply = response.choices[0].message['content'].strip()
else:
reply = "๋‹ต๊ธ€์„ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."
replies.append(reply)
logging.debug(f'Generated replies: {replies}')
return replies
async def create_thread_and_send_replies(message, video_id, comments, replies):
"""
๋Œ“๊ธ€๊ณผ ๋‹ต๊ธ€์„ ์ƒˆ๋กœ์šด ์“ฐ๋ ˆ๋“œ์— ์ „์†กํ•ฉ๋‹ˆ๋‹ค.
"""
thread = await message.channel.create_thread(name=f"{message.author.name}์˜ ๋Œ“๊ธ€ ๋‹ต๊ธ€", message=message)
for (comment, _), reply in zip(comments, replies):
embed = discord.Embed(description=f"**๋Œ“๊ธ€**: {comment}\n**๋‹ต๊ธ€**: {reply}")
await thread.send(embed=embed)
async def post_replies_to_youtube(video_id, comments, replies):
"""
์ƒ์„ฑ๋œ ๋‹ต๊ธ€์„ YouTube ๋Œ“๊ธ€๋กœ ๊ฒŒ์‹œํ•ฉ๋‹ˆ๋‹ค.
"""
for (comment, comment_id), reply in zip(comments, replies):
try:
response = youtube_service.comments().insert(
part='snippet',
body={
'snippet': {
'parentId': comment_id,
'textOriginal': reply
}
}
).execute()
logging.debug(f'Posted reply to comment: {comment_id} with response: {response}')
except Exception as e:
logging.error(f'Error posting reply to comment {comment_id}: {e}')
logging.debug(f'Response: {e.resp} | Content: {e.content}')
if __name__ == "__main__":
discord_client = MyClient(intents=intents)
discord_client.run(os.getenv('DISCORD_TOKEN'))