ich habe eine Flask-Datei für einen Chat geschrieben, die ganz ordentlich funktioniert.
Der Chat speist sich aus einer großen Zahl von Json-Dateien, die verschiedene Themen behandeln.
Der Name dieser Json-Dateien soll nun als Topic (Dateiname minus ".json") über einen intermediate_file.json an eine zweite Flask-Datei weitergeben werden.
Im intermediate_file.json soll verzeichnet werden, wer spricht (Bot oder User), Systemzeit, der Ort des Gespräches und die Chat-Message selbst.
Leider kommt Sprecher, timestamp und message prima in der zweiten Flask-Datei an, nicht aber das Topic. Nun bin ich ziemlich sicher, dass der Fehler ein schön blöder ist. Nur komme ich seit 4 Tagen einfach nicht drauf, welcher.
Mit diesem Codeblock versuche ich es:
Code: Alles auswählen
data_cache = {}
last_category_name = ""
last_json_filename = ""
recent_messages = []
last_matched_pattern = ""
last_responses = set()
speaker = ""
def remove_punctuation_for_matching(input_text):
pattern = f"[{re.escape(string.punctuation)}]"
return re.sub(pattern, '', input_text)
def log_message_to_file(speaker, message, json_filename=None):
if not json_filename:
print("Warnung: json_filename ist nicht gesetzt!")
else:
print(f"json_filename ist gesetzt: {json_filename}")
topic = os.path.splitext(json_filename)[0] if json_filename else 'Unbekannt'
placestamp = session.get('user_location', 'Unbekannt')
record = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"speaker": speaker,
"message": message,
"location": placestamp,
"topic": topic
}
file_path = 'C:/Users/andre/Desktop/MALDIX/GPT/intermediate_file.json'
try:
if os.path.exists(file_path):
with open(file_path, 'r+', encoding='utf-8') as file:
try:
data = json.load(file)
if not isinstance(data, list):
data = [data]
except json.JSONDecodeError:
data = []
data.append(record)
file.seek(0)
json.dump(data, file, ensure_ascii=False, indent=4)
file.truncate()
else:
with open(file_path, 'w', encoding='utf-8') as file:
json.dump([record], file, ensure_ascii=False, indent=4)
except Exception as e:
print(f"Error beim Schreiben: {e}")
@app.route("/start_conversation", methods=["GET"])
def start_conversation():
standortErmittlung = StandortErmittlung()
standortFrage = standortErmittlung.stelle_standortfrage()
ort = standortErmittlung.get_location()
if ort:
session['user_location'] = ort
return jsonify({
"message": standortFrage
})
emotions = MaldixEmotions()
emotional_memory = EmotionalMemory()
maldix_interface = MaldixEmotionInterface(emotions, emotional_memory)
emoDix = EmoDix(api_key)
@app.route("/chat", methods=["POST"])
def chat():
data = request.json
user_input_original = data.get("input_text", "").strip().lower()
# Find matching category and set last_json_filename
matching_category = find_matching_category(user_input_original)
if matching_category:
global last_category_name, last_json_filename
last_category_name = matching_category['pattern']
last_json_filename = matching_category.get('filename', '')
print(f"Set last_json_filename to: {last_json_filename}")
else:
print("No matching category found, last_json_filename remains unchanged.")
if "wie geht es dir?" in user_input_original:
emotion, ort = emoDix.get_emotion_based_on_weather()
if emotion and ort:
response = f"Ich fühle im Augenblick {emotion} aufgrund des Wetters in {ort}."
else:
response = "Keine Ahnung, wie ich mich gerade fühle! Versuch es später nochmal."
return jsonify({"response": response})
log_message_to_file("IC", user_input_original, last_json_filename)
cleaned_input = remove_punctuation_for_matching(user_input_original.lower())
response = ""
if ist_wetteranfrage(cleaned_input):
response = wetterService.check_and_respond(cleaned_input)
else:
global recent_messages, last_matched_pattern, last_responses
if last_category_name and last_json_filename in data_cache:
current_category = next((cat for cat in data_cache[last_json_filename] if cat['pattern'] == last_category_name), None)
if current_category:
matched_response = get_refined_response(current_category, cleaned_input, stopwords_de)
if matched_response:
response = matched_response
if not response:
matching_category = find_matching_category(user_input_original)
if matching_category:
global last_category_name, last_json_filename
last_category_name = matching_category['pattern']
last_json_filename = os.path.splitext(matching_category.get('filename', ''))[0]
print(f"Set last_json_filename to: {last_json_filename}")
else:
print("No matching category found, last_json_filename remains unchanged.")
last_json_filename = ''
log_message_to_file("MX", response, last_json_filename)
recent_messages.append(f"User: {user_input_original}")
recent_messages.append(f"Bot: {response}")
return jsonify({"response": response})
Herzliche Grüße
von
Andreas