kai-law2 / app.py
seawolf2357's picture
Update app.py
ec0581c verified
import discord
import logging
import os
from huggingface_hub import InferenceClient
import asyncio
import subprocess
from datasets import load_dataset
import pandas as pd
from fuzzywuzzy import process
# ν˜„μž¬ μž‘μ—… 디렉토리 좜λ ₯
print("Current Working Directory:", os.getcwd())
# 데이터셋 파일 이름
data_files = ['train_0.csv', 'train_1.csv', 'train_2.csv', 'train_3.csv', 'train_4.csv', 'train_5.csv']
# ν˜„μž¬ μž‘μ—… 디렉토리에 λͺ¨λ“  파일이 μžˆλŠ”μ§€ 확인
missing_files = [file for file in data_files if not os.path.exists(file)]
if missing_files:
print(f"Missing files: {missing_files}")
# ν•„μš”ν•œ 경우 μž‘μ—… 디렉토리 λ³€κ²½
os.chdir('/home/user/app')
print("Changed directory to:", os.getcwd())
else:
print("All files are present in the current directory.")
# 데이터셋 λ‘œλ“œ 및 μ΅œμ ν™”
def load_optimized_dataset(data_files):
data_frames = [pd.read_csv(file) for file in data_files]
full_data = pd.concat(data_frames, ignore_index=True)
# NaN κ°’ 처리
full_data['νŒμ‹œμ‚¬ν•­'] = full_data['νŒμ‹œμ‚¬ν•­'].fillna('')
full_data['사건λͺ…'] = full_data['사건λͺ…'].fillna('')
# 사건λͺ…을 ν‚€λ‘œ ν•˜κ³  μ‚¬κ±΄λ²ˆν˜Έμ™€ 전문을 μ €μž₯ν•˜λŠ” λ”•μ…”λ„ˆλ¦¬ 생성
name_to_number = full_data.groupby('사건λͺ…')['μ‚¬κ±΄λ²ˆν˜Έ'].apply(list).to_dict()
summary_to_number = full_data.groupby('νŒμ‹œμ‚¬ν•­')['μ‚¬κ±΄λ²ˆν˜Έ'].apply(list).to_dict()
number_to_fulltext = full_data.set_index('μ‚¬κ±΄λ²ˆν˜Έ')['μ „λ¬Έ'].to_dict()
return name_to_number, summary_to_number, number_to_fulltext
name_to_number, summary_to_number, number_to_fulltext = load_optimized_dataset(data_files)
print("Dataset loaded successfully.")
# 사건λͺ… 및 νŒμ‹œμ‚¬ν•­ 리슀트 생성
all_case_names = list(name_to_number.keys())
all_case_summaries = list(summary_to_number.keys())
# λ””λ²„κΉ…μš© λ‘œκΉ…
logging.debug(f"Sample all_case_names: {all_case_names[:3]}")
logging.debug(f"Sample all_case_summaries: {all_case_summaries[:3]}")
# λ‘œκΉ… μ„€μ •
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-08-2024", token=os.getenv("HF_TOKEN"))
# νŠΉμ • 채널 ID
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
# λŒ€ν™” νžˆμŠ€ν† λ¦¬λ₯Ό μ €μž₯ν•  μ „μ—­ λ³€μˆ˜
conversation_history = []
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}둜 λ‘œκ·ΈμΈλ˜μ—ˆμŠ΅λ‹ˆλ‹€!')
subprocess.Popen(["python", "web.py"])
logging.info("Web.py server has been started.")
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:
logging.debug("Currently processing another message, skipping this one.")
return
self.is_processing = True
try:
response_parts = await generate_response(message)
if response_parts:
for part in response_parts:
await message.channel.send(part)
else:
await message.channel.send("μ£„μ†‘ν•©λ‹ˆλ‹€, μ œκ³΅ν•  수 μžˆλŠ” 정보가 μ—†μŠ΅λ‹ˆλ‹€.")
finally:
self.is_processing = False
logging.debug("Message processing completed, ready for the next one.")
def is_message_in_specific_channel(self, message):
channel_condition = message.channel.id == SPECIFIC_CHANNEL_ID
thread_condition = isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
return channel_condition or thread_condition
async def generate_response(message):
global conversation_history
user_input = message.content.strip()
user_mention = message.author.mention
# μœ μ‚¬ν•œ 사건λͺ… 및 νŒμ‹œμ‚¬ν•­ 각각 μ°ΎκΈ°
matched_case_names = process.extractBests(user_input, all_case_names, limit=3, score_cutoff=70)
matched_case_summaries = process.extractBests(user_input, all_case_summaries, limit=3, score_cutoff=70)
logging.debug(f"Matched case names: {matched_case_names}")
logging.debug(f"Matched case summaries: {matched_case_summaries}")
case_numbers_set = set()
if matched_case_names:
for case_name, score in matched_case_names:
case_numbers_set.update(name_to_number.get(case_name, []))
if matched_case_summaries:
for case_summary, score in matched_case_summaries:
case_numbers_set.update(summary_to_number.get(case_summary, []))
if case_numbers_set:
case_numbers_str = "\n".join(case_numbers_set)
system_message = f"{user_mention}, '{user_input}'와 μœ μ‚¬ν•œ μ‚¬κ±΄μ˜ μ‚¬κ±΄λ²ˆν˜ΈλŠ” λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€:\n{case_numbers_str}"
elif user_input in number_to_fulltext:
full_text = number_to_fulltext[user_input]
system_message = f"{user_mention}, μ‚¬κ±΄λ²ˆν˜Έ '{user_input}'의 전문은 λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€:\n\n{full_text}"
else:
system_message = f"{user_mention}, κ΄€λ ¨ 법λ₯  정보λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
# λ©”μ‹œμ§€ 길이 μ œν•œ 처리
max_length = 2000
response_parts = []
for i in range(0, len(system_message), max_length):
part_response = system_message[i:i + max_length]
response_parts.append(part_response)
return response_parts
if __name__ == "__main__":
discord_client = MyClient(intents=intents)
discord_client.run(os.getenv('DISCORD_TOKEN'))