Spaces:
Runtime error
Runtime error
Download app.py from TheWizardNic/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 2.35 kB
-
https://huggingface.co/spaces/TheWizardNic/chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/TheWizardNic/chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/TheWizardNic/chatbot/resolve/main/app.py
2.35 kB
| 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() | |