Z3ktrix commited on
Commit
ae1e871
Β·
verified Β·
1 Parent(s): e4934d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -38
app.py CHANGED
@@ -6,6 +6,8 @@ import discord
6
  from discord.ext import commands
7
  from dotenv import load_dotenv
8
  import logging
 
 
9
 
10
  # Load environment variables from the .env file
11
  load_dotenv()
@@ -13,7 +15,7 @@ load_dotenv()
13
  DISCORD_TOKEN = os.getenv('dsTOK')
14
  HF_API_KEY = os.getenv('HFREAD')
15
 
16
- API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
17
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
18
 
19
  # Set up logging
@@ -21,29 +23,14 @@ logging.basicConfig(level=logging.INFO)
21
  logger = logging.getLogger(__name__)
22
 
23
  # Function to query the Hugging Face model with a structured prompt
24
- def query_huggingface(prompt, temperature=0.5, max_tokens=100, top_k=50, top_p=0.9):
25
- payload = {
26
- "inputs": prompt,
27
- "parameters": {
28
- "temperature": temperature,
29
- "max_new_tokens": max_tokens,
30
- "top_k": top_k,
31
- "top_p": top_p
32
- }
33
- }
34
  try:
35
  response = requests.post(API_URL, headers=headers, json=payload)
36
  response.raise_for_status()
37
- result = response.json()
38
- if isinstance(result, list) and len(result) > 0 and 'generated_text' in result[0]:
39
- return result[0]['generated_text']
40
- elif 'generated_text' in result:
41
- return result['generated_text']
42
- else:
43
- return "No response generated."
44
  except requests.exceptions.RequestException as e:
45
  logger.error(f"Error querying the API: {e}")
46
- return f"Error: {str(e)}"
47
 
48
  # Initialize the Discord bot with a default prefix
49
  intents = discord.Intents.default()
@@ -56,36 +43,37 @@ bot = commands.Bot(command_prefix=commands.when_mentioned_or(default_prefix), in
56
  async def on_ready():
57
  logger.info(f'Bot is ready. Logged in as {bot.user}')
58
 
59
- @bot.command(name='ask')
60
  @commands.cooldown(rate=1, per=10, type=commands.BucketType.user)
61
- async def ask(ctx, *question):
62
  """
63
- Command to ask a question to the Hugging Face model with an instructive prompt.
64
  """
65
- if not question:
66
- await ctx.send("You need to ask a question.")
67
  return
68
 
69
- question = " ".join(question)
70
  try:
71
- # Create a structured prompt
72
- prompt = f"Answer the following question accurately and concisely: {question}"
73
- response = query_huggingface(prompt, temperature=0.8, max_tokens=1000, top_k=70, top_p=0.4)
74
-
75
- # Extract and clean the response
76
- clean_response = response.replace(prompt, '').strip()
77
-
78
- await ctx.send(clean_response)
 
79
  except Exception as e:
80
- logger.error(f"Error processing the ask command: {e}")
81
  await ctx.send("An error occurred while processing your request.")
82
 
83
- @ask.error
84
- async def ask_error(ctx, error):
85
  if isinstance(error, commands.CommandOnCooldown):
86
  await ctx.send(f"This command is on cooldown. Please try again after {int(error.retry_after)} seconds.")
87
  else:
88
- logger.error(f"Error in ask command: {error}")
89
  await ctx.send("An error occurred. Please try again later.")
90
 
91
  @bot.command(name='setprefix')
@@ -98,7 +86,7 @@ async def set_prefix(ctx, prefix: str):
98
  async def help_custom(ctx):
99
  help_text = (
100
  "Here are the commands you can use:\n"
101
- "!ask <question> - Ask a question to the AI model.\n"
102
  "!setprefix <prefix> - Change the command prefix (admin only).\n"
103
  "!help_custom - Display this help message."
104
  )
@@ -107,3 +95,4 @@ async def help_custom(ctx):
107
  # Run the bot
108
  bot.run(DISCORD_TOKEN)
109
 
 
 
6
  from discord.ext import commands
7
  from dotenv import load_dotenv
8
  import logging
9
+ import io
10
+ from PIL import Image
11
 
12
  # Load environment variables from the .env file
13
  load_dotenv()
 
15
  DISCORD_TOKEN = os.getenv('dsTOK')
16
  HF_API_KEY = os.getenv('HFREAD')
17
 
18
+ API_URL = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
19
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
20
 
21
  # Set up logging
 
23
  logger = logging.getLogger(__name__)
24
 
25
  # Function to query the Hugging Face model with a structured prompt
26
+ def query(payload):
 
 
 
 
 
 
 
 
 
27
  try:
28
  response = requests.post(API_URL, headers=headers, json=payload)
29
  response.raise_for_status()
30
+ return response.content
 
 
 
 
 
 
31
  except requests.exceptions.RequestException as e:
32
  logger.error(f"Error querying the API: {e}")
33
+ return None
34
 
35
  # Initialize the Discord bot with a default prefix
36
  intents = discord.Intents.default()
 
43
  async def on_ready():
44
  logger.info(f'Bot is ready. Logged in as {bot.user}')
45
 
46
+ @bot.command(name='generate')
47
  @commands.cooldown(rate=1, per=10, type=commands.BucketType.user)
48
+ async def generate(ctx, *description):
49
  """
50
+ Command to generate an image based on a description using the Hugging Face model.
51
  """
52
+ if not description:
53
+ await ctx.send("You need to provide a description for the image.")
54
  return
55
 
56
+ description = " ".join(description)
57
  try:
58
+ payload = {"inputs": description}
59
+ image_bytes = query(payload)
60
+
61
+ if image_bytes:
62
+ image = Image.open(io.BytesIO(image_bytes))
63
+ image.save("generated_image.png")
64
+ await ctx.send(file=discord.File("generated_image.png"))
65
+ else:
66
+ await ctx.send("An error occurred while generating the image.")
67
  except Exception as e:
68
+ logger.error(f"Error processing the generate command: {e}")
69
  await ctx.send("An error occurred while processing your request.")
70
 
71
+ @generate.error
72
+ async def generate_error(ctx, error):
73
  if isinstance(error, commands.CommandOnCooldown):
74
  await ctx.send(f"This command is on cooldown. Please try again after {int(error.retry_after)} seconds.")
75
  else:
76
+ logger.error(f"Error in generate command: {error}")
77
  await ctx.send("An error occurred. Please try again later.")
78
 
79
  @bot.command(name='setprefix')
 
86
  async def help_custom(ctx):
87
  help_text = (
88
  "Here are the commands you can use:\n"
89
+ "!generate <description> - Generate an image based on the description.\n"
90
  "!setprefix <prefix> - Change the command prefix (admin only).\n"
91
  "!help_custom - Display this help message."
92
  )
 
95
  # Run the bot
96
  bot.run(DISCORD_TOKEN)
97
 
98
+