Spaces:
Runtime error
Runtime error
File size: 2,349 Bytes
3c398e4 05a2710 d13e5e0 05a2710 7a7dd79 05a2710 7a7dd79 05a2710 7a7dd79 8b353d1 7a7dd79 05a2710 7a7dd79 c69a33f 05a2710 5ba1b00 05a2710 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | import gradio as gr
import json, re
from sentence_transformers import SentenceTransformer
import faiss
from transformers import pipeline
# --- Carica i dati ---
with open("guida_olfattiva.txt", "r", encoding="utf-8") as f:
guida_text = f.read()
with open("faq_servizio_clienti.txt", "r", encoding="utf-8") as f:
faq_text = f.read()
with open("docs.json", "r", encoding="utf-8") as f:
prodotti = json.load(f)
# --- Prepara documenti e vettori ---
docs = []
sources = []
# separa guida e faq in paragrafi
for par in re.split(r"\n{2,}", guida_text + "\n\n" + faq_text):
if len(par.strip()) > 50:
docs.append(par.strip())
sources.append("guida/faq")
# embedding model (leggero e gratuito)
embedder = SentenceTransformer("all-MiniLM-L6-v2")
doc_embeddings = embedder.encode(docs, convert_to_tensor=False)
index = faiss.IndexFlatL2(doc_embeddings.shape[1])
index.add(doc_embeddings)
# LLM per generare risposte
llm = pipeline("text-generation", model="mistralai/Mistral-7B-Instruct", device_map="auto", max_new_tokens=300)
# --- Funzione principale ---
def chatbot(utente):
# trova i 2 testi più rilevanti
query_emb = embedder.encode([utente])
D, I = index.search(query_emb, 2)
context = "\n\n".join([docs[i] for i in I[0]])
# filtra prodotti per note o parole chiave
suggeriti = []
for p in prodotti:
descr = (p.get("descrizione") or "").lower() + " " + (p.get("olfatto") or "").lower()
if any(k in utente.lower() for k in descr.split()):
suggeriti.append(p)
suggeriti = suggeriti[:3]
# costruisce prompt
prompt = f"""Sei un assistente per una profumeria.
Hai accesso a una guida olfattiva e un catalogo prodotti.
Guida e FAQ rilevanti:
{context}
Domanda: {utente}
Consigli: {', '.join([p['nome'] for p in suggeriti]) if suggeriti else 'nessuno trovato'}
Rispondi in modo amichevole, proponendo solo profumi dal catalogo se pertinenti.
"""
risposta = llm(prompt)[0]["generated_text"]
return risposta.strip()
# --- Interfaccia Gradio ---
gr.Interface(
fn=chatbot,
inputs=gr.Textbox(label="Scrivi la tua domanda"),
outputs="text",
title="💬 Chatbot Profumeria Intelligente",
description="Capisce le note olfattive, consulta la guida e consiglia solo profumi effettivamente presenti nel catalogo."
).launch()
|