Spaces:
Raven7
/
Runtime error

Raven7 commited on
Commit
164cb65
Β·
verified Β·
1 Parent(s): b8a04bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -33
app.py CHANGED
@@ -1,43 +1,85 @@
1
- import requests
2
- import json
3
- import pandas as pd
4
- import os
5
- import pyarrow.parquet as pq
6
  import discord
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Discord 봇 토큰 및 채널 I μ„€μ •
9
- discordtoken = "MI2Mk0zQ3czc0Mz4Mw.Glf6.2bSeer-q5jHVnClSe1wsP0IHpVyIdxGaYac"
10
- discordchannelid = 1261896610506604564
 
 
11
 
12
- # Discord ν΄λΌμ΄μ–ΈνŠΈ 생성
13
- client = discord.Client()
14
 
15
- def respondtodiscord(message):
16
- # λ©”μ‹œμ§€ 전솑을 μœ„ν•œ Discord API μ—”λ“œν¬μΈνŠΈ
17
- url = f"https://discord.com/api/v9/channels/{discordchannelid}/messages"
 
 
 
 
 
 
 
18
 
19
- # λ©”μ‹œμ§€ 전솑 데이터
20
- data = {
21
- "content": message
22
- }
23
 
24
- # Discord API 인증 헀더
25
- headers = {
26
- "Authorization": discordtoken
27
- }
28
 
29
- try:
30
- # λ©”μ‹œμ§€ 전솑
31
- response = requests.post(url, headers=headers, json=data)
 
 
32
 
33
- if response.statuscode == 200:
34
- print("λ©”μ‹œμ§€ 전솑 성곡")
35
- else:
36
- print(f"λ©”μ‹œμ§€ 전솑 μ‹€νŒ¨: {response.statuscode}")
37
 
38
- except Exception as e:
39
- print(f"예기치 λͺ»ν•œ 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}")
40
 
41
- def getanswer(question):
42
- matchinganswer = df[df['question'] == question]['answer'].values
43
- return matching
 
 
 
 
 
 
1
  import discord
2
+ import logging
3
+ import os
4
+ from huggingface_hub import InferenceClient
5
+ import asyncio
6
+ import subprocess
7
+
8
+ # λ‘œκΉ… μ„€μ •
9
+ logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s: %(message)s', handlers=[logging.StreamHandler()])
10
+
11
+ # μΈν…νŠΈ μ„€μ •
12
+ intents = discord.Intents.default()
13
+ intents.message_content = True
14
+ intents.messages = True
15
+ intents.guilds = True
16
+ intents.guild_messages = True
17
+
18
+ # μΆ”λ‘  API ν΄λΌμ΄μ–ΈνŠΈ μ„€μ •
19
+ hf_client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct", token=os.getenv("HF_TOKEN"))
20
+
21
+ # νŠΉμ • 채널 ID
22
+ SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
23
+
24
+ # λŒ€ν™” νžˆμŠ€ν† λ¦¬λ₯Ό μ €μž₯ν•  μ „μ—­ λ³€μˆ˜
25
+ conversation_history = []
26
+
27
+ class MyClient(discord.Client):
28
+ def __init__(self, *args, **kwargs):
29
+ super().__init__(*args, **kwargs)
30
+ self.is_processing = False
31
+
32
+ async def on_message(self, message):
33
+ if message.author == self.user:
34
+ return
35
+ if not self.is_message_in_specific_channel(message):
36
+ return
37
+ if self.is_processing:
38
+ return
39
+ self.is_processing = True
40
+ try:
41
+ response = await generate_response(message)
42
+ await message.channel.send(response)
43
+ finally:
44
+ self.is_processing = False
45
 
46
+ def is_message_in_specific_channel(self, message):
47
+ # λ©”μ‹œμ§€κ°€ μ§€μ •λœ μ±„λ„μ΄κ±°λ‚˜, ν•΄λ‹Ή μ±„λ„μ˜ μ“°λ ˆλ“œμΈ 경우 True λ°˜ν™˜
48
+ return message.channel.id == SPECIFIC_CHANNEL_ID or (
49
+ isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
50
+ )
51
 
 
 
52
 
53
+ async def generate_response(message):
54
+ global conversation_history # μ „μ—­ λ³€μˆ˜ μ‚¬μš©μ„ λͺ…μ‹œ
55
+ user_input = message.content
56
+ user_mention = message.author.mention
57
+ system_message = f"{user_mention}, DISCORDμ—μ„œ μ‚¬μš©μžλ“€μ˜ μ§ˆλ¬Έμ— λ‹΅ν•˜λŠ” μ–΄μ‹œμŠ€ν„΄νŠΈμž…λ‹ˆλ‹€."
58
+ system_prefix = """
59
+ λ°˜λ“œμ‹œ ν•œκΈ€λ‘œ λ‹΅λ³€ν•˜μ‹­μ‹œμ˜€.
60
+ """
61
+ conversation_history.append({"role": "user", "content": user_input})
62
+ logging.debug(f'Conversation history updated: {conversation_history}')
63
 
64
+ messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}] + conversation_history
65
+ logging.debug(f'Messages to be sent to the model: {messages}')
 
 
66
 
67
+ loop = asyncio.get_event_loop()
68
+ response = await loop.run_in_executor(None, lambda: hf_client.chat_completion(
69
+ messages, max_tokens=1000, stream=True, temperature=0.7, top_p=0.85))
 
70
 
71
+ full_response = []
72
+ for part in response:
73
+ logging.debug(f'Part received from stream: {part}')
74
+ if part.choices and part.choices[0].delta and part.choices[0].delta.content:
75
+ full_response.append(part.choices[0].delta.content)
76
 
77
+ full_response_text = ''.join(full_response)
78
+ logging.debug(f'Full model response: {full_response_text}')
 
 
79
 
80
+ conversation_history.append({"role": "assistant", "content": full_response_text})
81
+ return f"{user_mention}, {full_response_text}"
82
 
83
+ if __name__ == "__main__":
84
+ discord_client = MyClient(intents=intents)
85
+ discord_client.run(os.getenv('DISCORD_TOKEN'))