Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
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'<latex_image:{image_base64}>') | |
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('<latex_image:') | |
for part in parts: | |
if part.startswith('data:image'): | |
# LaTeX ์ด๋ฏธ์ง ๋ถ๋ถ | |
image_data = part.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')) |