Spaces:
Runtime error
Runtime error
Delete src/stream_app.py
Browse files- src/stream_app.py +0 -191
src/stream_app.py
DELETED
|
@@ -1,191 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import sqlite3
|
| 4 |
-
import bcrypt
|
| 5 |
-
import os
|
| 6 |
-
from dotenv import load_dotenv
|
| 7 |
-
from langchain.document_loaders import PyPDFLoader, UnstructuredWordDocumentLoader
|
| 8 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 9 |
-
from langchain.embeddings import OpenAIEmbeddings
|
| 10 |
-
from langchain.vectorstores import FAISS
|
| 11 |
-
from langchain.chains import ConversationalRetrievalChain
|
| 12 |
-
from langchain.chat_models import ChatOpenAI
|
| 13 |
-
from langchain.callbacks.base import BaseCallbackHandler
|
| 14 |
-
|
| 15 |
-
# Carregar variables d'entorn
|
| 16 |
-
load_dotenv()
|
| 17 |
-
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 18 |
-
|
| 19 |
-
# --- Configuració inicial ---
|
| 20 |
-
st.set_page_config(page_title="Portal Premium Subscriptors", page_icon="🔐", layout="wide")
|
| 21 |
-
|
| 22 |
-
PRIMARY_COLOR = "#1986aa"
|
| 23 |
-
st.markdown(f"""
|
| 24 |
-
<style>
|
| 25 |
-
.stButton > button {{
|
| 26 |
-
background-color: {PRIMARY_COLOR};
|
| 27 |
-
color: white;
|
| 28 |
-
border-radius: 8px;
|
| 29 |
-
padding: 10px 20px;
|
| 30 |
-
font-size: 16px;
|
| 31 |
-
}}
|
| 32 |
-
.sidebar .sidebar-content {{
|
| 33 |
-
background-color: #f8f9fa;
|
| 34 |
-
}}
|
| 35 |
-
h1, h2, h3 {{
|
| 36 |
-
font-family: 'Arial', sans-serif;
|
| 37 |
-
}}
|
| 38 |
-
</style>
|
| 39 |
-
""", unsafe_allow_html=True)
|
| 40 |
-
|
| 41 |
-
# --- Base de dades ---
|
| 42 |
-
conn = sqlite3.connect("usuaris.db")
|
| 43 |
-
c = conn.cursor()
|
| 44 |
-
c.execute("""
|
| 45 |
-
CREATE TABLE IF NOT EXISTS usuaris (
|
| 46 |
-
email TEXT PRIMARY KEY,
|
| 47 |
-
password TEXT,
|
| 48 |
-
nom TEXT
|
| 49 |
-
)
|
| 50 |
-
""")
|
| 51 |
-
conn.commit()
|
| 52 |
-
|
| 53 |
-
def registrar_usuari(email, password, nom):
|
| 54 |
-
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
|
| 55 |
-
try:
|
| 56 |
-
c.execute("INSERT INTO usuaris VALUES (?, ?, ?)", (email, hashed, nom))
|
| 57 |
-
conn.commit()
|
| 58 |
-
return True
|
| 59 |
-
except sqlite3.IntegrityError:
|
| 60 |
-
return False
|
| 61 |
-
|
| 62 |
-
def validar_login(email, password):
|
| 63 |
-
c.execute("SELECT password FROM usuaris WHERE email=?", (email,))
|
| 64 |
-
result = c.fetchone()
|
| 65 |
-
return result and bcrypt.checkpw(password.encode(), result[0])
|
| 66 |
-
|
| 67 |
-
def reset_password(email, new_password):
|
| 68 |
-
hashed = bcrypt.hashpw(new_password.encode(), bcrypt.gensalt())
|
| 69 |
-
c.execute("UPDATE usuaris SET password=? WHERE email=?", (hashed, email))
|
| 70 |
-
conn.commit()
|
| 71 |
-
|
| 72 |
-
# --- Sessió ---
|
| 73 |
-
if "user" not in st.session_state:
|
| 74 |
-
st.session_state["user"] = None
|
| 75 |
-
if "chat_history" not in st.session_state:
|
| 76 |
-
st.session_state["chat_history"] = []
|
| 77 |
-
|
| 78 |
-
# --- Callback per streaming ---
|
| 79 |
-
class StreamHandler(BaseCallbackHandler):
|
| 80 |
-
def __init__(self, container):
|
| 81 |
-
self.container = container
|
| 82 |
-
self.text = ""
|
| 83 |
-
|
| 84 |
-
def on_llm_new_token(self, token, **kwargs):
|
| 85 |
-
self.text += token
|
| 86 |
-
self.container.markdown(f"**Resposta:** {self.text}")
|
| 87 |
-
|
| 88 |
-
# --- Sidebar ---
|
| 89 |
-
st.sidebar.image("logo.png", use_column_width=True)
|
| 90 |
-
st.sidebar.markdown(f"<h3 style='color:{PRIMARY_COLOR};'>Menú</h3>", unsafe_allow_html=True)
|
| 91 |
-
|
| 92 |
-
menu = ["Inici", "Consulta IA", "FAQs", "Vídeos", "Perfil"]
|
| 93 |
-
if st.session_state["user"]:
|
| 94 |
-
choice = st.sidebar.radio("Selecciona una secció:", menu)
|
| 95 |
-
if st.sidebar.button("Tancar sessió"):
|
| 96 |
-
st.session_state["user"] = None
|
| 97 |
-
st.session_state["chat_history"] = []
|
| 98 |
-
st.experimental_rerun()
|
| 99 |
-
else:
|
| 100 |
-
st.sidebar.info("Inicia sessió per accedir al contingut.")
|
| 101 |
-
choice = "Inici"
|
| 102 |
-
|
| 103 |
-
# --- Interfície principal ---
|
| 104 |
-
st.markdown(f"<h1 style='color:{PRIMARY_COLOR};text-align:center;'>Portal Premium Subscriptors</h1>", unsafe_allow_html=True)
|
| 105 |
-
|
| 106 |
-
if st.session_state["user"] is None:
|
| 107 |
-
# Registre
|
| 108 |
-
with st.expander("Registrar-se"):
|
| 109 |
-
nom_reg = st.text_input("Nom complet")
|
| 110 |
-
email_reg = st.text_input("Correu corporatiu")
|
| 111 |
-
pass_reg = st.text_input("Contrasenya", type="password")
|
| 112 |
-
if st.button("Crear compte"):
|
| 113 |
-
if email_reg.endswith("@sergimartinrealtor.com"):
|
| 114 |
-
if registrar_usuari(email_reg, pass_reg, nom_reg):
|
| 115 |
-
st.success("Compte creat correctament!")
|
| 116 |
-
else:
|
| 117 |
-
st.error("Aquest correu ja està registrat.")
|
| 118 |
-
else:
|
| 119 |
-
st.error("Només correus corporatius permesos.")
|
| 120 |
-
|
| 121 |
-
# Login
|
| 122 |
-
st.subheader("Inicia sessió")
|
| 123 |
-
email = st.text_input("Correu corporatiu")
|
| 124 |
-
password = st.text_input("Contrasenya", type="password")
|
| 125 |
-
if st.button("Entrar"):
|
| 126 |
-
if validar_login(email, password):
|
| 127 |
-
st.session_state["user"] = email
|
| 128 |
-
st.experimental_rerun()
|
| 129 |
-
else:
|
| 130 |
-
st.error("Credencials incorrectes")
|
| 131 |
-
|
| 132 |
-
# Recuperació
|
| 133 |
-
with st.expander("Recuperar contrasenya"):
|
| 134 |
-
email_reset = st.text_input("Correu corporatiu", key="reset_email")
|
| 135 |
-
new_pass = st.text_input("Nova contrasenya", type="password", key="reset_pass")
|
| 136 |
-
if st.button("Canviar contrasenya"):
|
| 137 |
-
c.execute("SELECT email FROM usuaris WHERE email=?", (email_reset,))
|
| 138 |
-
if c.fetchone():
|
| 139 |
-
reset_password(email_reset, new_pass)
|
| 140 |
-
st.success("Contrasenya actualitzada!")
|
| 141 |
-
else:
|
| 142 |
-
st.error("Aquest correu no està registrat.")
|
| 143 |
-
else:
|
| 144 |
-
if choice == "Consulta IA":
|
| 145 |
-
st.markdown(f"<h2 style='color:{PRIMARY_COLOR};'>Consulta Intel·ligent</h2>", unsafe_allow_html=True)
|
| 146 |
-
st.write("Pregunta el que vulguis sobre el coneixement corporatiu.")
|
| 147 |
-
|
| 148 |
-
docs_path = "documents"
|
| 149 |
-
all_docs = []
|
| 150 |
-
if os.path.exists(docs_path):
|
| 151 |
-
for f in os.listdir(docs_path):
|
| 152 |
-
if f.endswith(".pdf"):
|
| 153 |
-
loader = PyPDFLoader(os.path.join(docs_path, f))
|
| 154 |
-
all_docs.extend(loader.load())
|
| 155 |
-
elif f.endswith(".docx"):
|
| 156 |
-
loader = UnstructuredWordDocumentLoader(os.path.join(docs_path, f))
|
| 157 |
-
all_docs.extend(loader.load())
|
| 158 |
-
|
| 159 |
-
if all_docs:
|
| 160 |
-
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
| 161 |
-
chunks = splitter.split_documents(all_docs)
|
| 162 |
-
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
|
| 163 |
-
vectorstore = FAISS.from_documents(chunks, embeddings)
|
| 164 |
-
retriever = vectorstore.as_retriever()
|
| 165 |
-
|
| 166 |
-
pregunta = st.text_input("Escriu la teva pregunta:")
|
| 167 |
-
if st.button("Consultar IA"):
|
| 168 |
-
if pregunta:
|
| 169 |
-
container = st.empty()
|
| 170 |
-
handler = StreamHandler(container)
|
| 171 |
-
llm = ChatOpenAI(openai_api_key=openai_api_key, temperature=0, streaming=True, callbacks=[handler])
|
| 172 |
-
qa_chain = ConversationalRetrievalChain.from_llm(llm, retriever=retriever)
|
| 173 |
-
resposta = qa_chain.run({"question": pregunta, "chat_history": st.session_state["chat_history"]})
|
| 174 |
-
st.session_state["chat_history"].append((pregunta, resposta))
|
| 175 |
-
|
| 176 |
-
# Historial
|
| 177 |
-
if st.session_state["chat_history"]:
|
| 178 |
-
st.subheader("Historial de converses:")
|
| 179 |
-
for i, (q, a) in enumerate(st.session_state["chat_history"], 1):
|
| 180 |
-
st.write(f"{i}. **Q:** {q}")
|
| 181 |
-
st.write(f" **A:** {a}")
|
| 182 |
-
else:
|
| 183 |
-
st.warning("No hi ha documents carregats per entrenar la IA.")
|
| 184 |
-
elif choice == "Inici":
|
| 185 |
-
st.write("Benvingut al portal premium.")
|
| 186 |
-
elif choice == "FAQs":
|
| 187 |
-
st.write("Pròximament: Preguntes freqüents.")
|
| 188 |
-
elif choice == "Vídeos":
|
| 189 |
-
st.write("Pròximament: Transcripcions i resums.")
|
| 190 |
-
elif choice == "Perfil":
|
| 191 |
-
st.write(f"Correu: {st.session_state['user']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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