Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+261
- requirements.txtAdded+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261import gradio as gr
import requests
import json
import os
import boto3
import time
import wave
# 🔹 S3-Konfiguration
AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY")
BUCKET_NAME = "chatbot-storage-2025-01-17"
REGION_NAME = "eu-north-1"
s3_client = boto3.client(
"s3",
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY,
region_name=REGION_NAME
)
# 🔹 Multi-Turn-Gesprächsverlauf
conversation_history = []
# 🔹 Hochladen von Audiodateien zu S3
def upload_to_s3(file_path):
"""Lädt eine Audiodatei auf S3 hoch und gibt die öffentliche URL zurück"""
if not os.path.exists(file_path):
print("❌ Fehler: Datei existiert nicht")
return None
file_name = f"audio_{int(time.time())}.wav"
s3_client.upload_file(file_path, BUCKET_NAME, file_name)
public_url = f"https://{BUCKET_NAME}.s3.{REGION_NAME}.amazonaws.com/{file_name}"
return public_url
def format_conversation_for_gradio(conversation_history):
"""Formatiert den Chatverlauf für Gradio im Fehlerfall."""
formatted_conversation = []
for entry in conversation_history:
role = entry["role"]
print(f"📥 DEBUG: Fehlerfall - Eintrag in conversation_history → Role: {role} | Content: {repr(entry['content'])}")
# Falls content eine Liste ist und das erste Element ein dict ist, extrahiere den Text
if isinstance(entry["content"], list):
if len(entry["content"]) > 0 and isinstance(entry["content"][0], dict):
content = entry["content"][0].get("text", repr(entry["content"][0])) # Debug: Falls kein "text"-Key vorhanden ist, zeige den Inhalt als String
else:
content = repr(entry["content"]) # Debug: Falls eine leere Liste oder ein anderes Format, speichere es als String
elif isinstance(entry["content"], dict):
content = entry["content"].get("text", repr(entry["content"])) # Falls es direkt ein Dict ist, greife sicher zu
else:
content = str(entry["content"]) # Fallback: Falls `content` direkt ein String ist
formatted_conversation.append({
"role": role,
"content": content
})
print(f"\n📤 DEBUG: Fehlerfall - Umgewandelte Antwort für Gradio:\n{json.dumps(formatted_conversation, indent=2)}")
return formatted_conversation
def chat_with_api(user_input, audio_file, API_URL, API_KEY):
global conversation_history
print("\n🔹 DEBUG: Chat-API aufgerufen")
print(f"📥 Eingabe-Text: {repr(user_input)}")
print(f"🎤 Eingabe-Audio: {repr(audio_file)}")
# JSON-Struktur für API erstellen
user_content = []
# Falls weder Text noch Audio vorhanden sind → Ignorieren
if not user_input.strip() and not audio_file:
print("❌ DEBUG: Nachricht ist leer oder Aufnahme nicht gestoppt! Kein Text und keine gültige Audiodatei.")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False) # Chat bleibt gleich, Audio bleibt unverändert; Keine Veränderung der UI, keine Anfrage an die API
# Falls Text eingegeben wurde, hinzufügen
if isinstance(user_input, str) and user_input.strip():
user_content.append({"type": "text", "text": user_input})
# Falls eine Audiodatei hochgeladen wurde
s3_url = None
if audio_file:
print(f"🔍 DEBUG: Überprüfe Audiodatei {audio_file}")
if not isinstance(audio_file, str) or not os.path.exists(audio_file):
print("❌ DEBUG: Audiodatei nicht gefunden oder ungültig!")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
file_size = os.path.getsize(audio_file)
print(f"🔹 DEBUG: Audiodatei-Größe: {file_size} Bytes")
if file_size < 2048:
print("❌ DEBUG: Audiodatei ist zu klein!")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
try:
with wave.open(audio_file, "rb") as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / float(frame_rate)
print(f"🔹 DEBUG: Audiodauer: {duration:.2f} Sekunden")
if duration < 0.5:
print("❌ DEBUG: Aufnahme ist zu kurz!")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
except wave.Error as e:
print(f"❌ DEBUG: Fehler beim Analysieren der Datei: {e}")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
except Exception as e:
print(f"❌ DEBUG: Unerwarteter Fehler bei der Audioprüfung: {e}")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
# ✅ Datei erfolgreich geprüft → Jetzt zu S3 hochladen
s3_url = upload_to_s3(audio_file)
if s3_url:
print(f"✅ DEBUG: Audio erfolgreich zu S3 hochgeladen: {s3_url}")
user_content.append({"type": "audio_url", "audio_url": {"url": s3_url}})
else:
print("❌ DEBUG: Upload zu S3 fehlgeschlagen!")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
# **Falls keine gültige Eingabe vorhanden ist, direkt abbrechen**
if not user_content:
print("❌ DEBUG: Nachricht ist leer! Kein Text und keine gültige Audiodatei.")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
# Neues Benutzer-Statement hinzufügen
conversation_history.append({"role": "user", "content": user_content})
# **Validierungscheck: Stelle sicher, dass die Nachrichtenstruktur korrekt ist**
if not all("role" in message and "content" in message for message in conversation_history):
print("❌ DEBUG: Ungültige Nachrichtenstruktur! Eine Nachricht fehlt `role` oder `content`.")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
# API-Request-Daten im korrekten JSON-Format
data = {
"input_data": {
"input_string": conversation_history
}
}
print(f"\n📤 DEBUG: API-Request gesendet:\n{json.dumps(data, indent=2)}")
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {API_KEY}'
}
# Anfrage an API senden
try:
response = requests.post(API_URL, json=data, headers=headers, timeout=10)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(f"❌ DEBUG: HTTP-Fehler: {e} - {response.text}")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
except requests.exceptions.RequestException as e:
print(f"❌ DEBUG: API-Request fehlgeschlagen! Fehler: {e}")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
print("\n📥 DEBUG: HTTP-Response erhalten")
print(f"🔹 Statuscode: {response.status_code}")
print(f"🔹 Header: {response.headers}")
response_text = response.text.strip()
print(f"📥 DEBUG: API-Rohantwort erhalten:\n{response_text}")
# JSON-Antwort sicher parsen
try:
api_response = response.json()
print(f"✅ DEBUG: API-Antwort erfolgreich geparst.")
if isinstance(api_response, str):
print(f"🔹 DEBUG: API-Antwort ist ein String, versuche doppelte Dekodierung...")
api_response = json.loads(api_response)
print(f"✅ DEBUG: Zweites JSON-Decoding erfolgreich:\n{json.dumps(api_response, indent=2)}")
except json.JSONDecodeError:
print("❌ DEBUG: API-Antwort ist kein gültiges JSON!")
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=None, visible=False)
if "error" in api_response:
print(f"❌ DEBUG: API-Fehlermeldung erhalten: {api_response['error']}")
error_message_text = api_response["error"].strip()
if not error_message_text: # Falls die Fehlermeldung leer ist
error_message_text = "⚠️ API-Error: No response"
return format_conversation_for_gradio(conversation_history), gr.update(value=None), gr.update(value=error_message_text, visible=True)
# **Finale Verarbeitung der Antwort**
bot_reply = api_response.get("response", None)
print(f"📥 DEBUG: bot_reply Typ: {type(bot_reply)} | Inhalt: {repr(bot_reply)}")
# Falls bot_reply eine Zeichenkette ist, konvertieren wir sie in das erwartete Format
if isinstance(bot_reply, str):
conversation_history.append({"role": "assistant", "content": [{"type": "text", "text": bot_reply}]})
# **🚀 Fix: Gradio benötigt eine Liste von Dictionaries mit `role` & `content`**
formatted_conversation = []
for entry in conversation_history:
role = entry["role"]
# Füge Debugging hinzu, um das genaue Format der `content` zu untersuchen
print(f"📥 DEBUG: Eintrag in conversation_history → Role: {role} | Content: {repr(entry['content'])}")
# Falls content eine Liste ist und das erste Element ein dict ist, extrahiere den Text
if isinstance(entry["content"], list):
if len(entry["content"]) > 0 and isinstance(entry["content"][0], dict):
content = entry["content"][0].get("text", repr(entry["content"][0])) # Debug: Falls kein "text"-Key vorhanden ist, zeige den Inhalt als String
else:
content = repr(entry["content"]) # Debug: Falls eine leere Liste oder ein anderes Format, speichere es als String
elif isinstance(entry["content"], dict):
content = entry["content"].get("text", repr(entry["content"])) # Falls es direkt ein Dict ist, greife sicher zu
else:
content = str(entry["content"]) # Fallback: Falls `content` direkt ein String ist
formatted_conversation.append({
"role": role,
"content": content
})
print(f"\n📤 DEBUG: Umgewandelte Antwort für Gradio:\n{json.dumps(formatted_conversation, indent=2)}")
# **Finale Rückgabe: Gradio erwartet eine Liste von Dictionaries**
return formatted_conversation, gr.update(value=None), gr.update(value=None, visible=False) # Chatverlauf, Kein Audio-Output, Zurücksetzen des Audio-Eingabefeldes
def reset_conversation():
"""Setzt den Chatverlauf zurück und leert die UI (inkl. Audioaufnahme)."""
global conversation_history
conversation_history.clear()
print("✅ DEBUG: Gesprächsverlauf & Audio zurückgesetzt.")
# UI zurücksetzen: Leerer Chat + Leeres Audio-Eingabefeld
return gr.update(value=[]), gr.update(value=None) # Chat leer + Audio zurücksetzen
with gr.Blocks() as demo:
gr.Markdown("# 🔊 Chatbot with Audio & Text")
chatbot = gr.Chatbot(type="messages")
text_input = gr.Textbox(placeholder="Enter your message...")
error_message = gr.Markdown(visible=False) # 🔴 Fehlerhinweis (standardmäßig unsichtbar)
audio_input = gr.Audio(
sources=["microphone"],
type="filepath",
format="wav",
autoplay=False,
interactive=True
)
submit_button = gr.Button("Send")
reset_button = gr.Button("Reset Chat")
reset_button.click(reset_conversation, outputs=[chatbot, audio_input]) # Resettet Chat + Audio
api_url_input = gr.Textbox(label="API Endpoint URL")
api_key_input = gr.Textbox(label="API Auth Token", type="password")
submit_button.click(chat_with_api, inputs=[text_input, audio_input, api_url_input, api_key_input], outputs=[chatbot, audio_input, error_message])
demo.launch()1234gradio
boto3
requests
waveapp.pyAdded+261
requirements.txtAdded+4