Pycharm – die besten Beiträge

Python Code testen

Ich habe einen Python code geschrieben und würde mich über ehrliche tester freuen

import os
#os.system('cls' if os.name == 'nt' else 'clear')
liste = []
def addToClipBoard(text):
    with open("temp_clipboard.txt", "w", encoding="utf-8") as f:
        f.write(text)
    os.system("type temp_clipboard.txt | clip")
    os.remove("temp_clipboard.txt")
def hinzufügen():
    produkt = input("Welches Produkt möchten sie hinzufügen ")
    anzahl = int(input(f"Wie oft möchten sie {produkt} kaufen "))
    add = [str(produkt), str(anzahl)]
    liste.append(add)
def anzeigen():
    for i in range(0, len(liste)):
        print(liste[i][0], liste[i][1])
def entfernen():
    print("Welches Produkt möchten sie entfernen ")
    for i in range(0, len(liste)):
        print(f"{i + 1}: ",liste[i][0], liste[i][1])
    auswahl = int(input("")) - 1
    os.system('cls' if os.name == 'nt' else 'clear')
    print("Produkt wurde entfernt!")
    del liste[auswahl]

while True:
    auswahl = int(input("1: Produkt hinzufügen \n2: Produkt entfernen \n3: Liste anzeigen \n4: Liste leeren \n5: Liste kopieren\n"))
    os.system('cls' if os.name == 'nt' else 'clear')

    if auswahl == 1:
        try:
            hinzufügen()
        except ValueError:
            print("Fehler!")
            continue
    elif auswahl == 2:
        try:
            entfernen()
        except IndexError:
            print("Fehler!")
            continue
    elif auswahl == 3:
        anzeigen()
        if liste == []:
            print("Deine Einkaufsliste ist leer")
            continue
    elif auswahl == 4:
        liste = []
        print("Liste wurde geleert!")
    elif auswahl == 5:
        outlist = str(liste)
        outlist = "\n".join([f"{produkt}: {anzahl}" for produkt, anzahl in liste])

        print("Liste wurde in die Zwischenablage kopiert")
        addToClipBoard(str(outlist))

Schreibt gerne eure meinung und startet das Programm im Terminal

Code, Programmiersprache, Python, Pycharm

Customtkinter?

Ist es normal dass das erstellen von Labels, Textfelder oder Buttons in Klassen als Vorlage super viel Schreibarbeit ist oder geht das auch eleganter und sauberer?

main:

maclass Main(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.main_window()
        self.chatbot_output = InputBox(self, 1, 1, 10, 10, "s", 500, 500, "#202222", "red", "white", "Gib einen Text ein...")
        self.chatbot_output.grid(row=1, column=1, pady=10, padx=10, sticky="s")
        self.chatbot_input = InputBox(self, 2, 1, 0, 10, "n", 500, 50, "#202222", "red", "white", "Gib einen Text ein...")
        self.chatbot_input.grid(row=2, column=1, pady=0, padx=10, sticky="n")
        self.placeholder = Label(self, 0, 1, 0, 10, "n", 500, 320, "transparent", "transparent", "white", ".")
        self.placeholder.grid(row=0, column=1, pady=0, padx=10, sticky="n")
    def main_window(self):
        height = 920
        width = 1680
        x = (self.winfo_screenwidth()//2)-(width//2)
        y = (self.winfo_screenheight()//2) - (height//2)
        self.geometry(f"{width}x{height}+{x}+{y}")
        self.title("YourTerminal")
        self.grid_columnconfigure(0, weight=0)
        self.grid_rowconfigure(0, weight=0)



if __name__ == "__main__":
    main = Main()
    main.mainloop()
    sys.exit()

Vorlage in einer Klasse und in einer anderen Datei:

class InputBox(ctk.CTkFrame):
    def __init__(self, master, row, column, pady, padx, sticky, width, height, entry_fg_color,frame_fg_color, textcolor, placeholder, *args, **kwargs):
        super().__init__(master, fg_color=frame_fg_color, *args, **kwargs)
        self.set_setup(row, column, pady, padx, sticky, width, height, entry_fg_color, textcolor, placeholder)

    def set_setup(self, row, column, pady, padx, sticky, width, height, entry_fg_color, textcolor, placeholder):
        self.input = ctk.CTkEntry(self,
                                  width=width,
                                  height=height,
                                  fg_color=entry_fg_color,
                                  text_color=textcolor,
                                  placeholder_text=placeholder,
                                  )
        self.input.grid(row=row, column=column, pady=pady, padx=padx, sticky=sticky)
Code, Programmiersprache, Python, Python 3, Tkinter, Pycharm

Python Fehlermeldung "KeyError: 'data'"?

Ich möchte gerne einen KI Discord Server machen. Die KI hab ich schon und diese hat auch eine API(?). Ich hab den Bot auch schon auf dem Server und ich kann auch Prompts eingeben. Aber wenn ich Prompt eingebe, kommt bei diesem Code:

import discord
from gradio_client import Client


TOKEN = 'MeinToken'
FOOOCUS_API_URL = 'http://127.0.0.1:7865/'


fooocus_client = Client(FOOOCUS_API_URL)


intents = discord.Intents.default()
client = discord.Client(intents=intents)


@client.event
async def on_ready():
    print(f'{client.user} ist eingeloggt!')


@client.event
async def on_message(message):
    if message.channel.name == 'prompt-kanal' and message.author != client.user:
        result = fooocus_client.predict(message.content, fn_index=2)
        await message.channel.send(file=discord.File(result))


client.run(TOKEN)

Diese Fehlermeldung:

2024-04-16 15:35:07 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:...\venv\Lib\site-packages\gradio_client\compatibility.py", line 105, in _predict
output = result["data"]
~~~~~~^^^^^^^^
KeyError: 'data'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:...\venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:...\bot.py", line 19, in on_message
result = fooocus_client.predict(message.content, fn_index=2)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:...\venv\Lib\site-packages\gradio_client\client.py", line 459, in predict
).result()
^^^^^^^^
File "C:...\venv\Lib\site-packages\gradio_client\client.py", line 1374, in result
return super().result(timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users..._base.py", line 456, in result
return self.__get_result()
^^^^^^^^^^^^^^^^^^^
File "C:\Users..._base.py", line 401, in __get_result
raise self._exception
File "C:\Users...\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:...\compatibility.py", line 65, in _inner
predictions = _predict(*data)
^^^^^^^^^^^^^^^
File "C:...\compatibility.py", line 119, in _predict
raise KeyError(
KeyError: 'Could not find 'data' key in response. Response received: {'detail': [{'type': 'model_attributes_type', 'loc': ['body'], 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': '{"data": [""], "fn_index": 2, "session_hash": "d7f62bf0-174c-45fe-b3f6-c5e7f00848d3"}', 'url': 'https://errors.pydantic.dev/2.1/v/model_attributes_type'}]}'

Ich checke einfach nicht, woran das liegen könnte...

Linux, Bot, cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Pycharm, Discord, Discord Bot, ChatGPT

Meistgelesene Beiträge zum Thema Pycharm