kai-law2 / app.py
seawolf2357's picture
Update app.py
13feae4 verified
raw
history blame
4.23 kB
import discord
import logging
import os
from huggingface_hub import InferenceClient
import asyncio
import subprocess
from datasets import load_dataset
# ν˜„μž¬ μž‘μ—… 디렉토리 좜λ ₯
print("Current Working Directory:", os.getcwd())
# 데이터셋 파일 이름
data_file = 'train_0.csv'
# ν˜„μž¬ μž‘μ—… 디렉토리에 파일이 μžˆλŠ”μ§€ 확인
if os.path.exists(data_file):
print(f"File {data_file} exists in the current directory.")
else:
print(f"File {data_file} does not exist in the current directory.")
# μž‘μ—… 디렉토리 λ³€κ²½ (ν•„μš”ν•œ 경우)
os.chdir('/home/user/app')
print("Changed directory to:", os.getcwd())
# 데이터셋 λ‘œλ“œ
law_dataset = load_dataset('csv', data_files=data_file)
print("Dataset loaded successfully.")
# λ‘œκΉ… μ„€μ •
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"))
# νŠΉμ • 채널 ID
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
# λŒ€ν™” νžˆμŠ€ν† λ¦¬λ₯Ό μ €μž₯ν•  μ „μ—­ λ³€μˆ˜
conversation_history = []
# 법λ₯  데이터셋 λ‘œλ“œ
law_dataset = load_dataset('csv', data_files='train_0.csv')
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:
return
self.is_processing = True
try:
response = await generate_response(message)
# λΉ„μ–΄ μžˆλŠ” 응닡을 ν™•μΈν•˜κ³  처리
if response.strip() == "":
response = "μ£„μ†‘ν•©λ‹ˆλ‹€, μ œκ³΅ν•  수 μžˆλŠ” 정보가 μ—†μŠ΅λ‹ˆλ‹€."
await message.channel.send(response)
finally:
self.is_processing = False
def is_message_in_specific_channel(self, message):
return message.channel.id == SPECIFIC_CHANNEL_ID or (
isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
)
async def generate_response(message):
global conversation_history
user_input = message.content
user_mention = message.author.mention
system_message = f"{user_mention}, DISCORDμ—μ„œ μ‚¬μš©μžλ“€μ˜ μ§ˆλ¬Έμ— λ‹΅ν•˜λŠ” μ–΄μ‹œμŠ€ν„΄νŠΈμž…λ‹ˆλ‹€."
# 데이터 검색 및 응닡 μ€€λΉ„
answer = search_in_dataset(user_input, law_dataset)
full_response_text = system_message + "\n\n" + answer
# 응닡 λΆ„ν•  전솑
max_length = 2000
if len(full_response_text) > max_length:
# λ„ˆλ¬΄ κΈ΄ λ©”μ‹œμ§€λ₯Ό μ—¬λŸ¬ λΆ€λΆ„μœΌλ‘œ λ‚˜λˆ„μ–΄ λ³΄λƒ…λ‹ˆλ‹€.
for i in range(0, len(full_response_text), max_length):
part_response = full_response_text[i:i+max_length]
await message.channel.send(part_response)
else:
# λ©”μ‹œμ§€ 길이가 μ μ ˆν•˜λ©΄ ν•œ λ²ˆμ— 전솑
await message.channel.send(full_response_text)
logging.debug(f'Full model response sent: {full_response_text}')
conversation_history.append({"role": "assistant", "content": full_response_text})
def search_in_dataset(query, dataset):
# κ°„λ‹¨ν•œ 검색 λ‘œμ§μ„ κ΅¬ν˜„ν•©λ‹ˆλ‹€.
# μ—¬κΈ°μ—μ„œλŠ” 예제둜 λ‹¨μˆœν™”ν•˜κΈ° μœ„ν•΄ 첫 번째 ν•­λͺ©μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.
for record in dataset['train']:
if query in record['사건λͺ…']:
return record['μ‚¬κ±΄λ²ˆν˜Έ']
return "κ΄€λ ¨ 법λ₯  정보λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
if __name__ == "__main__":
discord_client = MyClient(intents=intents)
discord_client.run(os.getenv('DISCORD_TOKEN'))