Spaces:
Sleeping
Sleeping
Commit
·
47793bc
1
Parent(s):
dd6995c
RacoGPT skeleton app
Browse files- app.py +98 -0
- login.py +44 -0
- requirements.txt +5 -0
app.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
from streamlit import session_state as ss
|
5 |
+
import os
|
6 |
+
import login # Importa il file login.py che hai creato
|
7 |
+
|
8 |
+
# Inizializza lo stato di login se non esiste
|
9 |
+
if "is_logged_in" not in st.session_state:
|
10 |
+
st.session_state["is_logged_in"] = False
|
11 |
+
|
12 |
+
# Mostra la pagina di login solo se l'utente non è loggato
|
13 |
+
if not st.session_state["is_logged_in"]:
|
14 |
+
login.login_page() # Mostra la pagina di login e blocca il caricamento della chat
|
15 |
+
st.stop()
|
16 |
+
|
17 |
+
# Recupera le secrets da Hugging Face
|
18 |
+
model_repo = os.getenv("MODEL_REPO") # Repository del modello di base
|
19 |
+
hf_token = os.getenv("HF_TOKEN") # Token Hugging Face
|
20 |
+
|
21 |
+
# Carica il modello di base con caching
|
22 |
+
@st.cache_resource
|
23 |
+
def load_model():
|
24 |
+
tokenizer = AutoTokenizer.from_pretrained(model_repo, use_auth_token=hf_token)
|
25 |
+
model = AutoModelForCausalLM.from_pretrained(model_repo, use_auth_token=hf_token)
|
26 |
+
model.config.use_cache = True
|
27 |
+
return tokenizer, model
|
28 |
+
|
29 |
+
# Funzione per generare una risposta in tempo reale
|
30 |
+
def generate_llama_response_stream(user_input, tokenizer, model, max_length=512):
|
31 |
+
eos_token = tokenizer.eos_token if tokenizer.eos_token else ""
|
32 |
+
input_ids = tokenizer.encode(user_input + eos_token, return_tensors="pt")
|
33 |
+
response_text = ""
|
34 |
+
|
35 |
+
response_placeholder = st.empty() # Placeholder per mostrare la risposta progressiva
|
36 |
+
|
37 |
+
# Genera un token alla volta e aggiorna il placeholder
|
38 |
+
for i in range(max_length):
|
39 |
+
output = model.generate(input_ids, max_new_tokens=1, pad_token_id=tokenizer.eos_token_id, use_cache=True)
|
40 |
+
new_token_id = output[:, -1].item()
|
41 |
+
new_token = tokenizer.decode([new_token_id], skip_special_tokens=True)
|
42 |
+
|
43 |
+
response_text += new_token
|
44 |
+
response_placeholder.markdown(f"**RacoGPT:** {response_text}") # Aggiorna il testo progressivo
|
45 |
+
|
46 |
+
# Aggiungi il nuovo token alla sequenza di input
|
47 |
+
input_ids = torch.cat([input_ids, output[:, -1:]], dim=-1)
|
48 |
+
|
49 |
+
# Interrompe se il token generato è <|endoftext|> o eos_token_id
|
50 |
+
if new_token_id == tokenizer.eos_token_id:
|
51 |
+
break
|
52 |
+
|
53 |
+
return response_text
|
54 |
+
|
55 |
+
# Inizializza lo stato della sessione
|
56 |
+
if 'is_chat_input_disabled' not in ss:
|
57 |
+
ss.is_chat_input_disabled = False
|
58 |
+
|
59 |
+
if 'msg' not in ss:
|
60 |
+
ss.msg = []
|
61 |
+
|
62 |
+
if 'chat_history' not in ss:
|
63 |
+
ss.chat_history = None
|
64 |
+
|
65 |
+
# Carica il modello e tokenizer
|
66 |
+
tokenizer, model = load_model()
|
67 |
+
|
68 |
+
# Mostra la cronologia dei messaggi con le label personalizzate
|
69 |
+
for message in ss.msg:
|
70 |
+
if message["role"] == "user":
|
71 |
+
with st.chat_message("user"):
|
72 |
+
st.markdown(f"**Tu:** {message['content']}")
|
73 |
+
elif message["role"] == "RacoGPT":
|
74 |
+
with st.chat_message("RacoGPT"):
|
75 |
+
st.markdown(f"**RacoGPT:** {message['content']}")
|
76 |
+
|
77 |
+
# Gestione dell'input e disabilitazione
|
78 |
+
if (prompt := st.chat_input("Scrivi il tuo messaggio...", disabled=ss.is_chat_input_disabled) or "").strip():
|
79 |
+
|
80 |
+
# Salva il messaggio dell'utente e disabilita l'input
|
81 |
+
if not ss.is_chat_input_disabled:
|
82 |
+
ss.msg.append({"role": "user", "content": prompt})
|
83 |
+
with st.chat_message("user"):
|
84 |
+
ss.is_chat_input_disabled = True
|
85 |
+
st.markdown(f"**Tu:** {prompt}")
|
86 |
+
|
87 |
+
# Genera la risposta del bot con digitazione in tempo reale
|
88 |
+
with st.spinner("RacoGPT sta generando una risposta..."):
|
89 |
+
response = generate_llama_response_stream(prompt, tokenizer, model)
|
90 |
+
|
91 |
+
# Mostra il messaggio finale del bot dopo che la risposta è completata
|
92 |
+
ss.msg.append({"role": "RacoGPT", "content": response})
|
93 |
+
with st.chat_message("RacoGPT"):
|
94 |
+
st.markdown(f"**RacoGPT:** {response}")
|
95 |
+
ss.is_chat_input_disabled = False
|
96 |
+
|
97 |
+
# Rerun per aggiornare l'interfaccia
|
98 |
+
st.rerun()
|
login.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import psycopg2
|
3 |
+
|
4 |
+
# Recupera le credenziali dal file secrets di Hugging Face Spaces
|
5 |
+
user = st.secrets["SUPABASE_USER"]
|
6 |
+
password = st.secrets["SUPABASE_PASSWORD"]
|
7 |
+
host = st.secrets["SUPABASE_HOST"]
|
8 |
+
port = st.secrets["SUPABASE_PORT"]
|
9 |
+
dbname = st.secrets["SUPABASE_DBNAME"]
|
10 |
+
|
11 |
+
# Funzione per connettersi al database
|
12 |
+
def get_connection():
|
13 |
+
return psycopg2.connect(
|
14 |
+
user=user,
|
15 |
+
password=password,
|
16 |
+
host=host,
|
17 |
+
port=port,
|
18 |
+
dbname=dbname
|
19 |
+
)
|
20 |
+
|
21 |
+
# Funzione per verificare l'email e la password
|
22 |
+
def verify_user(email, password):
|
23 |
+
conn = get_connection()
|
24 |
+
cur = conn.cursor()
|
25 |
+
query = "SELECT * FROM users WHERE email = %s AND password = %s"
|
26 |
+
cur.execute(query, (email, password))
|
27 |
+
user = cur.fetchone()
|
28 |
+
cur.close()
|
29 |
+
conn.close()
|
30 |
+
return user
|
31 |
+
|
32 |
+
# Funzione di login
|
33 |
+
def login_page():
|
34 |
+
st.markdown("<h1 style='text-align: center;'>Accedi a RacoGPT</h1>", unsafe_allow_html=True)
|
35 |
+
email = st.text_input("Email", placeholder="Inserisci la tua email", key="login_email_unique")
|
36 |
+
password = st.text_input("Password", type="password", placeholder="Inserisci la tua password", key="login_password_unique")
|
37 |
+
|
38 |
+
if st.button("Accedi", key="login_button_unique"):
|
39 |
+
user = verify_user(email, password)
|
40 |
+
if user:
|
41 |
+
st.session_state["is_logged_in"] = True
|
42 |
+
st.rerun() # Reindirizza alla chat
|
43 |
+
else:
|
44 |
+
st.error("Email o password non corretti.")
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
transformers
|
3 |
+
peft
|
4 |
+
torch
|
5 |
+
psycopg2-binary
|