Changed action #5

Merged
wirehack7 merged 2 commits from dev into main 2025-05-01 14:13:16 +02:00
Owner

Changed action

Changed action
wirehack7 added 2 commits 2025-05-01 14:12:07 +02:00
Reviewed-on: #4
changed github action
Some checks failed
Safety Check / safety-check (pull_request) Successful in -1s
Code Quality Check / quality-check (pull_request) Failing after 14s
3564a1db62
First-time contributor

🛡️ Code Quality Report

🔍 black

--- /workspace/wirehack7/novelai-bot/src/main.py	2025-05-01 12:11:56.300000+00:00
+++ /workspace/wirehack7/novelai-bot/src/main.py	2025-05-01 12:12:01.504904+00:00
@@ -9,79 +9,88 @@
 from discord.ext import commands
 import requests
 
 NOVELAI_API_TOKEN = os.getenv("NOVELAI_API_TOKEN")
 BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
-ALLOWED_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID", "0"))  # falls nicht gesetzt → 0
+ALLOWED_CHANNEL_ID = int(
+    os.getenv("DISCORD_CHANNEL_ID", "0")
+)  # falls nicht gesetzt → 0
 
 logging.basicConfig(
     stream=sys.stdout,
     level=logging.INFO,
-    format="%(asctime)s - %(levelname)s - %(message)s"
+    format="%(asctime)s - %(levelname)s - %(message)s",
 )
 
 logger = logging.getLogger(__name__)
 
 if not all([NOVELAI_API_TOKEN, BOT_TOKEN, ALLOWED_CHANNEL_ID]):
-    raise ValueError("Environment-Variablen NOVELAI_API_TOKEN, DISCORD_BOT_TOKEN und DISCORD_CHANNEL_ID müssen gesetzt sein.")
+    raise ValueError(
+        "Environment-Variablen NOVELAI_API_TOKEN, DISCORD_BOT_TOKEN und DISCORD_CHANNEL_ID müssen gesetzt sein."
+    )
 
 intents = discord.Intents.default()
 bot = commands.Bot(command_prefix=commands.when_mentioned, intents=intents)
+
 
 @bot.event
 async def on_ready():
     print(f"Bot started as {bot.user}")
     try:
         synced = await bot.tree.sync()
         logging.info(f"{len(synced)} Slash-Commands synchronized.")
     except Exception as e:
         logging.error(e)
 
+
 @bot.tree.command(name="generate", description="Generate image with NovelAI v4 Full")
 @app_commands.describe(
     prompt="What should be generated?",
     undesired_prompt="What should be avoided? (optional)",
     orientation="portrait or landscape (Standard: portrait)",
-    seed="Optional seed (integer). If empty, a random one will be generated"
+    seed="Optional seed (integer). If empty, a random one will be generated",
 )
 async def generate(
     interaction: discord.Interaction,
     prompt: str,
     undesired_prompt: str = "",
     orientation: str = "portrait",
-    seed: int = None
+    seed: int = None,
 ):
-    
+
     default_negative = (
         "blurry, lowres, error, film grain, scan artifacts, worst quality, bad quality, jpeg artifacts, "
         "very displeasing, chromatic aberration, multiple views, logo, too many watermarks, white blank page, "
         "blank page, watermarks, watermark, text, "
     )
-    
+
     if interaction.channel.id != ALLOWED_CHANNEL_ID:
         await interaction.response.send_message(
-            "This command isn't allowed here.",
-            ephemeral=True
+            "This command isn't allowed here.", ephemeral=True
         )
         return
-    
+
     MAX_PROMPT_LENGTH = 500
 
     if len(prompt) > MAX_PROMPT_LENGTH:
-        await interaction.followup.send(f"Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed.")
+        await interaction.followup.send(
+            f"Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed."
+        )
         return
 
     if len(default_negative + undesired_prompt.strip()) > MAX_PROMPT_LENGTH:
-        await interaction.followup.send(f"Negative Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed.")
+        await interaction.followup.send(
+            f"Negative Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed."
+        )
         return
 
     await interaction.response.defer(thinking=True)
     logger.info(
         "User %s (%s, %s) requested image",
         interaction.user.display_name,
         interaction.user.name,
-        interaction.user.id
+        interaction.user.id,
     )
 
     # Auflösung wählen
     if orientation.lower() == "landscape":
         width, height = 1216, 832
@@ -119,40 +128,37 @@
             "legacy_uc": False,
             "normalize_reference_strength_multiple": True,
             "seed": seed,
             "characterPrompts": [],
             "v4_prompt": {
-                "caption": {
-                    "base_caption": prompt,
-                    "char_captions": []
-                },
+                "caption": {"base_caption": prompt, "char_captions": []},
                 "use_coords": False,
-                "use_order": True
+                "use_order": True,
             },
             "v4_negative_prompt": {
                 "caption": {
                     "base_caption": default_negative + undesired_prompt.strip(),
-                    "char_captions": []
+                    "char_captions": [],
                 },
-                "legacy_uc": False
+                "legacy_uc": False,
             },
             "negative_prompt": default_negative + undesired_prompt.strip(),
             "deliberate_euler_ancestral_bug": False,
-            "prefer_brownian": True
-        }
+            "prefer_brownian": True,
+        },
     }
 
     headers = {
         "Authorization": f"Bearer {NOVELAI_API_TOKEN}",
-        "Content-Type": "application/json"
+        "Content-Type": "application/json",
     }
 
     response = requests.post(
         "https://image.novelai.net/ai/generate-image",
         json=payload,
         headers=headers,
-        timeout=120
+        timeout=120,
     )
 
     if response.status_code == 200:
         response_bytes = response.content
 
@@ -164,37 +170,35 @@
 Steps: 28
 Scale: 3.7
 Model: nai-diffusion-4-full```"""
 
         # Prüfen ob ZIP (PK am Anfang)
-        if response_bytes[:2] == b'PK':
+        if response_bytes[:2] == b"PK":
             # ZIP-Archiv entpacken
             with zipfile.ZipFile(io.BytesIO(response_bytes)) as zip_file:
                 namelist = zip_file.namelist()
                 # Erstes PNG suchen
-                image_name = next((name for name in namelist if name.endswith(".png")), None)
+                image_name = next(
+                    (name for name in namelist if name.endswith(".png")), None
+                )
 
                 if image_name:
                     image_bytes = zip_file.read(image_name)
                     filename = "novelai.png"
                     file = discord.File(io.BytesIO(image_bytes), filename=filename)
                     await interaction.followup.send(content=param_text, file=file)
                 else:
-                    await interaction.followup.send(
-                        "Found no PNG inside archive"
-                    )
-
-        elif response_bytes[:4] == b'\x89PNG':
+                    await interaction.followup.send("Found no PNG inside archive")
+
+        elif response_bytes[:4] == b"\x89PNG":
             # Direkte PNG-Rückgabe
             filename = "novelai.png"
             file = discord.File(io.BytesIO(response_bytes), filename=filename)
             await interaction.followup.send(content=param_text, file=file)
 
         else:
-            await interaction.followup.send(
-                "API didn't send any file"
-            )
+            await interaction.followup.send("API didn't send any file")
 
     else:
         try:
             error_data = response.json()
         except Exception:
@@ -204,6 +208,7 @@
         for key, value in error_data.items():
             error_message += f"**{key}**: {value}\n"
 
         await interaction.followup.send(error_message)
 
+
 bot.run(BOT_TOKEN)
would reformat /workspace/wirehack7/novelai-bot/src/main.py

Oh no! 💥 💔 💥
1 file would be reformatted.

🔍 isort

ERROR: /workspace/wirehack7/novelai-bot/src/main.py Imports are incorrectly sorted and/or formatted.
--- /workspace/wirehack7/novelai-bot/src/main.py:before	2025-05-01 12:11:56.300000
+++ /workspace/wirehack7/novelai-bot/src/main.py:after	2025-05-01 12:12:01.979051
@@ -1,13 +1,14 @@
 import io
+import logging
 import os
+import random
 import sys
-import random
 import zipfile
-import logging
+
 import discord
+import requests
 from discord import app_commands
 from discord.ext import commands
-import requests
 
 NOVELAI_API_TOKEN = os.getenv("NOVELAI_API_TOKEN")
 BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
Skipped 1 files

🔍 pylint

************* Module src.main
src/main.py:25:0: C0301: Line too long (126/100) (line-too-long)
src/main.py:53:0: C0303: Trailing whitespace (trailing-whitespace)
src/main.py:55:0: C0301: Line too long (105/100) (line-too-long)
src/main.py:56:0: C0301: Line too long (111/100) (line-too-long)
src/main.py:59:0: C0303: Trailing whitespace (trailing-whitespace)
src/main.py:66:0: C0303: Trailing whitespace (trailing-whitespace)
src/main.py:70:0: C0301: Line too long (103/100) (line-too-long)
src/main.py:74:0: C0301: Line too long (112/100) (line-too-long)
src/main.py:1:0: C0114: Missing module docstring (missing-module-docstring)
src/main.py:31:0: C0116: Missing function or method docstring (missing-function-docstring)
src/main.py:36:11: W0718: Catching too general exception Exception (broad-exception-caught)
src/main.py:35:8: W1203: Use lazy % formatting in logging functions (logging-fstring-interpolation)
src/main.py:46:0: C0116: Missing function or method docstring (missing-function-docstring)
src/main.py:46:0: R0914: Too many local variables (24/15) (too-many-locals)
src/main.py:67:4: C0103: Variable name "MAX_PROMPT_LENGTH" doesn't conform to snake_case naming style (invalid-name)
src/main.py:200:15: W0718: Catching too general exception Exception (broad-exception-caught)
src/main.py:46:0: R0912: Too many branches (15/12) (too-many-branches)

-----------------------------------
Your code has been rated at 7.73/10

🔍 flake8

./src/main.py:14:80: E501 line too long (89 > 79 characters)
./src/main.py:25:80: E501 line too long (126 > 79 characters)
./src/main.py:30:1: E302 expected 2 blank lines, found 1
./src/main.py:39:1: E302 expected 2 blank lines, found 1
./src/main.py:39:80: E501 line too long (85 > 79 characters)
./src/main.py:53:1: W293 blank line contains whitespace
./src/main.py:55:80: E501 line too long (105 > 79 characters)
./src/main.py:56:80: E501 line too long (111 > 79 characters)
./src/main.py:59:1: W293 blank line contains whitespace
./src/main.py:66:1: W293 blank line contains whitespace
./src/main.py:70:80: E501 line too long (103 > 79 characters)
./src/main.py:74:80: E501 line too long (112 > 79 characters)
./src/main.py:133:80: E501 line too long (80 > 79 characters)
./src/main.py:174:80: E501 line too long (93 > 79 characters)
./src/main.py:179:80: E501 line too long (83 > 79 characters)
./src/main.py:180:80: E501 line too long (82 > 79 characters)
<!-- add-pr-comment:add-pr-comment --> ### 🛡️ Code Quality Report #### 🔍 black ``` --- /workspace/wirehack7/novelai-bot/src/main.py 2025-05-01 12:11:56.300000+00:00 +++ /workspace/wirehack7/novelai-bot/src/main.py 2025-05-01 12:12:01.504904+00:00 @@ -9,79 +9,88 @@ from discord.ext import commands import requests NOVELAI_API_TOKEN = os.getenv("NOVELAI_API_TOKEN") BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN") -ALLOWED_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID", "0")) # falls nicht gesetzt → 0 +ALLOWED_CHANNEL_ID = int( + os.getenv("DISCORD_CHANNEL_ID", "0") +) # falls nicht gesetzt → 0 logging.basicConfig( stream=sys.stdout, level=logging.INFO, - format="%(asctime)s - %(levelname)s - %(message)s" + format="%(asctime)s - %(levelname)s - %(message)s", ) logger = logging.getLogger(__name__) if not all([NOVELAI_API_TOKEN, BOT_TOKEN, ALLOWED_CHANNEL_ID]): - raise ValueError("Environment-Variablen NOVELAI_API_TOKEN, DISCORD_BOT_TOKEN und DISCORD_CHANNEL_ID müssen gesetzt sein.") + raise ValueError( + "Environment-Variablen NOVELAI_API_TOKEN, DISCORD_BOT_TOKEN und DISCORD_CHANNEL_ID müssen gesetzt sein." + ) intents = discord.Intents.default() bot = commands.Bot(command_prefix=commands.when_mentioned, intents=intents) + @bot.event async def on_ready(): print(f"Bot started as {bot.user}") try: synced = await bot.tree.sync() logging.info(f"{len(synced)} Slash-Commands synchronized.") except Exception as e: logging.error(e) + @bot.tree.command(name="generate", description="Generate image with NovelAI v4 Full") @app_commands.describe( prompt="What should be generated?", undesired_prompt="What should be avoided? (optional)", orientation="portrait or landscape (Standard: portrait)", - seed="Optional seed (integer). If empty, a random one will be generated" + seed="Optional seed (integer). If empty, a random one will be generated", ) async def generate( interaction: discord.Interaction, prompt: str, undesired_prompt: str = "", orientation: str = "portrait", - seed: int = None + seed: int = None, ): - + default_negative = ( "blurry, lowres, error, film grain, scan artifacts, worst quality, bad quality, jpeg artifacts, " "very displeasing, chromatic aberration, multiple views, logo, too many watermarks, white blank page, " "blank page, watermarks, watermark, text, " ) - + if interaction.channel.id != ALLOWED_CHANNEL_ID: await interaction.response.send_message( - "This command isn't allowed here.", - ephemeral=True + "This command isn't allowed here.", ephemeral=True ) return - + MAX_PROMPT_LENGTH = 500 if len(prompt) > MAX_PROMPT_LENGTH: - await interaction.followup.send(f"Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed.") + await interaction.followup.send( + f"Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed." + ) return if len(default_negative + undesired_prompt.strip()) > MAX_PROMPT_LENGTH: - await interaction.followup.send(f"Negative Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed.") + await interaction.followup.send( + f"Negative Prompt too long! Maximum {MAX_PROMPT_LENGTH} chars allowed." + ) return await interaction.response.defer(thinking=True) logger.info( "User %s (%s, %s) requested image", interaction.user.display_name, interaction.user.name, - interaction.user.id + interaction.user.id, ) # Auflösung wählen if orientation.lower() == "landscape": width, height = 1216, 832 @@ -119,40 +128,37 @@ "legacy_uc": False, "normalize_reference_strength_multiple": True, "seed": seed, "characterPrompts": [], "v4_prompt": { - "caption": { - "base_caption": prompt, - "char_captions": [] - }, + "caption": {"base_caption": prompt, "char_captions": []}, "use_coords": False, - "use_order": True + "use_order": True, }, "v4_negative_prompt": { "caption": { "base_caption": default_negative + undesired_prompt.strip(), - "char_captions": [] + "char_captions": [], }, - "legacy_uc": False + "legacy_uc": False, }, "negative_prompt": default_negative + undesired_prompt.strip(), "deliberate_euler_ancestral_bug": False, - "prefer_brownian": True - } + "prefer_brownian": True, + }, } headers = { "Authorization": f"Bearer {NOVELAI_API_TOKEN}", - "Content-Type": "application/json" + "Content-Type": "application/json", } response = requests.post( "https://image.novelai.net/ai/generate-image", json=payload, headers=headers, - timeout=120 + timeout=120, ) if response.status_code == 200: response_bytes = response.content @@ -164,37 +170,35 @@ Steps: 28 Scale: 3.7 Model: nai-diffusion-4-full```""" # Prüfen ob ZIP (PK am Anfang) - if response_bytes[:2] == b'PK': + if response_bytes[:2] == b"PK": # ZIP-Archiv entpacken with zipfile.ZipFile(io.BytesIO(response_bytes)) as zip_file: namelist = zip_file.namelist() # Erstes PNG suchen - image_name = next((name for name in namelist if name.endswith(".png")), None) + image_name = next( + (name for name in namelist if name.endswith(".png")), None + ) if image_name: image_bytes = zip_file.read(image_name) filename = "novelai.png" file = discord.File(io.BytesIO(image_bytes), filename=filename) await interaction.followup.send(content=param_text, file=file) else: - await interaction.followup.send( - "Found no PNG inside archive" - ) - - elif response_bytes[:4] == b'\x89PNG': + await interaction.followup.send("Found no PNG inside archive") + + elif response_bytes[:4] == b"\x89PNG": # Direkte PNG-Rückgabe filename = "novelai.png" file = discord.File(io.BytesIO(response_bytes), filename=filename) await interaction.followup.send(content=param_text, file=file) else: - await interaction.followup.send( - "API didn't send any file" - ) + await interaction.followup.send("API didn't send any file") else: try: error_data = response.json() except Exception: @@ -204,6 +208,7 @@ for key, value in error_data.items(): error_message += f"**{key}**: {value}\n" await interaction.followup.send(error_message) + bot.run(BOT_TOKEN) would reformat /workspace/wirehack7/novelai-bot/src/main.py Oh no! 💥 💔 💥 1 file would be reformatted. ``` #### 🔍 isort ``` ERROR: /workspace/wirehack7/novelai-bot/src/main.py Imports are incorrectly sorted and/or formatted. --- /workspace/wirehack7/novelai-bot/src/main.py:before 2025-05-01 12:11:56.300000 +++ /workspace/wirehack7/novelai-bot/src/main.py:after 2025-05-01 12:12:01.979051 @@ -1,13 +1,14 @@ import io +import logging import os +import random import sys -import random import zipfile -import logging + import discord +import requests from discord import app_commands from discord.ext import commands -import requests NOVELAI_API_TOKEN = os.getenv("NOVELAI_API_TOKEN") BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN") Skipped 1 files ``` #### 🔍 pylint ``` ************* Module src.main src/main.py:25:0: C0301: Line too long (126/100) (line-too-long) src/main.py:53:0: C0303: Trailing whitespace (trailing-whitespace) src/main.py:55:0: C0301: Line too long (105/100) (line-too-long) src/main.py:56:0: C0301: Line too long (111/100) (line-too-long) src/main.py:59:0: C0303: Trailing whitespace (trailing-whitespace) src/main.py:66:0: C0303: Trailing whitespace (trailing-whitespace) src/main.py:70:0: C0301: Line too long (103/100) (line-too-long) src/main.py:74:0: C0301: Line too long (112/100) (line-too-long) src/main.py:1:0: C0114: Missing module docstring (missing-module-docstring) src/main.py:31:0: C0116: Missing function or method docstring (missing-function-docstring) src/main.py:36:11: W0718: Catching too general exception Exception (broad-exception-caught) src/main.py:35:8: W1203: Use lazy % formatting in logging functions (logging-fstring-interpolation) src/main.py:46:0: C0116: Missing function or method docstring (missing-function-docstring) src/main.py:46:0: R0914: Too many local variables (24/15) (too-many-locals) src/main.py:67:4: C0103: Variable name "MAX_PROMPT_LENGTH" doesn't conform to snake_case naming style (invalid-name) src/main.py:200:15: W0718: Catching too general exception Exception (broad-exception-caught) src/main.py:46:0: R0912: Too many branches (15/12) (too-many-branches) ----------------------------------- Your code has been rated at 7.73/10 ``` #### 🔍 flake8 ``` ./src/main.py:14:80: E501 line too long (89 > 79 characters) ./src/main.py:25:80: E501 line too long (126 > 79 characters) ./src/main.py:30:1: E302 expected 2 blank lines, found 1 ./src/main.py:39:1: E302 expected 2 blank lines, found 1 ./src/main.py:39:80: E501 line too long (85 > 79 characters) ./src/main.py:53:1: W293 blank line contains whitespace ./src/main.py:55:80: E501 line too long (105 > 79 characters) ./src/main.py:56:80: E501 line too long (111 > 79 characters) ./src/main.py:59:1: W293 blank line contains whitespace ./src/main.py:66:1: W293 blank line contains whitespace ./src/main.py:70:80: E501 line too long (103 > 79 characters) ./src/main.py:74:80: E501 line too long (112 > 79 characters) ./src/main.py:133:80: E501 line too long (80 > 79 characters) ./src/main.py:174:80: E501 line too long (93 > 79 characters) ./src/main.py:179:80: E501 line too long (83 > 79 characters) ./src/main.py:180:80: E501 line too long (82 > 79 characters) ```
wirehack7 merged commit 422a77e07f into main 2025-05-01 14:13:16 +02:00
Sign in to join this conversation.
No Reviewers
No Label
2 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: wirehack7/novelai-bot#5
No description provided.