Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,6 @@ import json
|
|
| 3 |
import time
|
| 4 |
import requests
|
| 5 |
from anthropic import Anthropic
|
| 6 |
-
from openai import OpenAI
|
| 7 |
import gradio as gr
|
| 8 |
import pandas as pd
|
| 9 |
from huggingface_hub import CommitScheduler
|
|
@@ -16,24 +15,20 @@ from sentence_transformers import SentenceTransformer
|
|
| 16 |
import numpy as np
|
| 17 |
import faiss
|
| 18 |
import re
|
| 19 |
-
from docx import Document # NYTT: Flyttad till toppen
|
| 20 |
-
import PyPDF2 # NYTT: Flyttad till toppen
|
| 21 |
|
| 22 |
# --- Konfiguration ---
|
| 23 |
CHARGENODE_URL = "https://www.chargenode.eu"
|
| 24 |
MAX_CHUNK_SIZE = 2000
|
| 25 |
CHUNK_OVERLAP = 200
|
| 26 |
RETRIEVAL_K = 5
|
|
|
|
|
|
|
| 27 |
MODEL_NAME = "claude-sonnet-4-20250514"
|
| 28 |
-
FAQ_EXCEL_FILENAME = "FAQ stadat.xlsx" # NYTT: Konfigurerbart filnamn
|
| 29 |
|
|
|
|
| 30 |
IS_HUGGINGFACE = os.environ.get("SPACE_ID") is not None
|
| 31 |
|
| 32 |
-
|
| 33 |
-
if not OPENAI_API_KEY:
|
| 34 |
-
raise ValueError("OPENAI_API_KEY saknas")
|
| 35 |
-
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 36 |
-
|
| 37 |
ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY")
|
| 38 |
if not ANTHROPIC_API_KEY:
|
| 39 |
raise ValueError("ANTHROPIC_API_KEY saknas")
|
|
@@ -43,6 +38,7 @@ log_folder = "logs"
|
|
| 43 |
os.makedirs(log_folder, exist_ok=True)
|
| 44 |
log_file_path = os.path.join(log_folder, "conversation_log_v2.txt")
|
| 45 |
|
|
|
|
| 46 |
if not os.path.exists(log_file_path):
|
| 47 |
with open(log_file_path, "w", encoding="utf-8") as f:
|
| 48 |
f.write("")
|
|
@@ -52,128 +48,98 @@ hf_token = os.environ.get("HF_TOKEN")
|
|
| 52 |
if not hf_token:
|
| 53 |
raise ValueError("HF_TOKEN saknas")
|
| 54 |
|
|
|
|
| 55 |
scheduler = CommitScheduler(
|
| 56 |
repo_id="ChargeNodeEurope/logfiles",
|
| 57 |
repo_type="dataset",
|
| 58 |
folder_path=log_folder,
|
| 59 |
path_in_repo="logs_v2",
|
| 60 |
-
every=300,
|
| 61 |
token=hf_token
|
| 62 |
)
|
| 63 |
|
| 64 |
# --- Globala variabler ---
|
| 65 |
-
last_log = None
|
|
|
|
|
|
|
| 66 |
embedder = None
|
| 67 |
embeddings = None
|
| 68 |
index = None
|
| 69 |
chunks = []
|
| 70 |
chunk_sources = []
|
| 71 |
-
faq_dict = {}
|
| 72 |
-
|
| 73 |
-
# NYTT: Globala definitioner för nyckelord och typer (VIKTIGT: MÅSTE ANPASSAS EFTER BEHOV)
|
| 74 |
-
# Dessa behövs av check_direct_match och dess hjälpfunktioner.
|
| 75 |
-
# Anpassa listorna med relevanta termer för din applikation.
|
| 76 |
-
system_keywords = {
|
| 77 |
-
"app": [
|
| 78 |
-
"app", "appen", "mobilapp", "mobil", "telefon", "ladda bil", "qr-kod",
|
| 79 |
-
"betalkort i appen", "laddningar", "mitt kort", "mina sidor app", "kartvy",
|
| 80 |
-
"favoriter", "laddhistorik", "starta laddning", "stoppa laddning"
|
| 81 |
-
],
|
| 82 |
-
"portal": [
|
| 83 |
-
"portal", "portalen", "adminportal", "administrera", "webbportal", "dashboard",
|
| 84 |
-
"hantera medlemmar", "organisationskonto", "företagsportal", "användare portal",
|
| 85 |
-
"statistik portal", "prissättning portal"
|
| 86 |
-
],
|
| 87 |
-
"företagskonto": [ # För mer specifika företagskontofrågor som kanske inte är portaladmin
|
| 88 |
-
"företagskonto", "företagsavtal", "orgnummer", "organisationsnummer",
|
| 89 |
-
"tjänstebil", "firmabil", "fakturor företag"
|
| 90 |
-
],
|
| 91 |
-
"betalning_privat": [ # Används för att identifiera tydligt privata betalningsfrågor
|
| 92 |
-
"mitt betalsätt", "min betalmetod", "mitt kort", "min betalning",
|
| 93 |
-
"privat betalkort", "personlig betalning", "uppdatera mitt kort"
|
| 94 |
-
],
|
| 95 |
-
}
|
| 96 |
-
|
| 97 |
-
organization_types = [
|
| 98 |
-
"samfällighet", "samfällighetsförening", "bostadsrättsförening", "brf", "förening",
|
| 99 |
-
"organisation", "kommun", "företag", "fastighetsägare", "arbetsgivare"
|
| 100 |
-
]
|
| 101 |
-
|
| 102 |
-
# Används för att identifiera om en FAQ-nyckel i faq_dict är organisationsspecifik
|
| 103 |
-
# Detta är en förenkling; idealiskt sett bör FAQ-objekt ha metadata eller separata dictionaries.
|
| 104 |
-
# Dessa termer bör finnas i FRÅGAN (nyckeln) till en FAQ som är avsedd för organisationer.
|
| 105 |
-
organization_faq_keys_substrings = [
|
| 106 |
-
"samfällighet", "förening", "organisation", "portal", "företag",
|
| 107 |
-
"admin", "brf", "styrelse", "medlemmar", "avtal", "fakturering organisation"
|
| 108 |
-
]
|
| 109 |
-
# --- Slut på nya globala definitioner ---
|
| 110 |
|
| 111 |
# --- Förbättrad loggfunktion ---
|
| 112 |
def safe_append_to_log(log_entry):
|
|
|
|
| 113 |
try:
|
|
|
|
| 114 |
with open(log_file_path, "a", encoding="utf-8") as log_file:
|
| 115 |
log_json = json.dumps(log_entry)
|
| 116 |
log_file.write(log_json + "\n")
|
| 117 |
-
log_file.flush()
|
|
|
|
| 118 |
print(f"Loggpost tillagd: {log_entry.get('timestamp', 'okänd tid')}")
|
| 119 |
return True
|
|
|
|
| 120 |
except Exception as e:
|
| 121 |
print(f"Fel vid loggning: {e}")
|
|
|
|
|
|
|
| 122 |
try:
|
| 123 |
os.makedirs(os.path.dirname(log_file_path), exist_ok=True)
|
|
|
|
|
|
|
| 124 |
with open(log_file_path, "a", encoding="utf-8") as log_file:
|
| 125 |
log_json = json.dumps(log_entry)
|
| 126 |
log_file.write(log_json + "\n")
|
|
|
|
| 127 |
print("Loggpost tillagd efter återhämtning")
|
| 128 |
return True
|
|
|
|
| 129 |
except Exception as retry_error:
|
| 130 |
print(f"Kritiskt fel vid loggning: {retry_error}")
|
| 131 |
return False
|
| 132 |
|
| 133 |
# --- Laddar textkällor ---
|
| 134 |
def load_local_files():
|
|
|
|
| 135 |
uploaded_text = ""
|
| 136 |
-
allowed = [".txt", ".
|
| 137 |
excluded = ["requirements.txt", "app.py", "conversation_log.txt", "conversation_log_v2.txt", "secrets", "prompt.txt"]
|
| 138 |
for file in os.listdir("."):
|
| 139 |
if file.lower().endswith(tuple(allowed)) and file not in excluded:
|
| 140 |
try:
|
| 141 |
-
content = "" # NYTT: Initiera content
|
| 142 |
if file.endswith(".txt"):
|
| 143 |
with open(file, "r", encoding="utf-8") as f:
|
| 144 |
content = f.read()
|
| 145 |
-
elif file.endswith(".docx"):
|
| 146 |
-
# Document är redan importerad globalt
|
| 147 |
-
content = "\n".join([p.text for p in Document(file).paragraphs])
|
| 148 |
-
elif file.endswith(".pdf"):
|
| 149 |
-
# PyPDF2 är redan importerad globalt
|
| 150 |
-
with open(file, "rb") as f:
|
| 151 |
-
reader = PyPDF2.PdfReader(f)
|
| 152 |
-
content = "\n".join([p.extract_text() or "" for p in reader.pages])
|
| 153 |
elif file.endswith(".csv"):
|
| 154 |
content = pd.read_csv(file).to_string()
|
| 155 |
elif file.endswith((".xls", ".xlsx")):
|
| 156 |
-
if file ==
|
| 157 |
df = pd.read_excel(file)
|
| 158 |
rows = []
|
| 159 |
for index, row in df.iterrows():
|
| 160 |
-
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
| 162 |
row_text += f"\nKategori: {row['kategori']}"
|
| 163 |
-
elif 'Kategori' in df.columns
|
| 164 |
row_text += f"\nKategori: {row['Kategori']}"
|
|
|
|
| 165 |
rows.append(row_text)
|
| 166 |
content = "\n\n".join(rows)
|
| 167 |
else:
|
| 168 |
content = pd.read_excel(file).to_string()
|
| 169 |
-
|
| 170 |
-
if content: # NYTT: Lägg bara till om content finns
|
| 171 |
-
uploaded_text += f"\n\nFIL: {file}\n{content}"
|
| 172 |
except Exception as e:
|
| 173 |
print(f"Fel vid läsning av {file}: {str(e)}")
|
| 174 |
return uploaded_text.strip()
|
| 175 |
|
| 176 |
def load_prompt():
|
|
|
|
| 177 |
try:
|
| 178 |
with open("prompt.txt", "r", encoding="utf-8") as f:
|
| 179 |
prompt_content = f.read().strip()
|
|
@@ -190,54 +156,55 @@ def load_prompt():
|
|
| 190 |
|
| 191 |
# --- Förbättrad chunking ---
|
| 192 |
def prepare_chunks(text_data):
|
| 193 |
-
|
|
|
|
| 194 |
global faq_dict
|
| 195 |
|
| 196 |
-
for source, text in text_data.items():
|
|
|
|
| 197 |
paragraphs = [p for p in text.split("\n") if p.strip()]
|
| 198 |
|
|
|
|
| 199 |
i = 0
|
| 200 |
current_file_chunks = []
|
| 201 |
-
current_file_sources = []
|
| 202 |
while i < len(paragraphs):
|
|
|
|
| 203 |
current_chunk = ""
|
| 204 |
start_idx = i
|
| 205 |
|
|
|
|
| 206 |
if i < len(paragraphs) and paragraphs[i].startswith("Fråga:"):
|
| 207 |
-
question = paragraphs[i][7:].strip()
|
| 208 |
current_chunk = paragraphs[i]
|
| 209 |
i += 1
|
| 210 |
|
|
|
|
| 211 |
while i < len(paragraphs) and not paragraphs[i].startswith("Fråga:"):
|
|
|
|
| 212 |
if len(current_chunk) + len(paragraphs[i]) + 1 <= MAX_CHUNK_SIZE:
|
| 213 |
current_chunk += "\n" + paragraphs[i]
|
| 214 |
else:
|
|
|
|
| 215 |
if "Svar:" in current_chunk:
|
| 216 |
-
|
|
|
|
| 217 |
break
|
| 218 |
else:
|
| 219 |
-
current_chunk += "\n" + paragraphs[i]
|
| 220 |
else:
|
| 221 |
break
|
| 222 |
i += 1
|
| 223 |
|
|
|
|
| 224 |
if "Svar:" in current_chunk:
|
| 225 |
answer_start = current_chunk.find("Svar:")
|
| 226 |
answer_text = current_chunk[answer_start + 5:].strip()
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
# Betalningsvariationer (som tidigare)
|
| 231 |
-
if any(term in question.lower() for term in ["betalsätt", "betalmetod", "betalmedel", "kort",
|
| 232 |
-
"betalkort", "betalning", "betala"]):
|
| 233 |
-
payment_variations = [
|
| 234 |
-
"hur ändrar jag betalmedel", "hur byter jag betalsätt",
|
| 235 |
-
"hur uppdaterar jag mitt betalkort", "hur ändrar jag betalmetod",
|
| 236 |
-
"hur byter jag betalningsmetod", "hur ändrar jag betalkort"
|
| 237 |
-
]
|
| 238 |
-
for variation in payment_variations:
|
| 239 |
-
faq_dict[variation.lower()] = answer_text # NYTT: .lower() på variationen
|
| 240 |
else:
|
|
|
|
| 241 |
while i < len(paragraphs) and len(current_chunk) + len(paragraphs[i]) + 1 <= MAX_CHUNK_SIZE:
|
| 242 |
if current_chunk:
|
| 243 |
current_chunk += " " + paragraphs[i]
|
|
@@ -245,63 +212,60 @@ def prepare_chunks(text_data):
|
|
| 245 |
current_chunk = paragraphs[i]
|
| 246 |
i += 1
|
| 247 |
|
|
|
|
| 248 |
if current_chunk.strip():
|
| 249 |
current_file_chunks.append(current_chunk.strip())
|
| 250 |
-
current_file_sources.append(source)
|
| 251 |
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
i += 1
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
overlap_chunks_for_file = []
|
| 260 |
overlap_sources_for_file = []
|
| 261 |
|
| 262 |
for j in range(len(current_file_chunks)):
|
| 263 |
overlap_chunks_for_file.append(current_file_chunks[j])
|
| 264 |
-
overlap_sources_for_file.append(current_file_sources[j])
|
| 265 |
|
| 266 |
if j < len(current_file_chunks) - 1:
|
|
|
|
| 267 |
space_left = MAX_CHUNK_SIZE - len(current_file_chunks[j])
|
|
|
|
|
|
|
| 268 |
if space_left >= CHUNK_OVERLAP:
|
| 269 |
-
#
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
overlap_text = current_file_chunks[j] + " " + next_chunk_overlap_part
|
| 274 |
-
if len(overlap_text) <= MAX_CHUNK_SIZE:
|
| 275 |
overlap_chunks_for_file.append(overlap_text)
|
| 276 |
overlap_sources_for_file.append(current_file_sources[j])
|
| 277 |
|
| 278 |
chunks_list.extend(overlap_chunks_for_file)
|
| 279 |
sources_list.extend(overlap_sources_for_file)
|
| 280 |
-
|
| 281 |
print(f"Genererade {len(chunks_list)} chunks med {len(faq_dict)} FAQ-par")
|
| 282 |
return chunks_list, sources_list
|
| 283 |
|
| 284 |
|
| 285 |
def initialize_embeddings():
|
|
|
|
| 286 |
global embedder, embeddings, index, chunks, chunk_sources, faq_dict
|
| 287 |
|
| 288 |
if embedder is None:
|
| 289 |
print("Initierar SentenceTransformer och FAISS-index...")
|
|
|
|
| 290 |
print("Laddar textdata...")
|
| 291 |
-
|
| 292 |
-
# 'chunk_sources' endast att innehålla "local_files". För mer granulär
|
| 293 |
-
# källspårning (per fil), behöver load_local_files() returnera en dictionary
|
| 294 |
-
# med källor som nycklar och texter som värden, och prepare_chunks()
|
| 295 |
-
# anpassas för att hantera detta (liknande de "enhanced"-versionerna
|
| 296 |
-
# i den ursprungliga, större kodbasen).
|
| 297 |
-
text_data = {"local_files": load_local_files()}
|
| 298 |
print("Förbereder textsegment...")
|
| 299 |
chunks, chunk_sources = prepare_chunks(text_data)
|
| 300 |
-
print(f"{len(chunks)} segment laddade
|
| 301 |
|
| 302 |
if not chunks:
|
| 303 |
print("Varning: Inga chunks genererades. Kontrollera textkällor och chunking-logik.")
|
| 304 |
-
|
|
|
|
| 305 |
embeddings = np.array([]).reshape(0, embedder.get_sentence_embedding_dimension())
|
| 306 |
index = faiss.IndexFlatIP(embedder.get_sentence_embedding_dimension())
|
| 307 |
print("FAISS-index initialiserat tomt då inga chunks fanns.")
|
|
@@ -309,10 +273,12 @@ def initialize_embeddings():
|
|
| 309 |
|
| 310 |
print("Skapar embeddings...")
|
| 311 |
embedder = SentenceTransformer('all-MiniLM-L6-v2')
|
| 312 |
-
embeddings = embedder.encode(chunks, convert_to_numpy=True
|
| 313 |
|
|
|
|
| 314 |
if embeddings.ndim == 2 and embeddings.shape[0] > 0:
|
| 315 |
embeddings_norm = np.linalg.norm(embeddings, axis=1, keepdims=True)
|
|
|
|
| 316 |
embeddings_norm[embeddings_norm == 0] = 1e-10
|
| 317 |
embeddings = embeddings / embeddings_norm
|
| 318 |
|
|
@@ -321,249 +287,115 @@ def initialize_embeddings():
|
|
| 321 |
print("FAISS-index klart")
|
| 322 |
else:
|
| 323 |
print("Varning: Inga embeddings genererades, FAISS-index kan vara tomt eller ogiltigt.")
|
|
|
|
| 324 |
dimension = embedder.get_sentence_embedding_dimension() if embedder else 384
|
| 325 |
index = faiss.IndexFlatIP(dimension)
|
| 326 |
print("FAISS-index initialiserat tomt.")
|
| 327 |
|
| 328 |
print(f"FAQ Dictionary innehåller {len(faq_dict)} nycklar")
|
| 329 |
-
if len(faq_dict) > 0:
|
| 330 |
-
payment_keys_example = [k for k in faq_dict.keys() if any(term in k for term in ["betalsätt", "betalmetod", "betalmedel"])]
|
| 331 |
-
print(f"Exempel på betalningsrelaterade FAQ-nycklar: {payment_keys_example[:5]}")
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
# --- Kontextmedveten direct match ---
|
| 335 |
-
# Hjälpfunktioner (som tidigare föreslagits, behöver finjusteras)
|
| 336 |
-
def _is_app_focused(query_lower):
|
| 337 |
-
global system_keywords # Använd global
|
| 338 |
-
# Kollar om frågan innehåller starka app-indikatorer OCH individualitet
|
| 339 |
-
if any(app_term in query_lower for app_term in system_keywords.get("app", [])):
|
| 340 |
-
if any(individual_term in query_lower for individual_term in ["jag", "mitt", "min", "mina"]):
|
| 341 |
-
return True
|
| 342 |
-
# Om "appen" nämns explicit med en typisk app-åtgärd (även med "vi")
|
| 343 |
-
if any(app_action in query_lower for app_action in system_keywords.get("betalning_privat", []) + ["laddning", "betalkort"]):
|
| 344 |
-
return True
|
| 345 |
-
return False
|
| 346 |
-
|
| 347 |
-
def _is_org_admin_focused(query_lower):
|
| 348 |
-
global system_keywords, organization_types # Använd globala
|
| 349 |
-
is_org_type = any(org_type in query_lower for org_type in organization_types)
|
| 350 |
-
has_collective_pronoun = any(pronoun in query_lower for pronoun in ["vi", "vår", "våra", "oss", "föreningen", "organisationen"])
|
| 351 |
-
|
| 352 |
-
if is_org_type or has_collective_pronoun:
|
| 353 |
-
if any(portal_term in query_lower for portal_term in system_keywords.get("portal", [])):
|
| 354 |
-
return True
|
| 355 |
-
# Termer som starkt pekar på administration av organisationens uppgifter
|
| 356 |
-
org_admin_terms = ["uppgifter", "avtal", "fakturor", "medlemmar", "styrelse", "ekonomi", "administration"]
|
| 357 |
-
if any(org_admin_term in query_lower for org_admin_term in org_admin_terms) and \
|
| 358 |
-
not _is_app_focused(query_lower): # Viktigt: inte om det redan är klassat som app-fokuserat
|
| 359 |
-
return True
|
| 360 |
-
return False
|
| 361 |
|
| 362 |
def check_direct_match(query):
|
| 363 |
-
|
| 364 |
-
|
| 365 |
query_lower = query.lower().strip('?').strip()
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
is_org_admin_query = _is_org_admin_focused(query_lower) and not is_app_query # Prioritera app-fokus
|
| 369 |
-
|
| 370 |
-
# 1. App-specifika frågor
|
| 371 |
-
if is_app_query:
|
| 372 |
-
print(f"INFO: check_direct_match - Query klassad som APP-FOKUSERAD: '{query}'")
|
| 373 |
-
payment_prefixes = ["hur ändrar jag", "hur byter jag", "hur uppdaterar jag", "hur lägger jag till", "hur adderar jag", "hur registrerar jag"]
|
| 374 |
-
app_payment_terms_combined = system_keywords.get("betalning_privat", []) + ["betalkort", "kort", "betalmedel", "betalningsmetod"]
|
| 375 |
-
|
| 376 |
-
if any(query_lower.startswith(prefix) for prefix in payment_prefixes) and \
|
| 377 |
-
any(term in query_lower for term in app_payment_terms_combined):
|
| 378 |
-
payment_answer = """Så här lägger du till/ändrar betalkort:
|
| 379 |
-
1. Öppna ChargeNode-appen
|
| 380 |
-
2. Tryck på 'Meny' (hamburgerikon) i nedre menyn
|
| 381 |
-
3. Välj 'Mina betalsätt' eller 'Betalningsmetoder'
|
| 382 |
-
4. För att lägga till nytt kort: Tryck på 'Lägg till kort' eller '+' knappen
|
| 383 |
-
För att ersätta befintligt kort: Tryck på 'Ersätt kort'
|
| 384 |
-
5. Godkänn våra villkor
|
| 385 |
-
6. Tryck på 'Kortbetalning' under "bekräfta för auktorisering"
|
| 386 |
-
7. Lägg in dina kortuppgifter
|
| 387 |
-
8. Bekräfta med BankID
|
| 388 |
-
|
| 389 |
-
OBS! Se till att kortet har pengar och att det är upplåst för internetbetalningar."""
|
| 390 |
-
print(f"DEBUG: Direkt matchning (hårdkodad app-betalning) för: {query}")
|
| 391 |
-
return payment_answer
|
| 392 |
-
|
| 393 |
-
if query_lower in faq_dict:
|
| 394 |
-
# För app-frågor, returnera om nyckeln INTE ser ut som en org-admin-specifik nyckel
|
| 395 |
-
if not any(org_key_sub in query_lower for org_key_sub in organization_faq_keys_substrings):
|
| 396 |
-
print(f"DEBUG: Direkt matchning (FAQ, app-fokus) för: {query}")
|
| 397 |
-
return faq_dict[query_lower]
|
| 398 |
-
|
| 399 |
-
# Fuzzy matchning för app-frågor
|
| 400 |
-
for key, value in faq_dict.items():
|
| 401 |
-
if any(org_key_sub in key.lower() for org_key_sub in organization_faq_keys_substrings):
|
| 402 |
-
continue # Hoppa över organisationsspecifika FAQ-nycklar
|
| 403 |
-
|
| 404 |
-
# Enkel fuzzy: minst två gemensamma ord och nyckelord som "ändra"
|
| 405 |
-
key_lower = key.lower()
|
| 406 |
-
if ("ändra" in query_lower or "byta" in query_lower or "uppdatera" in query_lower) and \
|
| 407 |
-
("ändra" in key_lower or "byta" in key_lower or "uppdatera" in key_lower):
|
| 408 |
-
query_terms = set(re.findall(r'\b\w+\b', query_lower)) # Hitta hela ord
|
| 409 |
-
key_terms = set(re.findall(r'\b\w+\b', key_lower))
|
| 410 |
-
if len(query_terms.intersection(key_terms)) >= 2:
|
| 411 |
-
print(f"DEBUG: Fuzzy matchning (FAQ, app-fokus) för: '{query}' med nyckel '{key}'")
|
| 412 |
-
return value
|
| 413 |
-
print(f"INFO: App-fokuserad fråga '{query}' - ingen app-specifik FAQ-matchning, låter RAG hantera.")
|
| 414 |
-
return None # Faller igenom till RAG för app-frågor utan direktträff
|
| 415 |
-
|
| 416 |
-
# 2. Organisations-admin-specifika frågor
|
| 417 |
-
elif is_org_admin_query:
|
| 418 |
-
print(f"INFO: check_direct_match - Query klassad som ORG-ADMIN-FOKUSERAD: '{query}'")
|
| 419 |
-
if query_lower in faq_dict:
|
| 420 |
-
# För org-admin-frågor, returnera endast om nyckeln (frågan) ser org-specifik ut
|
| 421 |
-
if any(org_key_sub in query_lower for org_key_sub in organization_faq_keys_substrings):
|
| 422 |
-
print(f"DEBUG: Direkt matchning (FAQ, org-admin-fokus via query_lower check) för: {query}")
|
| 423 |
-
return faq_dict[query_lower]
|
| 424 |
-
|
| 425 |
-
# Fuzzy matchning för org-admin-frågor
|
| 426 |
-
for key, value in faq_dict.items():
|
| 427 |
-
key_lower = key.lower()
|
| 428 |
-
# Matcha endast med nycklar som är tydligt organisationsspecifika
|
| 429 |
-
if not any(org_key_sub in key_lower for org_key_sub in organization_faq_keys_substrings):
|
| 430 |
-
continue
|
| 431 |
-
|
| 432 |
-
if ("ändra" in query_lower or "logga in" in query_lower or "hantera" in query_lower) and \
|
| 433 |
-
("ändra" in key_lower or "logga in" in key_lower or "hantera" in key_lower or \
|
| 434 |
-
any(org_key_sub in key_lower for org_key_sub in organization_faq_keys_substrings) ): # Förstärk att nyckeln är org
|
| 435 |
-
query_terms = set(re.findall(r'\b\w+\b', query_lower))
|
| 436 |
-
key_terms = set(re.findall(r'\b\w+\b', key_lower))
|
| 437 |
-
if len(query_terms.intersection(key_terms)) >= 2:
|
| 438 |
-
print(f"DEBUG: Fuzzy matchning (FAQ, org-admin-fokus) för: '{query}' med nyckel '{key}'")
|
| 439 |
-
return value
|
| 440 |
-
print(f"INFO: Org-admin fråga '{query}' - ingen specifik org-FAQ-matchning, låter RAG hantera.")
|
| 441 |
-
return None
|
| 442 |
-
|
| 443 |
-
# 3. Fallback till generell FAQ-matchning om kontexten är oklar
|
| 444 |
-
print(f"INFO: check_direct_match - Query klassad som OKLAR/GENERELL: '{query}'")
|
| 445 |
if query_lower in faq_dict:
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
return faq_dict[query_lower]
|
| 450 |
-
|
| 451 |
-
# Generell fuzzy matchning
|
| 452 |
for key, value in faq_dict.items():
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
if
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
if any(org_key_sub in key_lower for org_key_sub in organization_faq_keys_substrings) and \
|
| 460 |
-
not any(org_key_sub in query_lower for org_key_sub in organization_faq_keys_substrings):
|
| 461 |
-
continue # Hoppa över om nyckeln är org-specifik men frågan inte är det
|
| 462 |
-
|
| 463 |
-
if ("ändra" in query_lower or "byta" in query_lower or "hur gör jag" in query_lower) and \
|
| 464 |
-
("ändra" in key_lower or "byta" in key_lower or "hur" in key_lower ) :
|
| 465 |
-
query_terms = set(re.findall(r'\b\w+\b', query_lower))
|
| 466 |
-
key_terms = set(re.findall(r'\b\w+\b', key_lower))
|
| 467 |
-
if len(query_terms.intersection(key_terms)) >= 1: # Lägre tröskel för generell fallback
|
| 468 |
-
print(f"DEBUG: Fuzzy matchning (FAQ, fallback generell) för: '{query}' med nyckel '{key}'")
|
| 469 |
-
return value
|
| 470 |
-
|
| 471 |
-
print(f"INFO: Ingen direkt FAQ-matchning alls för '{query}', låter RAG hantera.")
|
| 472 |
return None
|
| 473 |
|
| 474 |
def retrieve_context(query, k=RETRIEVAL_K):
|
| 475 |
-
|
|
|
|
|
|
|
| 476 |
|
|
|
|
| 477 |
direct_match = check_direct_match(query)
|
| 478 |
if direct_match:
|
| 479 |
-
print(f"
|
| 480 |
return f"Fråga: {query}\nSvar: {direct_match}", ["direct_match"]
|
| 481 |
|
| 482 |
-
|
| 483 |
if embedder is None or index is None or index.ntotal == 0:
|
| 484 |
-
print("
|
| 485 |
return "", []
|
| 486 |
|
| 487 |
query_embedding = embedder.encode([query], convert_to_numpy=True)
|
|
|
|
| 488 |
query_embedding_norm = np.linalg.norm(query_embedding)
|
| 489 |
if query_embedding_norm == 0: query_embedding_norm = 1e-10
|
| 490 |
query_embedding = query_embedding / query_embedding_norm
|
| 491 |
|
| 492 |
D, I = index.search(query_embedding, k)
|
| 493 |
retrieved, sources_set = [], set()
|
| 494 |
-
|
| 495 |
-
# ÄNDRAT: Använd globala 'chunks' och 'chunk_sources' som fylls av initialize_embeddings()
|
| 496 |
-
# Säkerställ att dessa globala variabler faktiskt innehåller data
|
| 497 |
-
if not chunks or not chunk_sources:
|
| 498 |
-
print("VARNING: Globala 'chunks' eller 'chunk_sources' är tomma. RAG kommer inte fungera korrekt.")
|
| 499 |
-
return "", []
|
| 500 |
-
|
| 501 |
for idx in I[0]:
|
| 502 |
-
if 0 <= idx < len(chunks):
|
| 503 |
retrieved.append(chunks[idx])
|
| 504 |
-
|
| 505 |
-
if idx < len(chunk_sources): # Säkerhetskoll
|
| 506 |
-
sources_set.add(chunk_sources[idx])
|
| 507 |
-
else:
|
| 508 |
-
sources_set.add("okänd_källa_pga_index_fel") # Fallback
|
| 509 |
-
|
| 510 |
-
if not retrieved:
|
| 511 |
-
print(f"DEBUG: retrieve_context - RAG hittade inga chunks för: {query}")
|
| 512 |
-
else:
|
| 513 |
-
print(f"DEBUG: retrieve_context - RAG hittade {len(retrieved)} chunks för: {query} från källor: {list(sources_set)}")
|
| 514 |
return " ".join(retrieved), list(sources_set)
|
| 515 |
|
| 516 |
-
#
|
| 517 |
-
# Dessa delar antas vara i stort sett korrekta från tidigare granskning,
|
| 518 |
-
# förutsatt att de globala nyckelordsvariablerna är korrekt definierade.
|
| 519 |
-
# Jag har bytt namn på vissa lokala variabler i Gradio-funktionerna för att undvika skuggning.
|
| 520 |
-
|
| 521 |
prompt_template = load_prompt()
|
| 522 |
|
| 523 |
def format_chat_history_for_claude(chat_history):
|
|
|
|
|
|
|
| 524 |
recent_history = chat_history[-10:] if len(chat_history) > 10 else chat_history
|
|
|
|
| 525 |
messages = []
|
| 526 |
-
for
|
| 527 |
-
if
|
| 528 |
messages.append({
|
| 529 |
-
"role":
|
| 530 |
-
"content":
|
| 531 |
})
|
|
|
|
| 532 |
return messages
|
| 533 |
|
| 534 |
def generate_answer(query, chat_history=None):
|
| 535 |
-
|
|
|
|
|
|
|
| 536 |
|
| 537 |
if not context.strip():
|
| 538 |
-
print(
|
| 539 |
-
|
|
|
|
| 540 |
system_prompt = prompt_template
|
| 541 |
-
messages_for_api = [] # ÄNDRAT: Nytt namn för att undvika konflikt
|
| 542 |
|
| 543 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
formatted_history = format_chat_history_for_claude(chat_history[:-1])
|
| 545 |
-
|
| 546 |
|
|
|
|
| 547 |
user_message_content = f"Relevant kontext för frågan:\n{context}\n\nMin fråga är: {query}"
|
| 548 |
if not context.strip():
|
| 549 |
user_message_content = f"Min fråga är: {query}"
|
| 550 |
|
| 551 |
-
|
| 552 |
|
| 553 |
try:
|
|
|
|
| 554 |
response = anthropic_client.messages.create(
|
| 555 |
model=MODEL_NAME,
|
| 556 |
max_tokens=1024,
|
| 557 |
temperature=0.3,
|
| 558 |
system=system_prompt,
|
| 559 |
-
messages=
|
| 560 |
)
|
| 561 |
answer = response.content[0].text
|
| 562 |
-
# NYTT: Lägg till källor om de finns och inte bara är 'direct_match'
|
| 563 |
-
if sources and sources != ["direct_match"]:
|
| 564 |
-
source_info = f"\n\n📚 Källor: {', '.join(set(s for s in sources if s))}" # Filtrera bort None/tomma källor
|
| 565 |
-
answer += source_info
|
| 566 |
-
|
| 567 |
return answer + "\n\nAI-genererat. Otillräcklig hjälp? Kontakta support@chargenode.eu eller 010-2051055"
|
| 568 |
except Exception as e:
|
| 569 |
print(f"Fel vid API-anrop: {str(e)}")
|
|
@@ -571,18 +403,39 @@ def generate_answer(query, chat_history=None):
|
|
| 571 |
|
| 572 |
# --- Slack Integration ---
|
| 573 |
def send_to_slack(subject, content, color="#2a9d8f"):
|
|
|
|
| 574 |
webhook_url = os.environ.get("SLACK_WEBHOOK_URL")
|
| 575 |
if not webhook_url:
|
| 576 |
print("Slack webhook URL saknas")
|
| 577 |
return False
|
|
|
|
| 578 |
try:
|
|
|
|
| 579 |
payload = {
|
| 580 |
"blocks": [
|
| 581 |
-
{
|
| 582 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
]
|
| 584 |
}
|
| 585 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
if response.status_code == 200:
|
| 587 |
print(f"Slack-meddelande skickat: {subject}")
|
| 588 |
return True
|
|
@@ -595,36 +448,52 @@ def send_to_slack(subject, content, color="#2a9d8f"):
|
|
| 595 |
|
| 596 |
# --- Feedback & Like-funktion ---
|
| 597 |
def vote(data: gr.LikeData):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 598 |
feedback_type = "up" if data.liked else "down"
|
| 599 |
-
global last_log
|
| 600 |
-
|
| 601 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 602 |
"feedback": feedback_type,
|
| 603 |
"bot_reply": data.value if not isinstance(data.value, dict) else data.value.get("value")
|
| 604 |
}
|
| 605 |
-
|
| 606 |
-
|
|
|
|
| 607 |
"session_id": last_log.get("session_id"),
|
| 608 |
"user_message": last_log.get("user_message"),
|
| 609 |
})
|
| 610 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
try:
|
| 612 |
if feedback_type == "down" and last_log:
|
| 613 |
feedback_message = f"""
|
| 614 |
*⚠️ Negativ feedback registrerad*
|
|
|
|
| 615 |
*Fråga:* {last_log.get('user_message', 'Okänd fråga')}
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
| 617 |
threading.Thread(
|
| 618 |
target=lambda: send_to_slack("Negativ feedback", feedback_message, "#ff0000"),
|
| 619 |
daemon=True
|
| 620 |
).start()
|
| 621 |
except Exception as e:
|
| 622 |
print(f"Kunde inte skicka feedback till Slack: {e}")
|
|
|
|
| 623 |
return
|
| 624 |
|
| 625 |
# --- Rapportering ---
|
| 626 |
def read_logs():
|
| 627 |
-
|
|
|
|
| 628 |
try:
|
| 629 |
if os.path.exists(log_file_path):
|
| 630 |
with open(log_file_path, "r", encoding="utf-8") as file:
|
|
@@ -632,340 +501,501 @@ def read_logs():
|
|
| 632 |
for line in file:
|
| 633 |
line_count += 1
|
| 634 |
try:
|
| 635 |
-
|
| 636 |
-
|
| 637 |
except json.JSONDecodeError as e:
|
| 638 |
print(f"Varning: Kunde inte tolka rad {line_count}: {e}")
|
| 639 |
continue
|
| 640 |
-
print(f"Läste {len(
|
| 641 |
else:
|
| 642 |
print(f"Loggfil saknas: {log_file_path}")
|
| 643 |
except Exception as e:
|
| 644 |
print(f"Fel vid läsning av loggfil: {e}")
|
| 645 |
-
return
|
| 646 |
-
|
| 647 |
-
def get_latest_conversations(
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
'
|
| 654 |
-
'
|
|
|
|
| 655 |
})
|
| 656 |
-
if len(
|
| 657 |
break
|
| 658 |
-
return
|
| 659 |
|
| 660 |
-
def get_feedback_stats(
|
|
|
|
| 661 |
feedback_count = {"up": 0, "down": 0}
|
| 662 |
negative_feedback_examples = []
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
|
|
|
| 666 |
if feedback in feedback_count:
|
| 667 |
feedback_count[feedback] += 1
|
| 668 |
-
|
|
|
|
|
|
|
| 669 |
negative_feedback_examples.append({
|
| 670 |
-
'user_message':
|
| 671 |
-
'bot_reply':
|
| 672 |
})
|
|
|
|
| 673 |
return feedback_count, negative_feedback_examples
|
| 674 |
|
| 675 |
def generate_monthly_stats(days=30):
|
|
|
|
| 676 |
print(f"Genererar statistik för de senaste {days} dagarna...")
|
| 677 |
-
|
| 678 |
-
|
|
|
|
|
|
|
|
|
|
| 679 |
return {"error": "Inga loggar hittades för den angivna perioden"}
|
| 680 |
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
|
|
|
| 684 |
|
| 685 |
-
for
|
| 686 |
-
if 'timestamp' in
|
| 687 |
try:
|
| 688 |
-
log_date = datetime.strptime(
|
| 689 |
if log_date >= cutoff_date:
|
| 690 |
-
|
| 691 |
-
except
|
| 692 |
-
pass
|
| 693 |
|
| 694 |
-
|
| 695 |
-
if not
|
| 696 |
return {"error": f"Inga loggar hittades för de senaste {days} dagarna"}
|
| 697 |
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
|
|
|
| 704 |
positive_feedback = sum(1 for log in feedback_logs if log.get('feedback') == 'up')
|
| 705 |
negative_feedback = sum(1 for log in feedback_logs if log.get('feedback') == 'down')
|
| 706 |
feedback_ratio = (positive_feedback / len(feedback_logs) * 100) if feedback_logs else 0
|
| 707 |
-
|
|
|
|
|
|
|
| 708 |
avg_response_time = sum(response_times) / len(response_times) if response_times else 0
|
|
|
|
|
|
|
| 709 |
platforms = {}
|
| 710 |
browsers = {}
|
| 711 |
operating_systems = {}
|
| 712 |
-
for log in
|
| 713 |
-
if 'platform' in log:
|
| 714 |
-
|
| 715 |
-
if '
|
|
|
|
|
|
|
|
|
|
| 716 |
|
|
|
|
| 717 |
report = {
|
| 718 |
"period": f"Senaste {days} dagarna",
|
| 719 |
-
"generated_at":
|
| 720 |
-
"basic_stats": {
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 724 |
}
|
|
|
|
| 725 |
return report
|
| 726 |
|
| 727 |
-
|
| 728 |
def simple_status_report():
|
|
|
|
| 729 |
print("Genererar statusrapport för Slack...")
|
|
|
|
| 730 |
try:
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
|
|
|
|
|
|
|
|
|
| 734 |
|
| 735 |
-
if 'error' in
|
| 736 |
-
|
| 737 |
-
return send_to_slack(
|
| 738 |
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
|
|
|
| 742 |
|
| 743 |
-
|
|
|
|
|
|
|
| 744 |
*Basstatistik* (senaste 7 dagarna)
|
| 745 |
- Totalt antal konversationer: {basic['total_conversations']}
|
| 746 |
- Unika sessioner: {basic['unique_sessions']}
|
| 747 |
- Unika användare: {basic['unique_users']}
|
| 748 |
- Genomsnittlig svarstid: {perf['avg_response_time']} sekunder
|
|
|
|
| 749 |
*Feedback*
|
| 750 |
-
- 👍 Tumme upp: {
|
| 751 |
-
- 👎 Tumme ned: {
|
| 752 |
-
- Nöjdhet: {
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
> *
|
| 764 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 765 |
except Exception as e:
|
| 766 |
print(f"Fel vid generering av statusrapport: {e}")
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
|
|
|
|
|
|
| 770 |
|
| 771 |
-
def send_support_to_slack(
|
|
|
|
| 772 |
try:
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 785 |
- *Tidpunkt:* {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
|
|
|
| 786 |
*Chatthistorik:*
|
| 787 |
-
{
|
| 788 |
-
|
|
|
|
|
|
|
|
|
|
| 789 |
except Exception as e:
|
| 790 |
print(f"Fel vid sändning av support till Slack: {type(e).__name__}: {e}")
|
| 791 |
return False
|
| 792 |
|
| 793 |
# --- Schemaläggning av rapporter ---
|
| 794 |
def run_scheduler():
|
|
|
|
|
|
|
| 795 |
schedule.every().day.at("08:00").do(simple_status_report)
|
| 796 |
schedule.every().day.at("12:00").do(simple_status_report)
|
| 797 |
schedule.every().day.at("17:00").do(simple_status_report)
|
|
|
|
|
|
|
| 798 |
schedule.every().monday.at("09:00").do(lambda: send_to_slack(
|
| 799 |
"Veckostatistik",
|
| 800 |
f"*ChargeNode AI Bot - Veckostatistik*\n\n{json.dumps(generate_monthly_stats(7), indent=2)}",
|
| 801 |
"#3498db"
|
| 802 |
))
|
|
|
|
| 803 |
while True:
|
| 804 |
schedule.run_pending()
|
| 805 |
-
time.sleep(60)
|
| 806 |
|
|
|
|
| 807 |
scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
|
| 808 |
scheduler_thread.start()
|
| 809 |
|
| 810 |
# --- Gradio UI ---
|
| 811 |
initial_chat = [{"role": "assistant", "content": "Detta är ChargeNode's AI bot. Hur kan jag hjälpa dig idag?"}]
|
| 812 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 813 |
|
| 814 |
with gr.Blocks(css=custom_css, title="ChargeNode Kundtjänst") as app:
|
| 815 |
gr.Markdown("Ställ din fråga om ChargeNodes produkter och tjänster nedan. Om du inte gillar botten, så ring oss gärna på 010 – 205 10 55")
|
| 816 |
|
|
|
|
| 817 |
with gr.Group(visible=True) as chat_interface:
|
| 818 |
-
|
| 819 |
-
|
| 820 |
|
| 821 |
with gr.Row():
|
| 822 |
-
|
| 823 |
|
| 824 |
with gr.Row():
|
| 825 |
with gr.Column(scale=1):
|
| 826 |
-
|
| 827 |
with gr.Column(scale=1):
|
| 828 |
-
|
| 829 |
|
|
|
|
| 830 |
with gr.Group(visible=False) as support_interface:
|
| 831 |
gr.Markdown("### Vänligen fyll i din områdeskod, uttagsnummer och din email adress")
|
|
|
|
| 832 |
with gr.Group(elem_classes="gr-form"):
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
|
| 837 |
gr.Markdown("### Chat som skickas till support:")
|
| 838 |
-
|
| 839 |
|
| 840 |
with gr.Row():
|
| 841 |
-
|
| 842 |
-
|
| 843 |
|
|
|
|
| 844 |
with gr.Group(visible=False) as success_interface:
|
| 845 |
gr.Markdown("Tack för att du kontaktar support@chargenode.eu. Vi återkommer inom kort", elem_classes="success-message")
|
| 846 |
-
|
| 847 |
|
| 848 |
-
def respond(
|
| 849 |
global last_log
|
| 850 |
-
|
| 851 |
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
op_elapsed = round(time.time() - op_start_time, 2) # ÄNDRAT namn
|
| 855 |
|
| 856 |
-
|
| 857 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 858 |
|
| 859 |
-
|
| 860 |
-
|
|
|
|
| 861 |
|
| 862 |
-
|
| 863 |
|
| 864 |
ua_str = request.headers.get("user-agent", "")
|
| 865 |
ref = request.headers.get("referer", "")
|
| 866 |
-
|
| 867 |
ua = parse_ua(ua_str)
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
if "chargenode.eu" in ref:
|
| 873 |
-
|
| 874 |
-
elif "
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 881 |
}
|
| 882 |
-
safe_append_to_log(log_data_entry)
|
| 883 |
-
last_log = log_data_entry
|
| 884 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 885 |
try:
|
| 886 |
-
|
| 887 |
-
*
|
| 888 |
-
|
| 889 |
-
*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 890 |
threading.Thread(
|
| 891 |
-
target=lambda: send_to_slack(f"Ny konversation",
|
|
|
|
| 892 |
).start()
|
| 893 |
except Exception as e:
|
| 894 |
print(f"Kunde inte skicka konversation till Slack: {e}")
|
| 895 |
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 911 |
return {
|
| 912 |
-
chat_interface: gr.
|
| 913 |
-
|
|
|
|
|
|
|
| 914 |
}
|
| 915 |
|
| 916 |
-
def
|
| 917 |
return {
|
| 918 |
-
chat_interface: gr.
|
| 919 |
-
|
|
|
|
| 920 |
}
|
| 921 |
|
| 922 |
-
def
|
| 923 |
-
|
|
|
|
|
|
|
| 924 |
validation_errors = []
|
| 925 |
-
|
| 926 |
-
if
|
| 927 |
-
|
| 928 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 929 |
|
| 930 |
if validation_errors:
|
|
|
|
| 931 |
error_message_md = "**Fel:**\n" + "\n".join(f"- {err}" for err in validation_errors)
|
| 932 |
return {
|
| 933 |
-
chat_interface: gr.update(visible=False),
|
| 934 |
-
|
|
|
|
|
|
|
| 935 |
}
|
|
|
|
| 936 |
try:
|
| 937 |
-
|
| 938 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 939 |
return {
|
| 940 |
-
chat_interface: gr.update(visible=False),
|
|
|
|
| 941 |
success_interface: gr.update(visible=True)
|
| 942 |
}
|
| 943 |
else:
|
| 944 |
-
|
|
|
|
| 945 |
return {
|
| 946 |
-
chat_interface: gr.update(visible=False),
|
| 947 |
-
|
|
|
|
|
|
|
| 948 |
}
|
| 949 |
except Exception as e:
|
| 950 |
-
|
|
|
|
| 951 |
return {
|
| 952 |
-
chat_interface: gr.update(visible=False),
|
| 953 |
-
|
|
|
|
|
|
|
| 954 |
}
|
| 955 |
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
[
|
| 964 |
-
[chat_interface, support_interface, success_interface,
|
| 965 |
)
|
| 966 |
|
|
|
|
| 967 |
print("Förbereder embedding-modell och index...")
|
| 968 |
-
initialize_embeddings()
|
| 969 |
print("Embedding-modell och index redo!")
|
| 970 |
|
| 971 |
if __name__ == "__main__":
|
|
|
|
| 3 |
import time
|
| 4 |
import requests
|
| 5 |
from anthropic import Anthropic
|
|
|
|
| 6 |
import gradio as gr
|
| 7 |
import pandas as pd
|
| 8 |
from huggingface_hub import CommitScheduler
|
|
|
|
| 15 |
import numpy as np
|
| 16 |
import faiss
|
| 17 |
import re
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# --- Konfiguration ---
|
| 20 |
CHARGENODE_URL = "https://www.chargenode.eu"
|
| 21 |
MAX_CHUNK_SIZE = 2000
|
| 22 |
CHUNK_OVERLAP = 200
|
| 23 |
RETRIEVAL_K = 5
|
| 24 |
+
|
| 25 |
+
# Uppdaterad modell till Sonnet 4
|
| 26 |
MODEL_NAME = "claude-sonnet-4-20250514"
|
|
|
|
| 27 |
|
| 28 |
+
# Kontrollera om vi kör i Hugging Face-miljön
|
| 29 |
IS_HUGGINGFACE = os.environ.get("SPACE_ID") is not None
|
| 30 |
|
| 31 |
+
# Lägg till Anthropic API-nyckel och klient
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY")
|
| 33 |
if not ANTHROPIC_API_KEY:
|
| 34 |
raise ValueError("ANTHROPIC_API_KEY saknas")
|
|
|
|
| 38 |
os.makedirs(log_folder, exist_ok=True)
|
| 39 |
log_file_path = os.path.join(log_folder, "conversation_log_v2.txt")
|
| 40 |
|
| 41 |
+
# Skapa en tom loggfil om den inte finns
|
| 42 |
if not os.path.exists(log_file_path):
|
| 43 |
with open(log_file_path, "w", encoding="utf-8") as f:
|
| 44 |
f.write("")
|
|
|
|
| 48 |
if not hf_token:
|
| 49 |
raise ValueError("HF_TOKEN saknas")
|
| 50 |
|
| 51 |
+
# Minsta möjliga konfiguration som bör fungera
|
| 52 |
scheduler = CommitScheduler(
|
| 53 |
repo_id="ChargeNodeEurope/logfiles",
|
| 54 |
repo_type="dataset",
|
| 55 |
folder_path=log_folder,
|
| 56 |
path_in_repo="logs_v2",
|
| 57 |
+
every=300, # Vänta 5 minuter
|
| 58 |
token=hf_token
|
| 59 |
)
|
| 60 |
|
| 61 |
# --- Globala variabler ---
|
| 62 |
+
last_log = None # Sparar loggdata från senaste svar för feedback
|
| 63 |
+
|
| 64 |
+
# Globala variabler för embeddings
|
| 65 |
embedder = None
|
| 66 |
embeddings = None
|
| 67 |
index = None
|
| 68 |
chunks = []
|
| 69 |
chunk_sources = []
|
| 70 |
+
faq_dict = {} # Dictionary för direktmatchning av vanliga frågor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
# --- Förbättrad loggfunktion ---
|
| 73 |
def safe_append_to_log(log_entry):
|
| 74 |
+
"""Säker metod för att lägga till loggdata utan att förlora historisk information."""
|
| 75 |
try:
|
| 76 |
+
# Öppna filen i append-läge
|
| 77 |
with open(log_file_path, "a", encoding="utf-8") as log_file:
|
| 78 |
log_json = json.dumps(log_entry)
|
| 79 |
log_file.write(log_json + "\n")
|
| 80 |
+
log_file.flush() # Säkerställ att data skrivs till disk omedelbart
|
| 81 |
+
|
| 82 |
print(f"Loggpost tillagd: {log_entry.get('timestamp', 'okänd tid')}")
|
| 83 |
return True
|
| 84 |
+
|
| 85 |
except Exception as e:
|
| 86 |
print(f"Fel vid loggning: {e}")
|
| 87 |
+
|
| 88 |
+
# Försök skapa mappen om den inte finns
|
| 89 |
try:
|
| 90 |
os.makedirs(os.path.dirname(log_file_path), exist_ok=True)
|
| 91 |
+
|
| 92 |
+
# Försök igen
|
| 93 |
with open(log_file_path, "a", encoding="utf-8") as log_file:
|
| 94 |
log_json = json.dumps(log_entry)
|
| 95 |
log_file.write(log_json + "\n")
|
| 96 |
+
|
| 97 |
print("Loggpost tillagd efter återhämtning")
|
| 98 |
return True
|
| 99 |
+
|
| 100 |
except Exception as retry_error:
|
| 101 |
print(f"Kritiskt fel vid loggning: {retry_error}")
|
| 102 |
return False
|
| 103 |
|
| 104 |
# --- Laddar textkällor ---
|
| 105 |
def load_local_files():
|
| 106 |
+
"""Laddar alla lokala filer och returnerar som en sammanhängande text."""
|
| 107 |
uploaded_text = ""
|
| 108 |
+
allowed = [".txt", ".csv", ".xls", ".xlsx"] # Tog bort .docx och .pdf
|
| 109 |
excluded = ["requirements.txt", "app.py", "conversation_log.txt", "conversation_log_v2.txt", "secrets", "prompt.txt"]
|
| 110 |
for file in os.listdir("."):
|
| 111 |
if file.lower().endswith(tuple(allowed)) and file not in excluded:
|
| 112 |
try:
|
|
|
|
| 113 |
if file.endswith(".txt"):
|
| 114 |
with open(file, "r", encoding="utf-8") as f:
|
| 115 |
content = f.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
elif file.endswith(".csv"):
|
| 117 |
content = pd.read_csv(file).to_string()
|
| 118 |
elif file.endswith((".xls", ".xlsx")):
|
| 119 |
+
if file == "FAQ stadat.xlsx":
|
| 120 |
df = pd.read_excel(file)
|
| 121 |
rows = []
|
| 122 |
for index, row in df.iterrows():
|
| 123 |
+
# Start with the required fields
|
| 124 |
+
row_text = f"Fråga: {row['Fråga']}\nSvar: {row['Svar']}"
|
| 125 |
+
|
| 126 |
+
# Add kategori if it exists in the dataframe
|
| 127 |
+
if 'kategori' in df.columns:
|
| 128 |
row_text += f"\nKategori: {row['kategori']}"
|
| 129 |
+
elif 'Kategori' in df.columns: # Also check for capitalized version
|
| 130 |
row_text += f"\nKategori: {row['Kategori']}"
|
| 131 |
+
|
| 132 |
rows.append(row_text)
|
| 133 |
content = "\n\n".join(rows)
|
| 134 |
else:
|
| 135 |
content = pd.read_excel(file).to_string()
|
| 136 |
+
uploaded_text += f"\n\nFIL: {file}\n{content}"
|
|
|
|
|
|
|
| 137 |
except Exception as e:
|
| 138 |
print(f"Fel vid läsning av {file}: {str(e)}")
|
| 139 |
return uploaded_text.strip()
|
| 140 |
|
| 141 |
def load_prompt():
|
| 142 |
+
"""Läser in system-prompts från prompt.txt med bättre felhantering."""
|
| 143 |
try:
|
| 144 |
with open("prompt.txt", "r", encoding="utf-8") as f:
|
| 145 |
prompt_content = f.read().strip()
|
|
|
|
| 156 |
|
| 157 |
# --- Förbättrad chunking ---
|
| 158 |
def prepare_chunks(text_data):
|
| 159 |
+
"""Delar upp texten i mindre segment för embedding och sökning."""
|
| 160 |
+
chunks_list, sources_list = [], []
|
| 161 |
global faq_dict
|
| 162 |
|
| 163 |
+
for source, text in text_data.items():
|
| 164 |
+
# Split text into paragraph-sized chunks
|
| 165 |
paragraphs = [p for p in text.split("\n") if p.strip()]
|
| 166 |
|
| 167 |
+
# Process FAQ-specific content better
|
| 168 |
i = 0
|
| 169 |
current_file_chunks = []
|
| 170 |
+
current_file_sources = []
|
| 171 |
while i < len(paragraphs):
|
| 172 |
+
# Start a new chunk
|
| 173 |
current_chunk = ""
|
| 174 |
start_idx = i
|
| 175 |
|
| 176 |
+
# Check for FAQ format
|
| 177 |
if i < len(paragraphs) and paragraphs[i].startswith("Fråga:"):
|
| 178 |
+
question = paragraphs[i][7:].strip() # Extract the question text
|
| 179 |
current_chunk = paragraphs[i]
|
| 180 |
i += 1
|
| 181 |
|
| 182 |
+
# Add content until we reach the next question or MAX_CHUNK_SIZE
|
| 183 |
while i < len(paragraphs) and not paragraphs[i].startswith("Fråga:"):
|
| 184 |
+
# Add this paragraph if it doesn't exceed chunk size
|
| 185 |
if len(current_chunk) + len(paragraphs[i]) + 1 <= MAX_CHUNK_SIZE:
|
| 186 |
current_chunk += "\n" + paragraphs[i]
|
| 187 |
else:
|
| 188 |
+
# If we're already processing a FAQ answer, don't break mid-answer
|
| 189 |
if "Svar:" in current_chunk:
|
| 190 |
+
# We prefer to keep whole answers together, so let's break only if answer is too long
|
| 191 |
+
if len(current_chunk) > MAX_CHUNK_SIZE * 1.5: # Allow some overflow
|
| 192 |
break
|
| 193 |
else:
|
| 194 |
+
current_chunk += "\n" + paragraphs[i]
|
| 195 |
else:
|
| 196 |
break
|
| 197 |
i += 1
|
| 198 |
|
| 199 |
+
# Store FAQ pairs in the dictionary for direct lookup
|
| 200 |
if "Svar:" in current_chunk:
|
| 201 |
answer_start = current_chunk.find("Svar:")
|
| 202 |
answer_text = current_chunk[answer_start + 5:].strip()
|
| 203 |
|
| 204 |
+
# Add the original question to the dictionary
|
| 205 |
+
faq_dict[question.lower()] = answer_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
else:
|
| 207 |
+
# Handle non-FAQ text using sliding window
|
| 208 |
while i < len(paragraphs) and len(current_chunk) + len(paragraphs[i]) + 1 <= MAX_CHUNK_SIZE:
|
| 209 |
if current_chunk:
|
| 210 |
current_chunk += " " + paragraphs[i]
|
|
|
|
| 212 |
current_chunk = paragraphs[i]
|
| 213 |
i += 1
|
| 214 |
|
| 215 |
+
# Save the chunk if it has content
|
| 216 |
if current_chunk.strip():
|
| 217 |
current_file_chunks.append(current_chunk.strip())
|
| 218 |
+
current_file_sources.append(source)
|
| 219 |
|
| 220 |
+
# If we've added a chunk but haven't advanced, we need to move forward
|
| 221 |
+
if i == start_idx:
|
| 222 |
+
i += 1
|
| 223 |
+
|
| 224 |
+
# Create overlapping chunks for better context preservation for THIS source
|
|
|
|
|
|
|
| 225 |
overlap_chunks_for_file = []
|
| 226 |
overlap_sources_for_file = []
|
| 227 |
|
| 228 |
for j in range(len(current_file_chunks)):
|
| 229 |
overlap_chunks_for_file.append(current_file_chunks[j])
|
| 230 |
+
overlap_sources_for_file.append(current_file_sources[j])
|
| 231 |
|
| 232 |
if j < len(current_file_chunks) - 1:
|
| 233 |
+
# Calculate available space in the current chunk
|
| 234 |
space_left = MAX_CHUNK_SIZE - len(current_file_chunks[j])
|
| 235 |
+
|
| 236 |
+
# If there's enough space, add part of the next chunk
|
| 237 |
if space_left >= CHUNK_OVERLAP:
|
| 238 |
+
# Ensure we don't duplicate if chunks are already naturally overlapping significantly
|
| 239 |
+
if not current_file_chunks[j].endswith(current_file_chunks[j+1][:CHUNK_OVERLAP]):
|
| 240 |
+
overlap_text = current_file_chunks[j] + " " + current_file_chunks[j+1][:CHUNK_OVERLAP]
|
| 241 |
+
if len(overlap_text) <= MAX_CHUNK_SIZE: # Ensure overlap doesn't exceed max size
|
|
|
|
|
|
|
| 242 |
overlap_chunks_for_file.append(overlap_text)
|
| 243 |
overlap_sources_for_file.append(current_file_sources[j])
|
| 244 |
|
| 245 |
chunks_list.extend(overlap_chunks_for_file)
|
| 246 |
sources_list.extend(overlap_sources_for_file)
|
| 247 |
+
|
| 248 |
print(f"Genererade {len(chunks_list)} chunks med {len(faq_dict)} FAQ-par")
|
| 249 |
return chunks_list, sources_list
|
| 250 |
|
| 251 |
|
| 252 |
def initialize_embeddings():
|
| 253 |
+
"""Initierar SentenceTransformer och FAISS-index vid första anrop."""
|
| 254 |
global embedder, embeddings, index, chunks, chunk_sources, faq_dict
|
| 255 |
|
| 256 |
if embedder is None:
|
| 257 |
print("Initierar SentenceTransformer och FAISS-index...")
|
| 258 |
+
# Ladda och förbered lokal data
|
| 259 |
print("Laddar textdata...")
|
| 260 |
+
text_data = {"local_files": load_local_files()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
print("Förbereder textsegment...")
|
| 262 |
chunks, chunk_sources = prepare_chunks(text_data)
|
| 263 |
+
print(f"{len(chunks)} segment laddade")
|
| 264 |
|
| 265 |
if not chunks:
|
| 266 |
print("Varning: Inga chunks genererades. Kontrollera textkällor och chunking-logik.")
|
| 267 |
+
# Sätt upp tomma men giltiga strukturer för att undvika fel senare
|
| 268 |
+
embedder = SentenceTransformer('all-MiniLM-L6-v2')
|
| 269 |
embeddings = np.array([]).reshape(0, embedder.get_sentence_embedding_dimension())
|
| 270 |
index = faiss.IndexFlatIP(embedder.get_sentence_embedding_dimension())
|
| 271 |
print("FAISS-index initialiserat tomt då inga chunks fanns.")
|
|
|
|
| 273 |
|
| 274 |
print("Skapar embeddings...")
|
| 275 |
embedder = SentenceTransformer('all-MiniLM-L6-v2')
|
| 276 |
+
embeddings = embedder.encode(chunks, convert_to_numpy=True)
|
| 277 |
|
| 278 |
+
# Normalisera embeddings för IndexFlatIP (dot product)
|
| 279 |
if embeddings.ndim == 2 and embeddings.shape[0] > 0:
|
| 280 |
embeddings_norm = np.linalg.norm(embeddings, axis=1, keepdims=True)
|
| 281 |
+
# Undvik division med noll om någon norm är noll
|
| 282 |
embeddings_norm[embeddings_norm == 0] = 1e-10
|
| 283 |
embeddings = embeddings / embeddings_norm
|
| 284 |
|
|
|
|
| 287 |
print("FAISS-index klart")
|
| 288 |
else:
|
| 289 |
print("Varning: Inga embeddings genererades, FAISS-index kan vara tomt eller ogiltigt.")
|
| 290 |
+
# Fallback: skapa ett tomt index om embeddings är tomma
|
| 291 |
dimension = embedder.get_sentence_embedding_dimension() if embedder else 384
|
| 292 |
index = faiss.IndexFlatIP(dimension)
|
| 293 |
print("FAISS-index initialiserat tomt.")
|
| 294 |
|
| 295 |
print(f"FAQ Dictionary innehåller {len(faq_dict)} nycklar")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
def check_direct_match(query):
|
| 298 |
+
"""Kontrollerar om frågan matchar någon av våra fördefinierade FAQ-svar."""
|
|
|
|
| 299 |
query_lower = query.lower().strip('?').strip()
|
| 300 |
+
|
| 301 |
+
# Check if query directly matches a FAQ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
if query_lower in faq_dict:
|
| 303 |
+
return faq_dict[query_lower]
|
| 304 |
+
|
| 305 |
+
# Check for close matches using pattern matching
|
|
|
|
|
|
|
|
|
|
| 306 |
for key, value in faq_dict.items():
|
| 307 |
+
# Check if key and query share important terms
|
| 308 |
+
query_terms = set(re.findall(r'\w+', query_lower))
|
| 309 |
+
key_terms = set(re.findall(r'\w+', key))
|
| 310 |
+
if len(query_terms.intersection(key_terms)) >= 2: # At least 2 words in common
|
| 311 |
+
return value
|
| 312 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
return None
|
| 314 |
|
| 315 |
def retrieve_context(query, k=RETRIEVAL_K):
|
| 316 |
+
"""Hämtar relevant kontext för frågor med direkt matchning för vanliga frågor."""
|
| 317 |
+
# Säkerställ att modeller är laddade
|
| 318 |
+
initialize_embeddings()
|
| 319 |
|
| 320 |
+
# Först, kolla efter direktmatchningar för vanliga frågor
|
| 321 |
direct_match = check_direct_match(query)
|
| 322 |
if direct_match:
|
| 323 |
+
print(f"Direkt matchning hittad för frågan: {query}")
|
| 324 |
return f"Fråga: {query}\nSvar: {direct_match}", ["direct_match"]
|
| 325 |
|
| 326 |
+
# Om ingen direktmatchning, använd vanlig embedding-sökning
|
| 327 |
if embedder is None or index is None or index.ntotal == 0:
|
| 328 |
+
print("Varning: Embedder eller FAISS-index är inte korrekt initierat eller är tomt. Returnerar tom kontext.")
|
| 329 |
return "", []
|
| 330 |
|
| 331 |
query_embedding = embedder.encode([query], convert_to_numpy=True)
|
| 332 |
+
# Normalisera query_embedding på samma sätt som indexets embeddings
|
| 333 |
query_embedding_norm = np.linalg.norm(query_embedding)
|
| 334 |
if query_embedding_norm == 0: query_embedding_norm = 1e-10
|
| 335 |
query_embedding = query_embedding / query_embedding_norm
|
| 336 |
|
| 337 |
D, I = index.search(query_embedding, k)
|
| 338 |
retrieved, sources_set = [], set()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
for idx in I[0]:
|
| 340 |
+
if 0 <= idx < len(chunks):
|
| 341 |
retrieved.append(chunks[idx])
|
| 342 |
+
sources_set.add(chunk_sources[idx])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
return " ".join(retrieved), list(sources_set)
|
| 344 |
|
| 345 |
+
# Ladda prompt template
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
prompt_template = load_prompt()
|
| 347 |
|
| 348 |
def format_chat_history_for_claude(chat_history):
|
| 349 |
+
"""Formaterar chatthistoriken för Claude API med endast de senaste meddelandena för att undvika token-gränser."""
|
| 350 |
+
# Ta endast de senaste 10 meddelandena för att hålla kontexten hanterbar
|
| 351 |
recent_history = chat_history[-10:] if len(chat_history) > 10 else chat_history
|
| 352 |
+
|
| 353 |
messages = []
|
| 354 |
+
for msg in recent_history:
|
| 355 |
+
if msg["role"] in ["user", "assistant"]:
|
| 356 |
messages.append({
|
| 357 |
+
"role": msg["role"],
|
| 358 |
+
"content": msg["content"]
|
| 359 |
})
|
| 360 |
+
|
| 361 |
return messages
|
| 362 |
|
| 363 |
def generate_answer(query, chat_history=None):
|
| 364 |
+
"""Genererar svar baserat på fråga, chatthistorik och retrieval-baserad kontext med Claude Sonnet 4."""
|
| 365 |
+
# Hämta relevant kontext via RAG istället för hela databasen
|
| 366 |
+
context, sources = retrieve_context(query)
|
| 367 |
|
| 368 |
if not context.strip():
|
| 369 |
+
print("Ingen RAG-kontext hittades. Försöker svara utan.")
|
| 370 |
+
|
| 371 |
+
# System-prompts
|
| 372 |
system_prompt = prompt_template
|
|
|
|
| 373 |
|
| 374 |
+
# Förbered meddelanden för Claude API
|
| 375 |
+
messages = []
|
| 376 |
+
|
| 377 |
+
# Lägg till chatthistorik om den finns och är meningsfull
|
| 378 |
+
if chat_history and len(chat_history) > 1:
|
| 379 |
formatted_history = format_chat_history_for_claude(chat_history[:-1])
|
| 380 |
+
messages.extend(formatted_history)
|
| 381 |
|
| 382 |
+
# Skapa användarmeddelandet med kontext och aktuell fråga
|
| 383 |
user_message_content = f"Relevant kontext för frågan:\n{context}\n\nMin fråga är: {query}"
|
| 384 |
if not context.strip():
|
| 385 |
user_message_content = f"Min fråga är: {query}"
|
| 386 |
|
| 387 |
+
messages.append({"role": "user", "content": user_message_content})
|
| 388 |
|
| 389 |
try:
|
| 390 |
+
# Använd Claude Sonnet 4 med RAG-baserad kontext och chatthistorik
|
| 391 |
response = anthropic_client.messages.create(
|
| 392 |
model=MODEL_NAME,
|
| 393 |
max_tokens=1024,
|
| 394 |
temperature=0.3,
|
| 395 |
system=system_prompt,
|
| 396 |
+
messages=messages
|
| 397 |
)
|
| 398 |
answer = response.content[0].text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
return answer + "\n\nAI-genererat. Otillräcklig hjälp? Kontakta support@chargenode.eu eller 010-2051055"
|
| 400 |
except Exception as e:
|
| 401 |
print(f"Fel vid API-anrop: {str(e)}")
|
|
|
|
| 403 |
|
| 404 |
# --- Slack Integration ---
|
| 405 |
def send_to_slack(subject, content, color="#2a9d8f"):
|
| 406 |
+
"""Basfunktion för att skicka meddelanden till Slack."""
|
| 407 |
webhook_url = os.environ.get("SLACK_WEBHOOK_URL")
|
| 408 |
if not webhook_url:
|
| 409 |
print("Slack webhook URL saknas")
|
| 410 |
return False
|
| 411 |
+
|
| 412 |
try:
|
| 413 |
+
# Formatera meddelandet för Slack
|
| 414 |
payload = {
|
| 415 |
"blocks": [
|
| 416 |
+
{
|
| 417 |
+
"type": "header",
|
| 418 |
+
"text": {
|
| 419 |
+
"type": "plain_text",
|
| 420 |
+
"text": subject
|
| 421 |
+
}
|
| 422 |
+
},
|
| 423 |
+
{
|
| 424 |
+
"type": "section",
|
| 425 |
+
"text": {
|
| 426 |
+
"type": "mrkdwn",
|
| 427 |
+
"text": content
|
| 428 |
+
}
|
| 429 |
+
}
|
| 430 |
]
|
| 431 |
}
|
| 432 |
+
|
| 433 |
+
response = requests.post(
|
| 434 |
+
webhook_url,
|
| 435 |
+
json=payload,
|
| 436 |
+
headers={"Content-Type": "application/json"}
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
if response.status_code == 200:
|
| 440 |
print(f"Slack-meddelande skickat: {subject}")
|
| 441 |
return True
|
|
|
|
| 448 |
|
| 449 |
# --- Feedback & Like-funktion ---
|
| 450 |
def vote(data: gr.LikeData):
|
| 451 |
+
"""
|
| 452 |
+
Hanterar feedback från Gradio's inbyggda like-funktion.
|
| 453 |
+
data.liked är True om upvote, annars False.
|
| 454 |
+
data.value innehåller information om meddelandet.
|
| 455 |
+
"""
|
| 456 |
feedback_type = "up" if data.liked else "down"
|
| 457 |
+
global last_log
|
| 458 |
+
log_entry = {
|
| 459 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 460 |
"feedback": feedback_type,
|
| 461 |
"bot_reply": data.value if not isinstance(data.value, dict) else data.value.get("value")
|
| 462 |
}
|
| 463 |
+
# Om global logdata finns, lägg till ytterligare metadata.
|
| 464 |
+
if last_log:
|
| 465 |
+
log_entry.update({
|
| 466 |
"session_id": last_log.get("session_id"),
|
| 467 |
"user_message": last_log.get("user_message"),
|
| 468 |
})
|
| 469 |
+
|
| 470 |
+
# Använd den förbättrade loggfunktionen
|
| 471 |
+
safe_append_to_log(log_entry)
|
| 472 |
+
|
| 473 |
+
# Skicka feedback till Slack
|
| 474 |
try:
|
| 475 |
if feedback_type == "down" and last_log:
|
| 476 |
feedback_message = f"""
|
| 477 |
*⚠️ Negativ feedback registrerad*
|
| 478 |
+
|
| 479 |
*Fråga:* {last_log.get('user_message', 'Okänd fråga')}
|
| 480 |
+
|
| 481 |
+
*Svar:* {log_entry.get('bot_reply', 'Okänt svar')[:300]}{'...' if len(log_entry.get('bot_reply', '')) > 300 else ''}
|
| 482 |
+
"""
|
| 483 |
+
# Skicka asynkront
|
| 484 |
threading.Thread(
|
| 485 |
target=lambda: send_to_slack("Negativ feedback", feedback_message, "#ff0000"),
|
| 486 |
daemon=True
|
| 487 |
).start()
|
| 488 |
except Exception as e:
|
| 489 |
print(f"Kunde inte skicka feedback till Slack: {e}")
|
| 490 |
+
|
| 491 |
return
|
| 492 |
|
| 493 |
# --- Rapportering ---
|
| 494 |
def read_logs():
|
| 495 |
+
"""Läs alla loggposter från loggfilen."""
|
| 496 |
+
logs = []
|
| 497 |
try:
|
| 498 |
if os.path.exists(log_file_path):
|
| 499 |
with open(log_file_path, "r", encoding="utf-8") as file:
|
|
|
|
| 501 |
for line in file:
|
| 502 |
line_count += 1
|
| 503 |
try:
|
| 504 |
+
log_entry = json.loads(line.strip())
|
| 505 |
+
logs.append(log_entry)
|
| 506 |
except json.JSONDecodeError as e:
|
| 507 |
print(f"Varning: Kunde inte tolka rad {line_count}: {e}")
|
| 508 |
continue
|
| 509 |
+
print(f"Läste {len(logs)} av {line_count} loggposter")
|
| 510 |
else:
|
| 511 |
print(f"Loggfil saknas: {log_file_path}")
|
| 512 |
except Exception as e:
|
| 513 |
print(f"Fel vid läsning av loggfil: {e}")
|
| 514 |
+
return logs
|
| 515 |
+
|
| 516 |
+
def get_latest_conversations(logs, limit=50):
|
| 517 |
+
"""Hämta de senaste frågorna och svaren."""
|
| 518 |
+
conversations = []
|
| 519 |
+
for log in reversed(logs):
|
| 520 |
+
if 'user_message' in log and 'bot_reply' in log:
|
| 521 |
+
conversations.append({
|
| 522 |
+
'user_message': log['user_message'],
|
| 523 |
+
'bot_reply': log['bot_reply'],
|
| 524 |
+
'timestamp': log.get('timestamp', '')
|
| 525 |
})
|
| 526 |
+
if len(conversations) >= limit:
|
| 527 |
break
|
| 528 |
+
return conversations
|
| 529 |
|
| 530 |
+
def get_feedback_stats(logs):
|
| 531 |
+
"""Sammanfatta feedback (tumme upp/ned)."""
|
| 532 |
feedback_count = {"up": 0, "down": 0}
|
| 533 |
negative_feedback_examples = []
|
| 534 |
+
|
| 535 |
+
for log in logs:
|
| 536 |
+
if 'feedback' in log:
|
| 537 |
+
feedback = log.get('feedback')
|
| 538 |
if feedback in feedback_count:
|
| 539 |
feedback_count[feedback] += 1
|
| 540 |
+
|
| 541 |
+
# Samla exempel på negativ feedback
|
| 542 |
+
if feedback == "down" and 'user_message' in log and len(negative_feedback_examples) < 10:
|
| 543 |
negative_feedback_examples.append({
|
| 544 |
+
'user_message': log.get('user_message', 'Okänd fråga'),
|
| 545 |
+
'bot_reply': log.get('bot_reply', 'Okänt svar')
|
| 546 |
})
|
| 547 |
+
|
| 548 |
return feedback_count, negative_feedback_examples
|
| 549 |
|
| 550 |
def generate_monthly_stats(days=30):
|
| 551 |
+
"""Genererar omfattande statistik över botanvändning för den senaste månaden."""
|
| 552 |
print(f"Genererar statistik för de senaste {days} dagarna...")
|
| 553 |
+
|
| 554 |
+
# Hämta loggar
|
| 555 |
+
logs = read_logs()
|
| 556 |
+
|
| 557 |
+
if not logs:
|
| 558 |
return {"error": "Inga loggar hittades för den angivna perioden"}
|
| 559 |
|
| 560 |
+
# Filtrera på datumintervall
|
| 561 |
+
now = datetime.now()
|
| 562 |
+
cutoff_date = now - timedelta(days=days)
|
| 563 |
+
filtered_logs = []
|
| 564 |
|
| 565 |
+
for log in logs:
|
| 566 |
+
if 'timestamp' in log:
|
| 567 |
try:
|
| 568 |
+
log_date = datetime.strptime(log['timestamp'], "%Y-%m-%d %H:%M:%S")
|
| 569 |
if log_date >= cutoff_date:
|
| 570 |
+
filtered_logs.append(log)
|
| 571 |
+
except:
|
| 572 |
+
pass # Hoppa över poster med ogiltigt datum
|
| 573 |
|
| 574 |
+
logs = filtered_logs
|
| 575 |
+
if not logs:
|
| 576 |
return {"error": f"Inga loggar hittades för de senaste {days} dagarna"}
|
| 577 |
|
| 578 |
+
# Basstatistik
|
| 579 |
+
total_conversations = sum(1 for log in logs if 'user_message' in log)
|
| 580 |
+
unique_sessions = len(set(log.get('session_id', 'unknown') for log in logs if 'session_id' in log))
|
| 581 |
+
unique_users = len(set(log.get('user_id', 'unknown') for log in logs if 'user_id' in log))
|
| 582 |
+
|
| 583 |
+
# Feedback-statistik
|
| 584 |
+
feedback_logs = [log for log in logs if 'feedback' in log]
|
| 585 |
positive_feedback = sum(1 for log in feedback_logs if log.get('feedback') == 'up')
|
| 586 |
negative_feedback = sum(1 for log in feedback_logs if log.get('feedback') == 'down')
|
| 587 |
feedback_ratio = (positive_feedback / len(feedback_logs) * 100) if feedback_logs else 0
|
| 588 |
+
|
| 589 |
+
# Svarstidsstatistik
|
| 590 |
+
response_times = [log.get('response_time', 0) for log in logs if 'response_time' in log and isinstance(log.get('response_time'), (int, float))]
|
| 591 |
avg_response_time = sum(response_times) / len(response_times) if response_times else 0
|
| 592 |
+
|
| 593 |
+
# Plattformsstatistik
|
| 594 |
platforms = {}
|
| 595 |
browsers = {}
|
| 596 |
operating_systems = {}
|
| 597 |
+
for log in logs:
|
| 598 |
+
if 'platform' in log:
|
| 599 |
+
platforms[log['platform']] = platforms.get(log['platform'], 0) + 1
|
| 600 |
+
if 'browser' in log:
|
| 601 |
+
browsers[log['browser']] = browsers.get(log['browser'], 0) + 1
|
| 602 |
+
if 'os' in log:
|
| 603 |
+
operating_systems[log['os']] = operating_systems.get(log['os'], 0) + 1
|
| 604 |
|
| 605 |
+
# Skapa rapport
|
| 606 |
report = {
|
| 607 |
"period": f"Senaste {days} dagarna",
|
| 608 |
+
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 609 |
+
"basic_stats": {
|
| 610 |
+
"total_conversations": total_conversations,
|
| 611 |
+
"unique_sessions": unique_sessions,
|
| 612 |
+
"unique_users": unique_users,
|
| 613 |
+
"messages_per_user": round(total_conversations / unique_users, 2) if unique_users else 0
|
| 614 |
+
},
|
| 615 |
+
"feedback": {
|
| 616 |
+
"positive": positive_feedback,
|
| 617 |
+
"negative": negative_feedback,
|
| 618 |
+
"ratio_percent": round(feedback_ratio, 1)
|
| 619 |
+
},
|
| 620 |
+
"performance": {
|
| 621 |
+
"avg_response_time": round(avg_response_time, 2)
|
| 622 |
+
},
|
| 623 |
+
"platform_distribution": platforms,
|
| 624 |
+
"browser_distribution": browsers,
|
| 625 |
+
"os_distribution": operating_systems
|
| 626 |
}
|
| 627 |
+
|
| 628 |
return report
|
| 629 |
|
|
|
|
| 630 |
def simple_status_report():
|
| 631 |
+
"""Skickar en förenklad statusrapport till Slack."""
|
| 632 |
print("Genererar statusrapport för Slack...")
|
| 633 |
+
|
| 634 |
try:
|
| 635 |
+
# Generera statistik
|
| 636 |
+
stats = generate_monthly_stats(days=7) # Senaste veckan
|
| 637 |
+
|
| 638 |
+
# Skapa innehåll för Slack
|
| 639 |
+
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 640 |
+
subject = f"ChargeNode AI Bot - Status {now_str}"
|
| 641 |
|
| 642 |
+
if 'error' in stats:
|
| 643 |
+
content = f"*Fel vid generering av statistik:* {stats['error']}"
|
| 644 |
+
return send_to_slack(subject, content, "#ff0000")
|
| 645 |
|
| 646 |
+
# Formatera statistik
|
| 647 |
+
basic = stats["basic_stats"]
|
| 648 |
+
feedback = stats["feedback"]
|
| 649 |
+
perf = stats["performance"]
|
| 650 |
|
| 651 |
+
content = f"""
|
| 652 |
+
*ChargeNode AI Bot - Statusrapport {now_str}*
|
| 653 |
+
|
| 654 |
*Basstatistik* (senaste 7 dagarna)
|
| 655 |
- Totalt antal konversationer: {basic['total_conversations']}
|
| 656 |
- Unika sessioner: {basic['unique_sessions']}
|
| 657 |
- Unika användare: {basic['unique_users']}
|
| 658 |
- Genomsnittlig svarstid: {perf['avg_response_time']} sekunder
|
| 659 |
+
|
| 660 |
*Feedback*
|
| 661 |
+
- 👍 Tumme upp: {feedback['positive']}
|
| 662 |
+
- 👎 Tumme ned: {feedback['negative']}
|
| 663 |
+
- Nöjdhet: {feedback['ratio_percent']}%
|
| 664 |
+
"""
|
| 665 |
+
|
| 666 |
+
# Lägg till de senaste konversationerna
|
| 667 |
+
all_logs = read_logs()
|
| 668 |
+
conversations = get_latest_conversations(all_logs, 3)
|
| 669 |
+
|
| 670 |
+
if conversations:
|
| 671 |
+
content += "\n*Senaste konversationer*\n"
|
| 672 |
+
for conv in conversations:
|
| 673 |
+
content += f"""
|
| 674 |
+
> *Tid:* {conv['timestamp']}
|
| 675 |
+
> *Fråga:* {conv['user_message'][:100]}{'...' if len(conv['user_message']) > 100 else ''}
|
| 676 |
+
> *Svar:* {conv['bot_reply'][:100]}{'...' if len(conv['bot_reply']) > 100 else ''}
|
| 677 |
+
"""
|
| 678 |
+
|
| 679 |
+
# Skicka till Slack
|
| 680 |
+
return send_to_slack(subject, content, "#2a9d8f")
|
| 681 |
+
|
| 682 |
except Exception as e:
|
| 683 |
print(f"Fel vid generering av statusrapport: {e}")
|
| 684 |
+
|
| 685 |
+
# Skicka felmeddelande till Slack
|
| 686 |
+
error_subject = f"ChargeNode AI Bot - Fel vid statusrapport"
|
| 687 |
+
error_content = f"*Fel vid generering av statusrapport:* {str(e)}"
|
| 688 |
+
return send_to_slack(error_subject, error_content, "#ff0000")
|
| 689 |
|
| 690 |
+
def send_support_to_slack(områdeskod, uttagsnummer, email, chat_history_list):
|
| 691 |
+
"""Skickar en supportförfrågan till Slack."""
|
| 692 |
try:
|
| 693 |
+
# Formatera chat-historiken
|
| 694 |
+
chat_content = ""
|
| 695 |
+
for msg in chat_history_list:
|
| 696 |
+
if msg['role'] == 'user':
|
| 697 |
+
chat_content += f">*Användare:* {msg['content']}\n\n"
|
| 698 |
+
elif msg['role'] == 'assistant':
|
| 699 |
+
chat_content += f">*Bot:* {msg['content'][:300]}{'...' if len(msg['content']) > 300 else ''}\n\n"
|
| 700 |
+
|
| 701 |
+
# Skapa innehåll
|
| 702 |
+
subject = f"Support förfrågan - {datetime.now().strftime('%Y-%m-%d %H:%M')}"
|
| 703 |
+
|
| 704 |
+
content = f"""
|
| 705 |
+
*Användarinformation*
|
| 706 |
+
- *Områdeskod:* {områdeskod or 'Ej angiven'}
|
| 707 |
+
- *Uttagsnummer:* {uttagsnummer or 'Ej angiven'}
|
| 708 |
+
- *Email:* {email}
|
| 709 |
- *Tidpunkt:* {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
| 710 |
+
|
| 711 |
*Chatthistorik:*
|
| 712 |
+
{chat_content}
|
| 713 |
+
"""
|
| 714 |
+
|
| 715 |
+
# Skicka till Slack
|
| 716 |
+
return send_to_slack(subject, content, "#e76f51")
|
| 717 |
except Exception as e:
|
| 718 |
print(f"Fel vid sändning av support till Slack: {type(e).__name__}: {e}")
|
| 719 |
return False
|
| 720 |
|
| 721 |
# --- Schemaläggning av rapporter ---
|
| 722 |
def run_scheduler():
|
| 723 |
+
"""Kör schemaläggaren i en separat tråd med förenklad statusrapportering."""
|
| 724 |
+
# Använd den förenklade funktionen för rapportering
|
| 725 |
schedule.every().day.at("08:00").do(simple_status_report)
|
| 726 |
schedule.every().day.at("12:00").do(simple_status_report)
|
| 727 |
schedule.every().day.at("17:00").do(simple_status_report)
|
| 728 |
+
|
| 729 |
+
# Veckorapport på måndagar
|
| 730 |
schedule.every().monday.at("09:00").do(lambda: send_to_slack(
|
| 731 |
"Veckostatistik",
|
| 732 |
f"*ChargeNode AI Bot - Veckostatistik*\n\n{json.dumps(generate_monthly_stats(7), indent=2)}",
|
| 733 |
"#3498db"
|
| 734 |
))
|
| 735 |
+
|
| 736 |
while True:
|
| 737 |
schedule.run_pending()
|
| 738 |
+
time.sleep(60) # Kontrollera varje minut
|
| 739 |
|
| 740 |
+
# Starta schemaläggaren i en separat tråd
|
| 741 |
scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
|
| 742 |
scheduler_thread.start()
|
| 743 |
|
| 744 |
# --- Gradio UI ---
|
| 745 |
initial_chat = [{"role": "assistant", "content": "Detta är ChargeNode's AI bot. Hur kan jag hjälpa dig idag?"}]
|
| 746 |
+
|
| 747 |
+
custom_css = """
|
| 748 |
+
body {background-color: #f7f7f7; font-family: Arial, sans-serif; margin: 0; padding: 0;}
|
| 749 |
+
h1 {font-family: Helvetica, sans-serif; color: #2a9d8f; text-align: center; margin-bottom: 0.5em;}
|
| 750 |
+
.gradio-container {max-width: 400px; margin: 0; padding: 10px; position: fixed; bottom: 20px; right: 20px; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1); border-radius: 10px; background-color: #fff;}
|
| 751 |
+
#chatbot_conversation { max-height: 300px; overflow-y: auto; }
|
| 752 |
+
.gr-button {background-color: #2a9d8f; color: #fff; border: none; border-radius: 4px; padding: 8px 16px; margin: 5px;}
|
| 753 |
+
.gr-button:hover {background-color: #264653;}
|
| 754 |
+
.support-btn {background-color: #000000; color: #ffffff; margin-top: 5px; margin-bottom: 10px;}
|
| 755 |
+
.support-btn:hover {background-color: #333333;}
|
| 756 |
+
.flex-row {display: flex; flex-direction: row; gap: 5px;}
|
| 757 |
+
.gr-form {padding: 10px; border: 1px solid #eee; border-radius: 4px; margin-bottom: 10px;}
|
| 758 |
+
.chat-preview {max-height: 150px; overflow-y: auto; border: 1px solid #eee; padding: 8px; margin-top: 10px; font-size: 12px; background-color: #f9f9f9;}
|
| 759 |
+
.success-message {font-size: 16px; font-weight: normal; margin-bottom: 15px;}
|
| 760 |
+
/* Dölj Gradio-footer */
|
| 761 |
+
footer {display: none !important;}
|
| 762 |
+
.footer {display: none !important;}
|
| 763 |
+
.gr-footer {display: none !important;}
|
| 764 |
+
.gradio-footer {display: none !important;}
|
| 765 |
+
.gradio-container .footer {display: none !important;}
|
| 766 |
+
.gradio-container .gr-footer {display: none !important;}
|
| 767 |
+
"""
|
| 768 |
|
| 769 |
with gr.Blocks(css=custom_css, title="ChargeNode Kundtjänst") as app:
|
| 770 |
gr.Markdown("Ställ din fråga om ChargeNodes produkter och tjänster nedan. Om du inte gillar botten, så ring oss gärna på 010 – 205 10 55")
|
| 771 |
|
| 772 |
+
# Chat interface
|
| 773 |
with gr.Group(visible=True) as chat_interface:
|
| 774 |
+
chatbot = gr.Chatbot(value=initial_chat, type="messages", elem_id="chatbot_conversation")
|
| 775 |
+
chatbot.like(vote, None, None)
|
| 776 |
|
| 777 |
with gr.Row():
|
| 778 |
+
msg = gr.Textbox(label="Meddelande", placeholder="Ange din fråga...")
|
| 779 |
|
| 780 |
with gr.Row():
|
| 781 |
with gr.Column(scale=1):
|
| 782 |
+
clear = gr.Button("Rensa")
|
| 783 |
with gr.Column(scale=1):
|
| 784 |
+
support_btn = gr.Button("Behöver du mer hjälp?", elem_classes="support-btn")
|
| 785 |
|
| 786 |
+
# Support form interface (initially hidden)
|
| 787 |
with gr.Group(visible=False) as support_interface:
|
| 788 |
gr.Markdown("### Vänligen fyll i din områdeskod, uttagsnummer och din email adress")
|
| 789 |
+
|
| 790 |
with gr.Group(elem_classes="gr-form"):
|
| 791 |
+
områdeskod = gr.Textbox(label="Områdeskod", placeholder="Områdeskod (valfritt)", info="Numeriskt värde")
|
| 792 |
+
uttagsnummer = gr.Textbox(label="Uttagsnummer", placeholder="Uttagsnummer (valfritt)", info="Numeriskt värde")
|
| 793 |
+
email = gr.Textbox(label="Din email adress", placeholder="din@email.se", info="Email adress krävs")
|
| 794 |
|
| 795 |
gr.Markdown("### Chat som skickas till support:")
|
| 796 |
+
chat_preview = gr.Markdown(elem_classes="chat-preview")
|
| 797 |
|
| 798 |
with gr.Row():
|
| 799 |
+
back_btn = gr.Button("Tillbaka")
|
| 800 |
+
send_support_btn = gr.Button("Skicka")
|
| 801 |
|
| 802 |
+
# Success message (initially hidden)
|
| 803 |
with gr.Group(visible=False) as success_interface:
|
| 804 |
gr.Markdown("Tack för att du kontaktar support@chargenode.eu. Vi återkommer inom kort", elem_classes="success-message")
|
| 805 |
+
back_to_chat_btn = gr.Button("Tillbaka till chatten")
|
| 806 |
|
| 807 |
+
def respond(message, chat_history_list, request: gr.Request):
|
| 808 |
global last_log
|
| 809 |
+
start_time = time.time()
|
| 810 |
|
| 811 |
+
# Lägg till användarens nuvarande meddelande i historiken FÖRE anrop till generate_answer
|
| 812 |
+
chat_history_list.append({"role": "user", "content": message})
|
|
|
|
| 813 |
|
| 814 |
+
# Skicka den uppdaterade chatthistoriken till generate_answer
|
| 815 |
+
response_text = generate_answer(message, chat_history_list)
|
| 816 |
+
elapsed = round(time.time() - start_time, 2)
|
| 817 |
+
|
| 818 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 819 |
+
session_id = str(uuid.uuid4())
|
| 820 |
|
| 821 |
+
# Använd session_id från tidigare logg om det finns
|
| 822 |
+
if last_log and 'session_id' in last_log:
|
| 823 |
+
session_id = last_log.get('session_id')
|
| 824 |
|
| 825 |
+
user_id = request.client.host if request else "okänd"
|
| 826 |
|
| 827 |
ua_str = request.headers.get("user-agent", "")
|
| 828 |
ref = request.headers.get("referer", "")
|
| 829 |
+
ip = request.headers.get("x-forwarded-for", user_id).split(",")[0].strip()
|
| 830 |
ua = parse_ua(ua_str)
|
| 831 |
+
browser = f"{ua.browser.family} {ua.browser.version_string}"
|
| 832 |
+
osys = f"{ua.os.family} {ua.os.version_string}"
|
| 833 |
+
|
| 834 |
+
platform = "webb"
|
| 835 |
+
if "chargenode.eu" in ref:
|
| 836 |
+
platform = "chargenode.eu"
|
| 837 |
+
elif "localhost" in ref or "127.0.0.1" in ref:
|
| 838 |
+
platform = "test"
|
| 839 |
+
elif "app" in ref:
|
| 840 |
+
platform = "app"
|
| 841 |
+
|
| 842 |
+
log_data = {
|
| 843 |
+
"timestamp": timestamp,
|
| 844 |
+
"user_id": user_id,
|
| 845 |
+
"session_id": session_id,
|
| 846 |
+
"user_message": message,
|
| 847 |
+
"bot_reply": response_text,
|
| 848 |
+
"response_time": elapsed,
|
| 849 |
+
"ip": ip,
|
| 850 |
+
"browser": browser,
|
| 851 |
+
"os": osys,
|
| 852 |
+
"platform": platform,
|
| 853 |
+
"chat_history_length": len(chat_history_list)
|
| 854 |
}
|
|
|
|
|
|
|
| 855 |
|
| 856 |
+
safe_append_to_log(log_data)
|
| 857 |
+
last_log = log_data
|
| 858 |
+
|
| 859 |
+
# Skicka varje konversation direkt till Slack
|
| 860 |
try:
|
| 861 |
+
conversation_content = f"""
|
| 862 |
+
*Ny konversation {timestamp}*
|
| 863 |
+
|
| 864 |
+
*Användare:* {message}
|
| 865 |
+
|
| 866 |
+
*Bot:* {response_text[:300]}{'...' if len(response_text) > 300 else ''}
|
| 867 |
+
|
| 868 |
+
*Sessionsinfo:* {session_id[:8]}... | {browser} | {platform} | Chat längd: {len(chat_history_list)} meddelanden
|
| 869 |
+
"""
|
| 870 |
threading.Thread(
|
| 871 |
+
target=lambda: send_to_slack(f"Ny konversation", conversation_content),
|
| 872 |
+
daemon=True
|
| 873 |
).start()
|
| 874 |
except Exception as e:
|
| 875 |
print(f"Kunde inte skicka konversation till Slack: {e}")
|
| 876 |
|
| 877 |
+
# Användarens meddelande är redan tillagt, lägg bara till assistentens svar.
|
| 878 |
+
chat_history_list.append({"role": "assistant", "content": response_text})
|
| 879 |
+
return "", chat_history_list
|
| 880 |
+
|
| 881 |
+
def format_chat_preview(chat_history_list):
|
| 882 |
+
if not chat_history_list:
|
| 883 |
+
return "Ingen chatthistorik att visa."
|
| 884 |
+
|
| 885 |
+
preview = ""
|
| 886 |
+
for msg_item in chat_history_list:
|
| 887 |
+
sender = "Användare" if msg_item["role"] == "user" else "Bot"
|
| 888 |
+
content = msg_item["content"]
|
| 889 |
+
if len(content) > 100: # Truncate long messages
|
| 890 |
+
content = content[:100] + "..."
|
| 891 |
+
preview += f"**{sender}:** {content}\n\n"
|
| 892 |
+
|
| 893 |
+
return preview
|
| 894 |
+
|
| 895 |
+
def show_support_form(chat_history_list):
|
| 896 |
+
preview = format_chat_preview(chat_history_list)
|
| 897 |
return {
|
| 898 |
+
chat_interface: gr.Group(visible=False),
|
| 899 |
+
support_interface: gr.Group(visible=True),
|
| 900 |
+
success_interface: gr.Group(visible=False),
|
| 901 |
+
chat_preview: preview
|
| 902 |
}
|
| 903 |
|
| 904 |
+
def back_to_chat():
|
| 905 |
return {
|
| 906 |
+
chat_interface: gr.Group(visible=True),
|
| 907 |
+
support_interface: gr.Group(visible=False),
|
| 908 |
+
success_interface: gr.Group(visible=False)
|
| 909 |
}
|
| 910 |
|
| 911 |
+
def submit_support_form(omr_kod, uttags_nr, email_addr, chat_history_list):
|
| 912 |
+
"""Hanterar formulärinskickningen med bättre felhantering."""
|
| 913 |
+
print(f"Support-förfrågan: områdeskod={omr_kod}, uttagsnummer={uttags_nr}, email={email_addr}")
|
| 914 |
+
|
| 915 |
validation_errors = []
|
| 916 |
+
|
| 917 |
+
if omr_kod and not omr_kod.isdigit():
|
| 918 |
+
print(f"Validerar områdeskod: '{omr_kod}' (felaktig)")
|
| 919 |
+
validation_errors.append("Områdeskod måste vara numerisk.")
|
| 920 |
+
else:
|
| 921 |
+
print(f"Validerar områdeskod: '{omr_kod}' (ok)")
|
| 922 |
+
|
| 923 |
+
if uttags_nr and not uttags_nr.isdigit():
|
| 924 |
+
print(f"Validerar uttagsnummer: '{uttags_nr}' (felaktig)")
|
| 925 |
+
validation_errors.append("Uttagsnummer måste vara numerisk.")
|
| 926 |
+
else:
|
| 927 |
+
print(f"Validerar uttagsnummer: '{uttags_nr}' (ok)")
|
| 928 |
+
|
| 929 |
+
if not email_addr:
|
| 930 |
+
print("Validerar email: (saknas)")
|
| 931 |
+
validation_errors.append("En giltig e-postadress krävs.")
|
| 932 |
+
elif '@' not in email_addr or '.' not in email_addr.split('@')[-1]:
|
| 933 |
+
print(f"Validerar email: '{email_addr}' (felaktigt format)")
|
| 934 |
+
validation_errors.append("En giltig e-postadress krävs.")
|
| 935 |
+
else:
|
| 936 |
+
print(f"Validerar email: '{email_addr}' (ok)")
|
| 937 |
|
| 938 |
if validation_errors:
|
| 939 |
+
print(f"Valideringsfel: {validation_errors}")
|
| 940 |
error_message_md = "**Fel:**\n" + "\n".join(f"- {err}" for err in validation_errors)
|
| 941 |
return {
|
| 942 |
+
chat_interface: gr.update(visible=False),
|
| 943 |
+
support_interface: gr.update(visible=True),
|
| 944 |
+
success_interface: gr.update(visible=False),
|
| 945 |
+
chat_preview: gr.update(value=error_message_md)
|
| 946 |
}
|
| 947 |
+
|
| 948 |
try:
|
| 949 |
+
print("Försöker skicka supportförfrågan till Slack...")
|
| 950 |
+
|
| 951 |
+
chat_summary = []
|
| 952 |
+
for msg_item in chat_history_list:
|
| 953 |
+
if 'role' in msg_item and 'content' in msg_item:
|
| 954 |
+
chat_summary.append(f"{msg_item['role']}: {msg_item['content'][:30]}...")
|
| 955 |
+
print(f"Chatthistorik att skicka: {chat_summary}")
|
| 956 |
+
|
| 957 |
+
success = send_support_to_slack(omr_kod, uttags_nr, email_addr, chat_history_list)
|
| 958 |
+
|
| 959 |
+
if success:
|
| 960 |
+
print("Support-förfrågan skickad till Slack framgångsrikt")
|
| 961 |
return {
|
| 962 |
+
chat_interface: gr.update(visible=False),
|
| 963 |
+
support_interface: gr.update(visible=False),
|
| 964 |
success_interface: gr.update(visible=True)
|
| 965 |
}
|
| 966 |
else:
|
| 967 |
+
print("Support-förfrågan till Slack misslyckades")
|
| 968 |
+
error_message_md = "**Ett fel uppstod när meddelandet skulle skickas. Vänligen försök igen senare.**"
|
| 969 |
return {
|
| 970 |
+
chat_interface: gr.update(visible=False),
|
| 971 |
+
support_interface: gr.update(visible=True),
|
| 972 |
+
success_interface: gr.update(visible=False),
|
| 973 |
+
chat_preview: gr.update(value=error_message_md)
|
| 974 |
}
|
| 975 |
except Exception as e:
|
| 976 |
+
print(f"Oväntat fel vid hantering av support-formulär: {e}")
|
| 977 |
+
error_message_md = f"**Ett oväntat fel uppstod: {str(e)}**"
|
| 978 |
return {
|
| 979 |
+
chat_interface: gr.update(visible=False),
|
| 980 |
+
support_interface: gr.update(visible=True),
|
| 981 |
+
success_interface: gr.update(visible=False),
|
| 982 |
+
chat_preview: gr.update(value=error_message_md)
|
| 983 |
}
|
| 984 |
|
| 985 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 986 |
+
clear.click(lambda: initial_chat, None, chatbot, queue=False)
|
| 987 |
+
support_btn.click(show_support_form, chatbot, [chat_interface, support_interface, success_interface, chat_preview])
|
| 988 |
+
back_btn.click(back_to_chat, None, [chat_interface, support_interface, success_interface])
|
| 989 |
+
back_to_chat_btn.click(back_to_chat, None, [chat_interface, support_interface, success_interface])
|
| 990 |
+
send_support_btn.click(
|
| 991 |
+
submit_support_form,
|
| 992 |
+
[områdeskod, uttagsnummer, email, chatbot],
|
| 993 |
+
[chat_interface, support_interface, success_interface, chat_preview]
|
| 994 |
)
|
| 995 |
|
| 996 |
+
# Initialisera embeddings vid uppstart
|
| 997 |
print("Förbereder embedding-modell och index...")
|
| 998 |
+
initialize_embeddings()
|
| 999 |
print("Embedding-modell och index redo!")
|
| 1000 |
|
| 1001 |
if __name__ == "__main__":
|