Pycharm – die meistgelesenen Beiträge

Wo kann ich Tokens für GPT-4 kaufen?

Hallo,

ich programmiere gerade einen Sprachassistenten und wollte ihn nun mit GPT-4 verbinden, ich habe auf Shop - ChatGPT 50000 Tokens gekauft, doch wenn ich das Programm starte, steht, dass ich trotzdem keinen Zugriff auf GPT-4 habe. Muss ich die Tokens irgendwo anders kaufen?

Mein Code:

import openai
import pyttsx3
import re
import pyjokes
import speech_recognition as sr
from pyowm import OWM
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import time
import random
import datetime
import pytz
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder


openai.api_key = 'sk-...'
model_id = "gpt-4"

engine = pyttsx3.init()


def recognize_speech():
    recognizer = sr.Recognizer()

    while True:
        with sr.Microphone() as source:
            print("Sage etwas...")
            audio = recognizer.listen(source, timeout=15)

        try:
            text = recognizer.recognize_google(audio, language="de-DE")
            print("Text: " + text)
            return text
        except sr.UnknownValueError:
            return "not_understood"
        except sr.RequestError as e:
            print(f"Fehler bei der Anfrage an die Google Web Speech API: {e}")
            return ""


def openai_request(prompt):
    response = openai.ChatCompletion.create(
        model=model_id,
        messages=prompt
    )

    api_usage = response['usage']
    print('Total Token consumed: {0}'.format(api_usage['total_tokens']))
    prompt.append({'role': response.choices[0].message.role, 'content': response.choices[0].message.content})
    return prompt


def speak(text):
    engine.say(text)
    engine.runAndWait()


def ausführen():
    while True:
        q = recognize_speech()
        print("Erkannter Text:", q)

        if q == "not_understood":
            speak("Entschuldigung! Das habe ich nicht verstanden.")
            break

        elif not q:
            break

        elif "hallo" in q:
            speak('Hallo! Womit kann ich dir behilflich sein?')
            break

        else:
            prompt = [{'role': 'user', 'content': q}]
            prompt = openai_request(prompt)
            response = prompt[-1]['content']
            speak(response)


if __name__ == '__main__':
    ausführen()

Fehlercode:

C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Scripts\python.exe C:\Users\User\PycharmProjects\voiceAssistant\main.py 

Sage etwas...

Text: wann war der erste Weltkrieg

Erkannter Text: wann war der erste Weltkrieg

Traceback (most recent call last):

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 83, in <module>

  ausführen()

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 77, in ausführen

  prompt = openai_request(prompt)

       ^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 43, in openai_request

  response = openai.ChatCompletion.create(

        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\openai\api_resources\chat_completion.py", line 25, in create

  return super().create(*args, **kwargs)

      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\openai\api_resources\abstract\engine_api_resource.py", line 153, in create

  response, _, api_key = requestor.request(

              ^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\openai\api_requestor.py", line 298, in request

  resp, got_stream = self._interpret_response(result, stream)

            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\openai\api_requestor.py", line 700, in _interpret_response

  self._interpret_response_line(

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\openai\api_requestor.py", line 765, in _interpret_response_line

  raise self.handle_error_response(

openai.error.InvalidRequestError: The model `gpt-4` does not exist or you do not have access to it. Learn more: https://help.openai.com/en/articles/7102672-how-can-i-access-gpt-4.

Process finished with exit code 1

Freundliche Grüsse

kaufen, Code, Error, künstliche Intelligenz, Programmiersprache, Python, Python 3, token, Sprachassistent, Pycharm, ChatGPT

Warum kann ich bei PyCharm keine interpreter installieren?

Hey ich versuche über Pycharm einen Discord Bot zu programmieren allerdings seit ich meinen pc zurückgesetzt habe kann ich keine interpreter installieren.

Egal ob über das Terminal oder über die Einstellungen, denn es kommt immer diese Fehlermeldung:
``` (venv) leonmt12345@penguin:~/PycharmProjects/bittepycharm$ pip install py-cord == 2.3.2

Traceback (most recent call last):

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/bin/pip", line 5, in <module>

from pip._internal.cli.main import main

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/cli/main.py", line 9, in <module>

from pip._internal.cli.autocompletion import autocomplete

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py", line 10, in <module>

from pip._internal.cli.main_parser import create_main_parser

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py", line 8, in <module>

from pip._internal.cli import cmdoptions

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/cli/cmdoptions.py", line 23, in <module>

from pip._internal.cli.parser import ConfigOptionParser

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/cli/parser.py", line 12, in <module>

from pip._internal.configuration import Configuration, ConfigurationError

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/configuration.py", line 26, in <module>

from pip._internal.utils.logging import getLogger

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/utils/logging.py", line 13, in <module>

from pip._internal.utils.misc import ensure_dir

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/utils/misc.py", line 40, in <module>

from pip._internal.locations import get_major_minor_version, site_packages, user_site

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/locations/__init__.py", line 14, in <module>

from . import _distutils, _sysconfig

File "/home/leonmt12345/PycharmProjects/bittepycharm/venv/lib/python3.9/site-packages/pip/_internal/locations/_distutils.py", line 9, in <module>

from distutils.cmd import Command as DistutilsCommand

ModuleNotFoundError: No module named 'distutils.cmd'```
Ich bin auf Linux wenn das irgenwie hilft.

Linux, Python, Pycharm, Discord, Discord Bot

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

TypeError: can only concatenate str (not "function") to str?

ich möchte eine ui für mailtm erstellen aber bekomme kein output raus also wenn email ankommen werden sie nicht angezeigt und wenn ich listener eingebe bekomme ich jedes mal den gleichen fehler code

Fehler code:

TypeError: can only concatenate str (not "function") to str

from mailtm import *


def listener(message):
    print("\nSubject: " + message['subject'] + str(listener))
    print("Content: " + message['text'] if message['text'] else message['html'] + str(listener))


test = Email()
print("\nDomain: " + test.domain)

test.register()
print("\nEmail Adress: " + str(test.address))


test.start(listener, interval=3)
print("\nHab Sabr.....")


main = ctk.CTk()
main.geometry("500x320")
main.title("Temp mail By Amjn")


emaila = ctk.CTkEntry(main, placeholder_text="         " + test.address, width=900, font=("Helvetica", 20))
emaila.configure(state="readonly")
emaila._corner_radius = 10
emaila.pack()


Copyt = ctk.CTkLabel(main, text="Copy Email", font=("Helvetica", 20))
Copyt.pack()


def neuw(self=None):
    neu = ctk.CTkToplevel(main)
    neu.title("Emails              (MADE BY AMJN)")
    neu.geometry("500x320")
    neu.corner_radius = 30
    neu.resizable(width=True, height=True)

    Ausg = ctk.CTkEntry(neuw, placeholder_text=("         ") + listener, width=900, font=("Helvetica", 20))
    Ausg.pack()


knopf = ctk.CTkButton(main, text="Emails", font=("Helvetica", 20), command=neuw)
knopf.pack(pady=20)

main.mainloop()
Code, Programmiersprache, Python, UI, Python 3, Tkinter, Pycharm

Warum ist dieser Code so schlecht /funktioniert fast nicht?

Hallo, ich bin an einem Sprachassistenten dran und bin gerade bei der "Speech-to-Text" Funktion. Das ist mein bisheriger Code:

import speech_recognition as sr


def aufnahme():
    r = sr.Recognizer()

    with sr.Microphone() as quelle:
        r.pause_threshold = 0.8
        r.adjust_for_ambient_noise(quelle)
        gesagt = r.listen(quelle)

    try:

        q = r.recognize_google(gesagt, language="de")
        print("Recognized speech (Google):", q)
        return q

    except sr.UnknownValueError:
        print('Leider nicht verstanden (Google)')
        print("Recognized speech (Google):", r.recognize_google(gesagt, show_all=True, language="de"))

    except sr.RequestError as e:
        print(f'Fehler bei Sphinx-Erkennung: {e}')
        return "Ich warte auf Anweisungen"


# Call the function
result = aufnahme()
print(result)

Jedoch funktioniert er richtig schlecht, er versteht höchstens zwei Wörter und in 90% der Fälle kommt dieser Fehlercode:

Leider nicht verstanden (Google)

Traceback (most recent call last):

 File "C:\Users\...\PycharmProjects\voiceAssistant\main.py", line 21, in aufnahme

  q = r.recognize_google(gesagt, language="de")

 File "C:\Users\...\lib\site-packages\speech_recognition\recognizers\google.py", line 251, in recognize_legacy

  return output_parser.parse(response_text)

 File "C:\Users\...\lib\site-packages\speech_recognition\recognizers\google.py", line 124, in parse

  actual_result = self.convert_to_result(response_text)

 File "C:\Users\....\lib\site-packages\speech_recognition\recognizers\google.py", line 173, in convert_to_result

  raise UnknownValueError()

speech_recognition.exceptions.UnknownValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

 File "C:\Users\...\PycharmProjects\voiceAssistant\main.py", line 35, in <module>

  result = aufnahme()

 File "C:\Users\...\PycharmProjects\voiceAssistant\main.py", line 27, in aufnahme

  print("Recognized speech (Google):", r.recognize_google(gesagt, show_all=True, language="de"))

 File "C:\Users\...\lib\site-packages\speech_recognition\recognizers\google.py", line 251, in recognize_legacy

  return output_parser.parse(response_text)

 File "C:\Users\...\lib\site-packages\speech_recognition\recognizers\google.py", line 124, in parse

  actual_result = self.convert_to_result(response_text)

 File "C:\Users\...\lib\site-packages\speech_recognition\recognizers\google.py", line 173, in convert_to_result

  raise UnknownValueError()

speech_recognition.exceptions.UnknownValueError

Process finished with exit code 1

Woran liegt das, soll ich eine andere Speech Recognition verwenden und wenn ja welche?

Vielen Dank im Voraus!

Assistent, cmd, Code, Error, Problemlösung, Programmiersprache, Python, Python 3, Sprachassistent, Pycharm

discord.py fehlermeldung?

Hallo ihr lieben,

ich bin ein programmier anfänger und ich habe nun vor einen discord bot zu coden ich habe einen anfangs schrit in phyton vn einem video übernommen aber es kommt der fehler

Traceback (most recent call last):

 File "C:\Users\jweiling\PycharmProjects\NightmaresSystem\main.py", line 53, in <module>

   bot.run("")

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 828, in run

   asyncio.run(runner())

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 44, in run

   return loop.run_until_complete(main)

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete

   return future.result()

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 817, in runner

   await self.start(token, reconnect=reconnect)

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 746, in start

   await self.connect(reconnect=reconnect)

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 672, in connect

   raise PrivilegedIntentsRequired(exc.shard_id) from None

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000000002D2B160>

Traceback (most recent call last):

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 116, in __del__

   self.close()

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 108, in close

   self._loop.call_soon(self._call_connection_lost, None)

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 719, in call_soon

   self._check_closed()

 File "C:\Users\jweiling\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 508, in _check_closed

   raise RuntimeError('Event loop is closed')

RuntimeError: Event loop is closed

hat wer eine Ahnung

LG Hyper

Python, Pycharm, Discord, Discord Bot

Warum funktioniert mein Code auf dem Raspberry Pi nicht?

Hallo,

Ich programmiere gerade einen Sprachassistenten und auf meinem Windows PC hat alles super funktioniert, aber als ich das Programm auf den Pi geladen und das Programm gestartet habe, kam diese Fehlermeldung:

Traceback (most recent call last):

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 1164, in <module>

  execute()

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 658, in execute

  if detect_wake_word(): # Falls das Wake-Word erkannt wurde

    ^^^^^^^^^^^^^^^^^^

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/main.py", line 139, in detect_wake_word

  recognizer.adjust_for_ambient_noise(source) # Hintergrundgeräusche anpassen

  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "/home/grafjulian08/PycharmProjects/voiceAssistant/.venv/lib/python3.11/site-packages/speech_recognition/__init__.py", line 389, in adjust_for_ambient_noise

  assert source.stream is not None, "Audio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"

      ^^^^^^^^^^^^^^^^^^^^^^^^^

AssertionError: Audio source must be entered before adjusting, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?

Ich habe ein gutes Mikrofon am Pi, welches auch funktioniert, und ich habe schon viel am Code geändert, aber es geht nicht weg. Woran kann das sonst liegen?

Wenn ich Teile meines Codes zeigen soll, könnt ihr das sagen.

Freundliche Grüsse

cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Raspberry Pi, Pycharm, ChatGPT

Wie kann ich die Porcupine Wake-Word detection verwenden?

Hallo,

ich programmiere gerade einen Sprachassistenten und wollte nun die Wake-Word Funktion hinzufügen. Das ist mein Code:

def wait_for_wake_word(recognizer, source):
    keyword_path = r"C:\Users\User\PycharmProjects\voiceAssistant\hey-Luna_de_windows_v3_0_0 (2)\hey-Luna_de_windows_v3_0_0.ppn"
    sensitivity = 0.5
    access_key = "..."

    handle = pvporcupine.create(keywords=[keyword_path], sensitivities=[sensitivity], access_key=access_key)

    if handle is None:
        print("Fehler beim Erstellen des Porcupine-Objekts. Überprüfe den Dateipfad und den Zugriffsschlüssel.")
        return

    audio = pyaudio.PyAudio()

    try:
        print("Warte auf das Wake-Word...")

        stream = audio.open(
            rate=handle.sample_rate,
            channels=1,
            format=pyaudio.paInt16,
            input=True,
            frames_per_buffer=handle.frame_length)

        while True:
            pcm = stream.read(handle.frame_length)
            pcm = pcm[0: handle.frame_length]

            keyword_index = handle.process(pcm)
            if keyword_index >= 0:
                print("Wake-Word 'Luna' erkannt!")
                break
    finally:
        if handle is not None:
            handle.delete()
        if stream is not None:
            stream.close()
        if audio is not None:
            audio.terminate()

Wenn ich es nun aber ausführe, kommt diese Fehlermeldung:

Traceback (most recent call last):

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 1162, in <module>

  execute()

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 671, in execute

  wait_for_wake_word(recognizer, source)

 File "C:\Users\User\PycharmProjects\voiceAssistant\main.py", line 121, in wait_for_wake_word

  handle = pvporcupine.create(keywords=[keyword_path], sensitivities=[sensitivity], access_key=access_key)

       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\User\PycharmProjects\voiceAssistant\venv\interpreter\Lib\site-packages\pvporcupine\_factory.py", line 59, in create

  raise ValueError(

ValueError: One or more keywords are not available by default. Available default keywords are:\ngrapefruit, picovoice, terminator, americano, computer, hey siri, bumblebee, hey barista, ok google, alexa, hey google, blueberry, grasshopper, jarvis, porcupine, pico clock

Es liegt aber nicht an einem Rechtschreibfehler im Dateipfad oder im API Key. Woran kann es sonst liegen?

Freundliche Grüsse

cmd, Code, künstliche Intelligenz, Programmiersprache, Python, Python 3, Pycharm

Python Fehler no attribute 'TFE_NewContextOptions'?

Hi, Ich habe einen Fehler beim ausführen von einem Python Script:

C:\Users\DeneX\Desktop\SC_FEGAN\SC-FEGAN-program-files>python demo.py

Traceback (most recent call last):

 File "C:\Users\DeneX\Desktop\SC_FEGAN\SC-FEGAN-program-files\demo.py", line 11, in <module>

   from model import Model

 File "C:\Users\DeneX\Desktop\SC_FEGAN\SC-FEGAN-program-files\model.py", line 1, in <module>

   import tensorflow as tf

 File "C:\Users\DeneX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\tensorflow\__init__.py", line 24, in <module>

   from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import

   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 File "C:\Users\DeneX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\tensorflow\python\__init__.py", line 49, in <module>

   from tensorflow.python import pywrap_tensorflow

 File "C:\Users\DeneX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>

   from tensorflow.python.pywrap_tensorflow_internal import *

 File "C:\Users\DeneX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 96, in <module>

   TFE_NewContextOptions = _pywrap_tensorflow_internal.TFE_NewContextOptions

                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

AttributeError: module '_pywrap_tensorflow_internal' has no attribute 'TFE_NewContextOptions'

Wie bekomme ich das behoben; Ich habe tensorflow==1.13.0rc2 installiert damit das Script läuft & Python 3.11.3

Linux, Programmiersprache, Python, Python 3, Pygame, Tkinter, Pycharm, Discord, Discord Bot

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

Warum funktioniert Flask und Websockets nicht?

Hallo,

ich wollte meinen Python- Code mit meinem HTML- Code verbinden, damit, wenn mein Wake- Word "Luna" erkannt wurde, der Hintergrund der Datei output.html seine Farbe ändert und rot wird. Hier ist der Code:

Python:

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('connect')
def handle_connect():
    print("Client verbunden")


@socketio.on('disconnect')
def handle_disconnect():
    print("Client getrennt")


@socketio.on('change_background')
def change_background(color):
    print("Hintergrundfarbe ändern:", color)
    socketio.emit('background_changed', color)

HTML /CSS:

... body {
  background-color: black;
  margin: 0;
  padding: 0;
  text-align: center;
  overflow-x: hidden;
  overflow-y: hidden;
    -webkit-user-select: none; /* Für WebKit-Browser */
    -moz-user-select: none; /* Für Mozilla-basierte Browser */
    -ms-user-select: none; /* Für Microsoft Edge */
    user-select: none;
}  
</style>
</head>
<body>

JavaScript:

... // FLASK
    var socket = io();

    socket.on('connect', function() {
        console.log('Verbunden mit dem Server');
    });

    socket.on('disconnect', function() {
        console.log('Verbindung zum Server getrennt');
    });

    socket.on('background_changed', function(color) {
        console.log('Hintergrundfarbe geändert:', color);
        document.body.style.backgroundColor = color;
    });
</script>
</body>
</html>
    """
    with open("output.html", "w") as html_file:
        html_file.write(html_content)

    return "output.html"

Wenn ich den Code aber ausführe und "Luna" sage, ändert der Hintergrund nicht seine Farbe. Woran liegt das?

Freundliche Grüsse

HTML, Webseite, JavaScript, HTML5, Code, Programmiersprache, Python, Frontend, Python 3, Pycharm, Flask