Update app.py
Browse files
app.py
CHANGED
|
@@ -3,89 +3,168 @@ from langchain.llms import HuggingFaceHub
|
|
| 3 |
from langchain.chains import ConversationChain
|
| 4 |
from langchain.memory import ConversationBufferMemory
|
| 5 |
import os
|
|
|
|
| 6 |
|
| 7 |
# Configure page
|
| 8 |
-
st.set_page_config(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
# Title
|
| 11 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
# Initialize session
|
| 14 |
if "memory" not in st.session_state:
|
| 15 |
-
st.session_state.memory = ConversationBufferMemory(
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
# Initialize session state for chat history
|
| 18 |
if "messages" not in st.session_state:
|
| 19 |
st.session_state.messages = []
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
# Hugging Face API token
|
| 25 |
-
hf_api_token = os.environ.get("HF_API_TOKEN", "")
|
| 26 |
-
if not hf_api_token:
|
| 27 |
-
st.error("Hugging Face API token not found. Please set it in the Space secrets.")
|
| 28 |
-
st.stop()
|
| 29 |
-
|
| 30 |
-
# Select the appropriate model based on language
|
| 31 |
-
model_name = "bigscience/bloom" if language == "English" else "bigscience/bloom"
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
)
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
# Display chat history
|
| 48 |
for message in st.session_state.messages:
|
| 49 |
-
|
|
|
|
| 50 |
st.markdown(message["content"])
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
if
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
# Process the user input
|
| 59 |
if prompt:
|
|
|
|
|
|
|
|
|
|
| 60 |
# Add user message to chat history
|
| 61 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 62 |
-
|
| 63 |
# Display user message
|
| 64 |
-
with st.chat_message("user"):
|
| 65 |
st.markdown(prompt)
|
| 66 |
-
|
| 67 |
-
# Display assistant response
|
| 68 |
-
with st.chat_message("assistant"):
|
| 69 |
-
with st.spinner("
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
with st.sidebar:
|
| 84 |
-
st.header("About this Chatbot")
|
|
|
|
| 85 |
if language == "English":
|
| 86 |
-
st.
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
else:
|
| 90 |
-
st.
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from langchain.chains import ConversationChain
|
| 4 |
from langchain.memory import ConversationBufferMemory
|
| 5 |
import os
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
|
| 8 |
# Configure page
|
| 9 |
+
st.set_page_config(
|
| 10 |
+
page_title="Tourism Chatbot",
|
| 11 |
+
page_icon="🌍",
|
| 12 |
+
layout="wide"
|
| 13 |
+
)
|
| 14 |
|
| 15 |
+
# Title with better styling
|
| 16 |
+
st.markdown("""
|
| 17 |
+
<h1 style='text-align: center; color: #2E86C1;'>
|
| 18 |
+
Tourism Assistant - مساعد السياحة
|
| 19 |
+
</h1>
|
| 20 |
+
""", unsafe_allow_html=True)
|
| 21 |
|
| 22 |
+
# Initialize session states
|
| 23 |
if "memory" not in st.session_state:
|
| 24 |
+
st.session_state.memory = ConversationBufferMemory(
|
| 25 |
+
return_messages=True,
|
| 26 |
+
memory_key="chat_history"
|
| 27 |
+
)
|
| 28 |
|
|
|
|
| 29 |
if "messages" not in st.session_state:
|
| 30 |
st.session_state.messages = []
|
| 31 |
|
| 32 |
+
if "last_request" not in st.session_state:
|
| 33 |
+
st.session_state.last_request = datetime.now() - timedelta(seconds=10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
# Language selector with better styling
|
| 36 |
+
language = st.selectbox(
|
| 37 |
+
"Choose Language / اختر اللغة",
|
| 38 |
+
["English", "العربية"],
|
| 39 |
+
key="lang_select"
|
| 40 |
)
|
| 41 |
|
| 42 |
+
# Hugging Face API token with better error handling
|
| 43 |
+
try:
|
| 44 |
+
hf_api_token = os.environ["HF_API_TOKEN"]
|
| 45 |
+
except KeyError:
|
| 46 |
+
st.error("""
|
| 47 |
+
Hugging Face API token not found.
|
| 48 |
+
Please set it in the Space secrets as HF_API_TOKEN.
|
| 49 |
+
""")
|
| 50 |
+
st.stop()
|
| 51 |
+
|
| 52 |
+
# Improved model selection with better Arabic support
|
| 53 |
+
model_config = {
|
| 54 |
+
"English": {
|
| 55 |
+
"repo_id": "google/flan-t5-large",
|
| 56 |
+
"params": {"temperature": 0.7, "max_length": 512}
|
| 57 |
+
},
|
| 58 |
+
"العربية": {
|
| 59 |
+
"repo_id": "aubmindlab/aragpt2-base",
|
| 60 |
+
"params": {"temperature": 0.5, "max_length": 1024}
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
# Initialize the language model with error handling
|
| 65 |
+
try:
|
| 66 |
+
llm = HuggingFaceHub(
|
| 67 |
+
repo_id=model_config[language]["repo_id"],
|
| 68 |
+
huggingfacehub_api_token=hf_api_token,
|
| 69 |
+
model_kwargs=model_config[language]["params"]
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
conversation = ConversationChain(
|
| 73 |
+
llm=llm,
|
| 74 |
+
memory=st.session_state.memory,
|
| 75 |
+
verbose=False
|
| 76 |
+
)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
st.error(f"Failed to initialize model: {str(e)}")
|
| 79 |
+
st.stop()
|
| 80 |
|
| 81 |
+
# Display chat history with avatars
|
| 82 |
for message in st.session_state.messages:
|
| 83 |
+
avatar = "🧑" if message["role"] == "user" else "🤖"
|
| 84 |
+
with st.chat_message(message["role"], avatar=avatar):
|
| 85 |
st.markdown(message["content"])
|
| 86 |
|
| 87 |
+
# Rate limiting check
|
| 88 |
+
if (datetime.now() - st.session_state.last_request).seconds < 2:
|
| 89 |
+
st.warning("Please wait a moment before sending another message.")
|
| 90 |
+
st.stop()
|
| 91 |
+
|
| 92 |
+
# User input with language-specific placeholders
|
| 93 |
+
prompt = st.chat_input(
|
| 94 |
+
"Ask about tourist destinations..." if language == "English"
|
| 95 |
+
else "اسأل عن الوجهات السياحية..."
|
| 96 |
+
)
|
| 97 |
|
|
|
|
| 98 |
if prompt:
|
| 99 |
+
# Update last request time
|
| 100 |
+
st.session_state.last_request = datetime.now()
|
| 101 |
+
|
| 102 |
# Add user message to chat history
|
| 103 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 104 |
+
|
| 105 |
# Display user message
|
| 106 |
+
with st.chat_message("user", avatar="🧑"):
|
| 107 |
st.markdown(prompt)
|
| 108 |
+
|
| 109 |
+
# Display assistant response
|
| 110 |
+
with st.chat_message("assistant", avatar="🤖"):
|
| 111 |
+
with st.spinner("Generating response..." if language == "English" else "جارٍ تحضير الرد..."):
|
| 112 |
+
try:
|
| 113 |
+
# Enhanced prompt engineering
|
| 114 |
+
if language == "English":
|
| 115 |
+
full_prompt = f"""You are an expert tourism assistant. Provide detailed, helpful information about:
|
| 116 |
+
- Travel destinations
|
| 117 |
+
- Cultural experiences
|
| 118 |
+
- Local customs
|
| 119 |
+
- Safety advice
|
| 120 |
+
|
| 121 |
+
Question: {prompt}
|
| 122 |
+
Answer:"""
|
| 123 |
+
else:
|
| 124 |
+
full_prompt = f"""أنت مساعد سياحي خبير. قدم معلومات مفيدة ومفصلة حول:
|
| 125 |
+
- الوجهات السياحية
|
| 126 |
+
- التجارب الثقافية
|
| 127 |
+
- العادات المحلية
|
| 128 |
+
- نصائح السلامة
|
| 129 |
+
|
| 130 |
+
السؤال: {prompt}
|
| 131 |
+
الجواب:"""
|
| 132 |
+
|
| 133 |
+
response = conversation.predict(input=full_prompt)
|
| 134 |
+
st.markdown(response)
|
| 135 |
+
|
| 136 |
+
# Add to chat history
|
| 137 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 138 |
+
|
| 139 |
+
except Exception as e:
|
| 140 |
+
st.error(f"Error generating response: {str(e)}")
|
| 141 |
+
st.session_state.messages.append({
|
| 142 |
+
"role": "assistant",
|
| 143 |
+
"content": "Sorry, I encountered an error. Please try again."
|
| 144 |
+
})
|
| 145 |
+
|
| 146 |
+
# Enhanced sidebar with clear sections
|
| 147 |
with st.sidebar:
|
| 148 |
+
st.header("ℹ️ About this Chatbot")
|
| 149 |
+
|
| 150 |
if language == "English":
|
| 151 |
+
st.markdown("""
|
| 152 |
+
### Features:
|
| 153 |
+
- Bilingual English/Arabic support
|
| 154 |
+
- Tourism expert knowledge
|
| 155 |
+
- Conversation memory
|
| 156 |
+
|
| 157 |
+
**Note:** Responses may take 10-20 seconds to generate.
|
| 158 |
+
""")
|
| 159 |
else:
|
| 160 |
+
st.markdown("""
|
| 161 |
+
### الميزات:
|
| 162 |
+
- دعم ثنائي اللغة الإنجليزية/العربية
|
| 163 |
+
- معرفة خبيرة بالسياحة
|
| 164 |
+
- ذاكرة المحادثة
|
| 165 |
+
|
| 166 |
+
**ملاحظة:** قد يستغرق الرد 10-20 ثانية.
|
| 167 |
+
""")
|
| 168 |
+
|
| 169 |
+
st.markdown("---")
|
| 170 |
+
st.markdown("Made with ❤️ using [Streamlit](https://streamlit.io/) and [LangChain](https://langchain.com/)")
|