seawolf2357 commited on
Commit
c99009f
Β·
verified Β·
1 Parent(s): 3c9dc5f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -21
app.py CHANGED
@@ -5,29 +5,32 @@ from huggingface_hub import InferenceClient
5
  import requests
6
  import asyncio
7
  import subprocess
 
8
 
9
- # λ‘œκΉ… μ„€μ •
 
 
 
10
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', handlers=[logging.StreamHandler()])
11
 
12
- # μΈν…νŠΈ μ„€μ •
13
  intents = discord.Intents.default()
14
  intents.message_content = True
15
  intents.messages = True
16
  intents.guilds = True
17
  intents.guild_messages = True
18
 
19
- # μΆ”λ‘  API ν΄λΌμ΄μ–ΈνŠΈ μ„€μ •
20
  hf_client = InferenceClient("meta-llama/Meta-Llama-3.1-70B-Instruct", token=os.getenv("HF_TOKEN"))
21
- #hf_client = InferenceClient("CohereForAI/aya-23-35B", token=os.getenv("HF_TOKEN"))
22
 
23
- # Pexels API ν‚€ μ„€μ •
24
- PEXELS_API_KEY = "I8tiAXZQYb5eHq7VUZ6K0GnIfudtnuxFZin1yMQriADtNoLW5wubC7IE"
25
- PEXELS_API_URL = "https://api.pexels.com/v1/search"
26
 
27
- # νŠΉμ • 채널 ID
28
  SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
29
 
30
- # λŒ€ν™” νžˆμŠ€ν† λ¦¬λ₯Ό μ €μž₯ν•  μ „μ—­ λ³€μˆ˜
31
  conversation_history = []
32
 
33
  class MyClient(discord.Client):
@@ -40,7 +43,7 @@ class MyClient(discord.Client):
40
  subprocess.Popen(["python", "web.py"])
41
  logging.info("Web.py server has been started.")
42
 
43
- # 봇이 μ‹œμž‘λ  λ•Œ μ•ˆλ‚΄ λ©”μ‹œμ§€λ₯Ό 전솑
44
  channel = self.get_channel(SPECIFIC_CHANNEL_ID)
45
  if channel:
46
  await channel.send("찾고싢은 사진에 λŒ€ν•œ μ„€λͺ…을 ν•œ λ¬Έμž₯ λ‹¨μœ„λ‘œ μž…λ ₯ν•˜μ„Έμš”. 예) λˆˆλ°­μ— λ›°μ–΄ 놀고 μžˆλŠ” ν—ˆμŠ€ν‚€")
@@ -54,13 +57,13 @@ class MyClient(discord.Client):
54
  return
55
  self.is_processing = True
56
  try:
57
- # 의미 λΆ„μ„ν•˜μ—¬ 영문 ν‚€μ›Œλ“œ μΆ”μΆœ
58
  keywords = await extract_keywords(message)
59
  if keywords:
60
- # Pexels API둜 고해상도 이미지 검색
61
  image_urls = await search_images(keywords)
62
  if image_urls:
63
- # μš”μ²­μžμ™€μ˜ μ“°λ ˆλ“œ 생성 및 고해상도 이미지 전솑
64
  await create_thread_and_send_images(message, keywords, image_urls)
65
  else:
66
  await message.channel.send(f"**{keywords}**에 λŒ€ν•œ 고해상도 이미지λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
@@ -70,7 +73,7 @@ class MyClient(discord.Client):
70
  self.is_processing = False
71
 
72
  def is_message_in_specific_channel(self, message):
73
- # λ©”μ‹œμ§€κ°€ μ§€μ •λœ μ±„λ„μ΄κ±°λ‚˜, ν•΄λ‹Ή μ±„λ„μ˜ μ“°λ ˆλ“œμΈ 경우 True λ°˜ν™˜
74
  return message.channel.id == SPECIFIC_CHANNEL_ID or (
75
  isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
76
  )
@@ -88,7 +91,7 @@ async def extract_keywords(message):
88
  response = await loop.run_in_executor(None, lambda: hf_client.chat_completion(
89
  messages, max_tokens=10, temperature=0.7, top_p=0.85))
90
 
91
- # Hugging Face 응닡 νŒŒμ‹±
92
  if response.choices and response.choices[0].message:
93
  keywords = response.choices[0].message['content'].strip()
94
  else:
@@ -98,20 +101,21 @@ async def extract_keywords(message):
98
 
99
  async def search_images(keywords):
100
  headers = {
101
- "Authorization": PEXELS_API_KEY
102
  }
103
  params = {
104
  "query": keywords,
105
- "per_page": 80 # μ΅œλŒ€ 20개 이미지λ₯Ό κ°€μ Έμ˜΅λ‹ˆλ‹€
106
  }
107
- response = requests.get(PEXELS_API_URL, headers=headers, params=params)
108
  if response.status_code == 200:
109
  data = response.json()
110
- return [photo['src']['large2x'] for photo in data['photos']]
 
111
  return None
112
 
113
  async def create_thread_and_send_images(message, keywords, image_urls):
114
- # μ“°λ ˆλ“œ 생성
115
  thread = await message.channel.create_thread(name=f"{message.author.name}의 검색 κ²°κ³Ό", message=message)
116
  message_content = f"**{keywords}**에 λŒ€ν•œ 고해상도 이미지 {len(image_urls)}μž₯을 μ°Ύμ•˜μŠ΅λ‹ˆλ‹€:"
117
  await thread.send(message_content)
@@ -120,4 +124,4 @@ async def create_thread_and_send_images(message, keywords, image_urls):
120
 
121
  if __name__ == "__main__":
122
  discord_client = MyClient(intents=intents)
123
- discord_client.run(os.getenv('DISCORD_TOKEN'))
 
5
  import requests
6
  import asyncio
7
  import subprocess
8
+ from dotenv import load_dotenv
9
 
10
+ # Load environment variables
11
+ load_dotenv()
12
+
13
+ # Logging setup
14
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', handlers=[logging.StreamHandler()])
15
 
16
+ # Intent setup
17
  intents = discord.Intents.default()
18
  intents.message_content = True
19
  intents.messages = True
20
  intents.guilds = True
21
  intents.guild_messages = True
22
 
23
+ # Inference API client setup
24
  hf_client = InferenceClient("meta-llama/Meta-Llama-3.1-70B-Instruct", token=os.getenv("HF_TOKEN"))
 
25
 
26
+ # Unsplash API setup
27
+ UNSPLASH_ACCESS_KEY = "QEtGo0U6vCZsZp8vDHzG21TXhuqjLScX7sMLHgSwnVM"
28
+ UNSPLASH_API_URL = "https://api.unsplash.com/search/photos"
29
 
30
+ # Specific channel ID
31
  SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
32
 
33
+ # Global variable to store conversation history
34
  conversation_history = []
35
 
36
  class MyClient(discord.Client):
 
43
  subprocess.Popen(["python", "web.py"])
44
  logging.info("Web.py server has been started.")
45
 
46
+ # Send a guide message when the bot starts
47
  channel = self.get_channel(SPECIFIC_CHANNEL_ID)
48
  if channel:
49
  await channel.send("찾고싢은 사진에 λŒ€ν•œ μ„€λͺ…을 ν•œ λ¬Έμž₯ λ‹¨μœ„λ‘œ μž…λ ₯ν•˜μ„Έμš”. 예) λˆˆλ°­μ— λ›°μ–΄ 놀고 μžˆλŠ” ν—ˆμŠ€ν‚€")
 
57
  return
58
  self.is_processing = True
59
  try:
60
+ # Extract English keywords from the meaning analysis
61
  keywords = await extract_keywords(message)
62
  if keywords:
63
+ # Search for high-resolution images using Unsplash API
64
  image_urls = await search_images(keywords)
65
  if image_urls:
66
+ # Create a thread with the requester and send high-resolution images
67
  await create_thread_and_send_images(message, keywords, image_urls)
68
  else:
69
  await message.channel.send(f"**{keywords}**에 λŒ€ν•œ 고해상도 이미지λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
 
73
  self.is_processing = False
74
 
75
  def is_message_in_specific_channel(self, message):
76
+ # Return True if the message is in the specified channel or in a thread of that channel
77
  return message.channel.id == SPECIFIC_CHANNEL_ID or (
78
  isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
79
  )
 
91
  response = await loop.run_in_executor(None, lambda: hf_client.chat_completion(
92
  messages, max_tokens=10, temperature=0.7, top_p=0.85))
93
 
94
+ # Parse Hugging Face response
95
  if response.choices and response.choices[0].message:
96
  keywords = response.choices[0].message['content'].strip()
97
  else:
 
101
 
102
  async def search_images(keywords):
103
  headers = {
104
+ "Authorization": f"Client-ID {UNSPLASH_ACCESS_KEY}"
105
  }
106
  params = {
107
  "query": keywords,
108
+ "per_page": 10 # Get up to 10 images
109
  }
110
+ response = requests.get(UNSPLASH_API_URL, headers=headers, params=params)
111
  if response.status_code == 200:
112
  data = response.json()
113
+ return [photo['urls']['regular'] for photo in data['results']]
114
+ logging.error(f"Unsplash API error: {response.status_code}, {response.text}")
115
  return None
116
 
117
  async def create_thread_and_send_images(message, keywords, image_urls):
118
+ # Create a thread
119
  thread = await message.channel.create_thread(name=f"{message.author.name}의 검색 κ²°κ³Ό", message=message)
120
  message_content = f"**{keywords}**에 λŒ€ν•œ 고해상도 이미지 {len(image_urls)}μž₯을 μ°Ύμ•˜μŠ΅λ‹ˆλ‹€:"
121
  await thread.send(message_content)
 
124
 
125
  if __name__ == "__main__":
126
  discord_client = MyClient(intents=intents)
127
+ discord_client.run(os.getenv('DISCORD_TOKEN'))