import discord import logging import os import requests from huggingface_hub import InferenceClient from transformers import pipeline import asyncio import subprocess import re import urllib.parse from requests.exceptions import HTTPError import matplotlib.pyplot as plt from io import BytesIO import base64 # 기존 import 및 설정 유지 # LaTeX를 이미지로 변환하는 함수 추가 def latex_to_image(latex_string): plt.figure(figsize=(10, 1)) plt.axis('off') plt.text(0.5, 0.5, f'${latex_string}$', size=20, ha='center', va='center') buffer = BytesIO() plt.savefig(buffer, format='png', bbox_inches='tight', pad_inches=0.1, transparent=True) buffer.seek(0) image_base64 = base64.b64encode(buffer.getvalue()).decode() plt.close() return image_base64 # LaTeX 수식을 찾아 이미지로 변환하는 함수 def process_and_convert_latex(text): latex_pattern = r'\$(.*?)\$' matches = re.findall(latex_pattern, text) for match in matches: image_base64 = latex_to_image(match) text = text.replace(f'${match}$', f'') return text class MyClient(discord.Client): # 기존 __init__ 및 on_ready 메서드 유지 async def on_message(self, message): # 기존 검사 로직 유지 self.is_processing = True try: if self.is_math_question(message.content): text_response = await self.handle_math_question(message.content) await self.send_message_with_latex(message.channel, text_response) else: response = await self.generate_response(message) await self.send_message_with_latex(message.channel, response) finally: self.is_processing = False # 기존 메서드들 유지 async def handle_math_question(self, question): # 기존 로직 유지 # combined_response 반환 async def generate_response(self, message): # 기존 로직 유지 # full_response 반환 async def send_message_with_latex(self, channel, message): # 텍스트와 LaTeX 수식 분리 processed_message = process_and_convert_latex(message) parts = processed_message.split('')[0] image_binary = base64.b64decode(image_data) await channel.send(file=discord.File(BytesIO(image_binary), 'equation.png')) else: # 텍스트 부분 if part.strip(): await self.send_long_message(channel, part) async def send_long_message(self, channel, message): if len(message) <= 2000: await channel.send(message) else: parts = [message[i:i+2000] for i in range(0, len(message), 2000)] for part in parts: await channel.send(part) if __name__ == "__main__": discord_client = MyClient(intents=intents) discord_client.run(os.getenv('DISCORD_TOKEN'))