Spaces:
Build error
Build error
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +146 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,148 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
""
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
import openai
|
| 4 |
+
import requests
|
| 5 |
+
from bs4 import BeautifulSoup
|
| 6 |
+
import faiss
|
| 7 |
+
import numpy as np
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
import os
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
class CompanyChatBot:
|
| 15 |
+
def __init__(self, website_url):
|
| 16 |
+
self.api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
+
self.website_url = website_url
|
| 18 |
+
self.website_text = self._scrape_website()
|
| 19 |
+
self.embeddings_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 20 |
+
self.faiss_index = None
|
| 21 |
+
self.text_chunks = []
|
| 22 |
+
openai.api_key = self.api_key
|
| 23 |
+
self._setup_faiss()
|
| 24 |
+
|
| 25 |
+
def _scrape_website(self):
|
| 26 |
+
try:
|
| 27 |
+
response = requests.get(self.website_url)
|
| 28 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 29 |
+
texts = soup.find_all(['p', 'li', 'h1', 'h2', 'h3'])
|
| 30 |
+
content = "\n".join([text.get_text() for text in texts])
|
| 31 |
+
return content[:12000]
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f"Error scraping website: {e}"
|
| 34 |
+
|
| 35 |
+
def _chunk_text(self, text, chunk_size=500):
|
| 36 |
+
words = text.split()
|
| 37 |
+
chunks = [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
|
| 38 |
+
return chunks
|
| 39 |
+
|
| 40 |
+
def _setup_faiss(self):
|
| 41 |
+
# Chunk the website text
|
| 42 |
+
self.text_chunks = self._chunk_text(self.website_text)
|
| 43 |
+
|
| 44 |
+
# Generate embeddings
|
| 45 |
+
embeddings = self.embeddings_model.encode(self.text_chunks)
|
| 46 |
+
|
| 47 |
+
# Create FAISS index
|
| 48 |
+
dimension = embeddings.shape[1]
|
| 49 |
+
self.faiss_index = faiss.IndexFlatL2(dimension)
|
| 50 |
+
self.faiss_index.add(embeddings.astype('float32'))
|
| 51 |
+
|
| 52 |
+
def _get_relevant_chunks(self, query, k=3):
|
| 53 |
+
query_embedding = self.embeddings_model.encode([query])
|
| 54 |
+
distances, indices = self.faiss_index.search(query_embedding.astype('float32'), k)
|
| 55 |
+
return [self.text_chunks[idx] for idx in indices[0]]
|
| 56 |
+
|
| 57 |
+
def ask_question(self, user_query):
|
| 58 |
+
if not user_query:
|
| 59 |
+
return "Please ask a question."
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
# Get relevant chunks using FAISS
|
| 63 |
+
relevant_chunks = self._get_relevant_chunks(user_query)
|
| 64 |
+
context = "\n".join(relevant_chunks)
|
| 65 |
+
|
| 66 |
+
client = OpenAI(api_key=self.api_key)
|
| 67 |
+
response = client.chat.completions.create(
|
| 68 |
+
model="gpt-3.5-turbo",
|
| 69 |
+
max_tokens=250,
|
| 70 |
+
messages=[
|
| 71 |
+
{
|
| 72 |
+
"role": "system",
|
| 73 |
+
"content": """You are a compassionate and empathetic Optimal performance coach assistant. Your role is to:
|
| 74 |
+
1. Actively listen and validate the user's feelings
|
| 75 |
+
2. Ask thoughtful, open-ended questions to understand their situation deeply
|
| 76 |
+
3. Provide supportive guidance while helping them find their own solutions
|
| 77 |
+
4. Maintain a warm, conversational tone that builds trust
|
| 78 |
+
5. When appropriate, gently challenge negative thought patterns
|
| 79 |
+
6. Help users connect their experiences to potential growth opportunities
|
| 80 |
+
|
| 81 |
+
For emotional concerns:
|
| 82 |
+
- Acknowledge the difficulty without immediately trying to fix it
|
| 83 |
+
- Help the user explore their feelings and experiences
|
| 84 |
+
- Normalize struggles when appropriate
|
| 85 |
+
- Guide them toward self-reflection and personal insights
|
| 86 |
+
|
| 87 |
+
For performance-related questions:
|
| 88 |
+
- Focus on process over outcomes
|
| 89 |
+
- Help identify small, actionable steps
|
| 90 |
+
- Encourage a growth mindset
|
| 91 |
+
- Connect to relevant company resources when applicable
|
| 92 |
+
|
| 93 |
+
Remember:
|
| 94 |
+
- If user asks direct question not related to company content, respond with I cannot answer that or something like that"
|
| 95 |
+
- Privacy is important - reassure users their conversations are confidential
|
| 96 |
+
- Be patient and allow the conversation to unfold naturally
|
| 97 |
+
- Use reflective language ("It sounds like...", "I hear you saying...")
|
| 98 |
+
- Balance empathy with gentle challenges to unhelpful thinking patterns"""
|
| 99 |
+
},
|
| 100 |
+
{"role": "system", "content": f"Company context (use when relevant):\n{context}"},
|
| 101 |
+
{"role": "user", "content": user_query}
|
| 102 |
+
],
|
| 103 |
+
temperature=0.7
|
| 104 |
+
)
|
| 105 |
+
return response.choices[0].message.content.strip()
|
| 106 |
+
except Exception as e:
|
| 107 |
+
return f"Error generating answer: {e}"
|
| 108 |
+
|
| 109 |
+
def run(self):
|
| 110 |
+
st.set_page_config(page_title="OP AI", layout="centered")
|
| 111 |
+
st.title("🤖 DEMO OP AI(Currently build on your website. After giving your all documents I will train it based on these ) ")
|
| 112 |
+
|
| 113 |
+
# Initialize chat history
|
| 114 |
+
if "messages" not in st.session_state:
|
| 115 |
+
st.session_state.messages = []
|
| 116 |
+
|
| 117 |
+
# Display chat messages from history
|
| 118 |
+
for message in st.session_state.messages:
|
| 119 |
+
with st.chat_message(message["role"]):
|
| 120 |
+
st.markdown(message["content"])
|
| 121 |
+
|
| 122 |
+
# Text input
|
| 123 |
+
user_query = st.chat_input("How can I support you today?")
|
| 124 |
+
|
| 125 |
+
if user_query:
|
| 126 |
+
# Add user message to chat history
|
| 127 |
+
st.session_state.messages.append({"role": "user", "content": user_query})
|
| 128 |
+
|
| 129 |
+
# Display user message
|
| 130 |
+
with st.chat_message("user"):
|
| 131 |
+
st.markdown(user_query)
|
| 132 |
+
|
| 133 |
+
# Get assistant response
|
| 134 |
+
with st.spinner("Thinking..."):
|
| 135 |
+
assistant_response = self.ask_question(user_query)
|
| 136 |
+
|
| 137 |
+
# Add assistant response to chat history
|
| 138 |
+
st.session_state.messages.append({"role": "assistant", "content": assistant_response})
|
| 139 |
+
|
| 140 |
+
# Display assistant response
|
| 141 |
+
with st.chat_message("assistant"):
|
| 142 |
+
st.markdown(assistant_response)
|
| 143 |
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
chatbot = CompanyChatBot(
|
| 146 |
+
website_url="https://optimalperformancesystem.com/"
|
| 147 |
+
)
|
| 148 |
+
chatbot.run()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|