Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,116 +1,77 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import pickle
|
| 5 |
-
import threading
|
| 6 |
import time
|
| 7 |
-
import
|
| 8 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
-
from langchain_community.vectorstores import FAISS
|
| 10 |
from langchain_huggingface import HuggingFaceEmbeddings
|
|
|
|
| 11 |
from langchain_community.document_loaders import TextLoader
|
| 12 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
cache_path = "cached_documents.pkl" # Cache per evitare ricalcoli
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
with open(cache_path, "rb") as f:
|
| 27 |
-
vectorstore = pickle.load(f)
|
| 28 |
-
else:
|
| 29 |
-
print("📄 Elaborazione del documento in corso...")
|
| 30 |
-
loader = TextLoader(file_path, encoding="utf-8")
|
| 31 |
documents = loader.load()
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 38 |
-
vectorstore = FAISS.from_documents(texts, embeddings)
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
pickle.dump(vectorstore, f)
|
| 43 |
-
|
| 44 |
-
print(f"✅ {len(texts)} frammenti di testo elaborati e salvati!")
|
| 45 |
-
|
| 46 |
-
### 📌 STEP 2: Funzioni di ricerca ###
|
| 47 |
|
|
|
|
| 48 |
def search_docs(query):
|
| 49 |
-
|
|
|
|
| 50 |
results = vectorstore.similarity_search(query, k=3)
|
| 51 |
-
|
| 52 |
-
return "⚠️ Nessuna informazione trovata nei documenti."
|
| 53 |
-
return results
|
| 54 |
|
|
|
|
| 55 |
def search_web(query):
|
| 56 |
-
""
|
| 57 |
-
api_key = "TUA_CHIAVE_API" # Inserisci la tua API key
|
| 58 |
url = f"https://serpapi.com/search?q={query}&api_key={api_key}"
|
| 59 |
-
|
| 60 |
try:
|
| 61 |
response = requests.get(url).json()
|
| 62 |
if "organic_results" in response:
|
| 63 |
return response["organic_results"][:3]
|
| 64 |
-
return ["⚠️
|
| 65 |
except Exception as e:
|
| 66 |
return [f"❌ Errore nella ricerca web: {e}"]
|
| 67 |
|
| 68 |
-
#
|
| 69 |
-
|
| 70 |
-
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # Usa "TinyLlama/TinyLlama-1.1B-Chat-v1.0" se necessario
|
| 71 |
-
|
| 72 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 73 |
-
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
|
| 74 |
-
|
| 75 |
-
### 📌 STEP 4: Funzione principale del chatbot ###
|
| 76 |
-
|
| 77 |
def chatbot_response(query):
|
| 78 |
-
""" Cerca la risposta nei documenti, sul web e usa il modello per generare testo. """
|
| 79 |
-
|
| 80 |
-
# ✅ Cerca nei documenti con FAISS
|
| 81 |
docs = search_docs(query)
|
| 82 |
-
doc_response = docs[0].page_content if isinstance(docs, list) and docs else "⚠️ Nessuna informazione trovata nei documenti."
|
| 83 |
-
|
| 84 |
-
# ✅ Cerca sul web con Perplexity o SerpAPI
|
| 85 |
web_results = search_web(query)
|
| 86 |
-
web_response = web_results[0]["snippet"] if isinstance(web_results, list) and web_results else "⚠️ Nessuna informazione trovata sul web."
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
input_text = f"Domanda: {query}\nRisposta:"
|
| 91 |
-
inputs = tokenizer(input_text, return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 92 |
-
output = model.generate(**inputs, max_new_tokens=100)
|
| 93 |
-
model_response = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 94 |
-
except Exception as e:
|
| 95 |
-
model_response = f"❌ Errore nel modello: {e}"
|
| 96 |
-
|
| 97 |
-
return f"📚 **Dai documenti:** {doc_response}\n🌐 **Dal web:** {web_response}\n🤖 **LLM:** {model_response}"
|
| 98 |
|
| 99 |
-
|
| 100 |
|
|
|
|
| 101 |
def keep_alive():
|
| 102 |
-
""" Ping Hugging Face Spaces per evitare timeout. """
|
| 103 |
while True:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
except:
|
| 107 |
-
pass
|
| 108 |
-
time.sleep(600) # Pinga ogni 10 minuti
|
| 109 |
-
|
| 110 |
-
threading.Thread(target=keep_alive, daemon=True).start()
|
| 111 |
-
|
| 112 |
-
### 📌 STEP 6: Avvia l'interfaccia del chatbot ###
|
| 113 |
|
| 114 |
-
|
|
|
|
| 115 |
|
| 116 |
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
|
|
|
|
|
|
| 3 |
import time
|
| 4 |
+
from huggingface_hub import login
|
|
|
|
|
|
|
| 5 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 6 |
+
from langchain_community.vectorstores import FAISS
|
| 7 |
from langchain_community.document_loaders import TextLoader
|
| 8 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
+
import torch
|
| 11 |
|
| 12 |
+
# 🔐 Autenticazione Hugging Face per modelli gated
|
| 13 |
+
HF_TOKEN = "TUA_HUGGINGFACE_TOKEN" # 🔴 INSERISCI IL TUO TOKEN QUI
|
| 14 |
+
login(HF_TOKEN)
|
|
|
|
| 15 |
|
| 16 |
+
# 📌 Sostituisci "google/gemma-2b" con un modello pubblico se necessario
|
| 17 |
+
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # 🔄 Modello alternativo pubblico
|
| 18 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 19 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
+
model_name, torch_dtype=torch.float16, device_map="auto"
|
| 21 |
+
)
|
| 22 |
|
| 23 |
+
# 📄 Caricamento del dizionario e gestione UTF-8
|
| 24 |
+
try:
|
| 25 |
+
loader = TextLoader("dizionario.txt", encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
documents = loader.load()
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"❌ Errore nel caricamento del dizionario: {e}")
|
| 29 |
+
documents = []
|
| 30 |
|
| 31 |
+
# 🔍 Creazione degli embeddings
|
| 32 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 33 |
+
texts = text_splitter.split_documents(documents)
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 36 |
+
vectorstore = FAISS.from_documents(texts, embeddings) if texts else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
# 🔎 Ricerca nei documenti
|
| 39 |
def search_docs(query):
|
| 40 |
+
if not vectorstore:
|
| 41 |
+
return "⚠️ Il database di documenti non è disponibile."
|
| 42 |
results = vectorstore.similarity_search(query, k=3)
|
| 43 |
+
return results if results else ["⚠️ Nessuna informazione trovata nei documenti."]
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# 🌐 Ricerca web con gestione errori
|
| 46 |
def search_web(query):
|
| 47 |
+
api_key = "TUA_CHIAVE_API" # 🔴 INSERISCI LA TUA API KEY
|
|
|
|
| 48 |
url = f"https://serpapi.com/search?q={query}&api_key={api_key}"
|
| 49 |
+
|
| 50 |
try:
|
| 51 |
response = requests.get(url).json()
|
| 52 |
if "organic_results" in response:
|
| 53 |
return response["organic_results"][:3]
|
| 54 |
+
return ["⚠️ Nessun risultato trovato."]
|
| 55 |
except Exception as e:
|
| 56 |
return [f"❌ Errore nella ricerca web: {e}"]
|
| 57 |
|
| 58 |
+
# 🤖 Generazione risposta del chatbot
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
def chatbot_response(query):
|
|
|
|
|
|
|
|
|
|
| 60 |
docs = search_docs(query)
|
|
|
|
|
|
|
|
|
|
| 61 |
web_results = search_web(query)
|
|
|
|
| 62 |
|
| 63 |
+
doc_response = docs[0] if docs else "Nessuna informazione trovata nei documenti."
|
| 64 |
+
web_response = web_results[0]["snippet"] if web_results and isinstance(web_results[0], dict) else "Nessuna informazione trovata sul web."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
return f"📚 **Dai documenti:** {doc_response}\n🌐 **Dal web:** {web_response}"
|
| 67 |
|
| 68 |
+
# 🔄 Keep-Alive per evitare timeout
|
| 69 |
def keep_alive():
|
|
|
|
| 70 |
while True:
|
| 71 |
+
print("🔄 Keep-alive attivo...")
|
| 72 |
+
time.sleep(600) # Mantiene il processo attivo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
# 🚀 Avvio interfaccia Gradio
|
| 75 |
+
gr.Interface(fn=chatbot_response, inputs="text", outputs="text", title="Chatbot Personalizzato").launch()
|
| 76 |
|
| 77 |
|