Spaces:
seawolf2357
/
Running on CPU Upgrade

kai-math / app.py
seawolf2357's picture
Update app.py
939869e verified
raw
history blame
3.2 kB
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'))