Update app.py
Browse files
app.py
CHANGED
@@ -4,10 +4,14 @@ 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 |
)
|
@@ -32,139 +36,162 @@ if "messages" not in st.session_state:
|
|
32 |
if "last_request" not in st.session_state:
|
33 |
st.session_state.last_request = datetime.now() - timedelta(seconds=10)
|
34 |
|
35 |
-
# Language selector
|
36 |
language = st.selectbox(
|
37 |
-
"Choose Language / اختر اللغة",
|
38 |
["English", "العربية"],
|
39 |
key="lang_select"
|
40 |
)
|
41 |
|
42 |
-
# Hugging Face API token
|
43 |
-
|
44 |
-
|
45 |
-
except KeyError:
|
46 |
st.error("""
|
47 |
-
|
48 |
-
|
|
|
49 |
""")
|
50 |
st.stop()
|
51 |
|
52 |
-
#
|
53 |
model_config = {
|
54 |
"English": {
|
55 |
-
"repo_id": "google/flan-t5-
|
56 |
-
"params": {
|
|
|
|
|
|
|
|
|
|
|
57 |
},
|
58 |
"العربية": {
|
59 |
-
"repo_id": "aubmindlab/aragpt2-
|
60 |
-
"params": {
|
|
|
|
|
|
|
|
|
|
|
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=
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
st.stop()
|
80 |
|
81 |
-
# Display chat history with
|
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 |
-
|
|
|
|
|
|
|
86 |
|
87 |
-
#
|
88 |
-
if (datetime.now() - st.session_state.last_request).seconds <
|
89 |
-
st.warning("Please wait a moment before sending another message."
|
|
|
90 |
st.stop()
|
91 |
|
92 |
-
# User input with
|
93 |
-
|
94 |
-
"Ask about
|
95 |
-
|
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 |
-
|
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 =
|
116 |
-
-
|
117 |
-
- Cultural
|
118 |
-
-
|
119 |
-
-
|
120 |
-
|
|
|
121 |
Question: {prompt}
|
122 |
-
Answer:"""
|
123 |
else:
|
124 |
-
full_prompt =
|
125 |
-
- الوجهات السياحية
|
126 |
-
-
|
127 |
-
-
|
128 |
-
-
|
129 |
-
|
|
|
130 |
السؤال: {prompt}
|
131 |
-
|
132 |
-
|
133 |
response = conversation.predict(input=full_prompt)
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
|
|
|
|
|
|
|
|
139 |
except Exception as e:
|
140 |
-
|
|
|
|
|
|
|
|
|
141 |
st.session_state.messages.append({
|
142 |
-
"role": "assistant",
|
143 |
-
"content":
|
144 |
})
|
145 |
|
146 |
-
#
|
147 |
with st.sidebar:
|
148 |
-
st.header("ℹ️ About
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
"""
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
st.markdown("---")
|
170 |
-
st.markdown("Made with ❤️ using [Streamlit](https://streamlit.io/) and [LangChain](https://langchain.com/)")
|
|
|
4 |
from langchain.memory import ConversationBufferMemory
|
5 |
import os
|
6 |
from datetime import datetime, timedelta
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
|
9 |
+
# Load environment variables - MUST be at the top
|
10 |
+
load_dotenv('.env') # Explicitly load from .env file
|
11 |
|
12 |
# Configure page
|
13 |
st.set_page_config(
|
14 |
+
page_title="Tourism Chatbot",
|
15 |
page_icon="🌍",
|
16 |
layout="wide"
|
17 |
)
|
|
|
36 |
if "last_request" not in st.session_state:
|
37 |
st.session_state.last_request = datetime.now() - timedelta(seconds=10)
|
38 |
|
39 |
+
# Language selector
|
40 |
language = st.selectbox(
|
41 |
+
"Choose Language / اختر اللغة",
|
42 |
["English", "العربية"],
|
43 |
key="lang_select"
|
44 |
)
|
45 |
|
46 |
+
# Hugging Face API token configuration - PRODUCTION READY
|
47 |
+
HF_TOKEN = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
48 |
+
if not HF_TOKEN:
|
|
|
49 |
st.error("""
|
50 |
+
API token not configured properly. Please:
|
51 |
+
1. Create a .env file with HUGGINGFACEHUB_API_TOKEN=your_token_here
|
52 |
+
2. On Hugging Face Spaces, add it as a secret named HUGGINGFACEHUB_API_TOKEN
|
53 |
""")
|
54 |
st.stop()
|
55 |
|
56 |
+
# Enhanced model configuration
|
57 |
model_config = {
|
58 |
"English": {
|
59 |
+
"repo_id": "google/flan-t5-xxl",
|
60 |
+
"params": {
|
61 |
+
"temperature": 0.7,
|
62 |
+
"max_length": 512,
|
63 |
+
"max_new_tokens": 300,
|
64 |
+
"repetition_penalty": 1.2
|
65 |
+
}
|
66 |
},
|
67 |
"العربية": {
|
68 |
+
"repo_id": "aubmindlab/aragpt2-mega",
|
69 |
+
"params": {
|
70 |
+
"temperature": 0.6,
|
71 |
+
"max_length": 1024,
|
72 |
+
"max_new_tokens": 400,
|
73 |
+
"repetition_penalty": 1.3
|
74 |
+
}
|
75 |
}
|
76 |
}
|
77 |
|
78 |
+
# Initialize the language model with enhanced error handling
|
79 |
try:
|
80 |
llm = HuggingFaceHub(
|
81 |
repo_id=model_config[language]["repo_id"],
|
82 |
+
huggingfacehub_api_token=HF_TOKEN, # Correct parameter name
|
83 |
model_kwargs=model_config[language]["params"]
|
84 |
)
|
85 |
+
|
86 |
conversation = ConversationChain(
|
87 |
llm=llm,
|
88 |
memory=st.session_state.memory,
|
89 |
verbose=False
|
90 |
)
|
91 |
except Exception as e:
|
92 |
+
error_msg = str(e)
|
93 |
+
if "API token" in error_msg:
|
94 |
+
st.error("Invalid API token. Please check your Hugging Face token.")
|
95 |
+
elif "repo_id" in error_msg:
|
96 |
+
st.error("Model loading failed. The specified model may not be available.")
|
97 |
+
else:
|
98 |
+
st.error(f"Initialization error: {error_msg}")
|
99 |
st.stop()
|
100 |
|
101 |
+
# Display chat history with improved formatting
|
102 |
for message in st.session_state.messages:
|
103 |
+
avatar = "🧑" if message["role"] == "user" else "🌍"
|
104 |
with st.chat_message(message["role"], avatar=avatar):
|
105 |
+
if language == "العربية":
|
106 |
+
st.markdown(f"<div style='text-align: right;'>{message['content']}</div>", unsafe_allow_html=True)
|
107 |
+
else:
|
108 |
+
st.markdown(message["content"])
|
109 |
|
110 |
+
# Enhanced rate limiting
|
111 |
+
if (datetime.now() - st.session_state.last_request).seconds < 3:
|
112 |
+
st.warning("Please wait a moment before sending another message." if language == "English"
|
113 |
+
else "الرجاء الانتظار قليلاً قبل إرسال رسالة أخرى")
|
114 |
st.stop()
|
115 |
|
116 |
+
# User input with better placeholder handling
|
117 |
+
prompt_placeholder = {
|
118 |
+
"English": "Ask about destinations, culture, or safety tips...",
|
119 |
+
"العربية": "اسأل عن الوجهات، الثقافة، أو نصائح السلامة..."
|
120 |
+
}
|
121 |
+
prompt = st.chat_input(prompt_placeholder[language])
|
122 |
|
123 |
if prompt:
|
|
|
124 |
st.session_state.last_request = datetime.now()
|
|
|
|
|
125 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
126 |
+
|
|
|
127 |
with st.chat_message("user", avatar="🧑"):
|
128 |
st.markdown(prompt)
|
129 |
+
|
130 |
+
with st.chat_message("assistant", avatar="🌍"):
|
|
|
131 |
with st.spinner("Generating response..." if language == "English" else "جارٍ تحضير الرد..."):
|
132 |
try:
|
133 |
# Enhanced prompt engineering
|
134 |
if language == "English":
|
135 |
+
full_prompt = """You are an expert tourism assistant specializing in:
|
136 |
+
- Detailed travel destination information
|
137 |
+
- Cultural norms and etiquette
|
138 |
+
- Safety recommendations
|
139 |
+
- Local transportation options
|
140 |
+
- Authentic dining experiences
|
141 |
+
|
142 |
Question: {prompt}
|
143 |
+
Answer in clear, detailed points:""".format(prompt=prompt)
|
144 |
else:
|
145 |
+
full_prompt = """أنت مساعد سياحي خبير متخصص في:
|
146 |
+
- معلومات مفصلة عن الوجهات السياحية
|
147 |
+
- الأعراف الثقافية وآداب السلوك
|
148 |
+
- توصيات السلامة
|
149 |
+
- خيارات النقل المحلي
|
150 |
+
- تجارب تناول الطعام الأصيلة
|
151 |
+
|
152 |
السؤال: {prompt}
|
153 |
+
الجواب بنقاط واضحة ومفصلة:""".format(prompt=prompt)
|
154 |
+
|
155 |
response = conversation.predict(input=full_prompt)
|
156 |
+
|
157 |
+
# Post-process response
|
158 |
+
cleaned_response = response.strip()
|
159 |
+
if language == "العربية":
|
160 |
+
cleaned_response = f"<div style='text-align: right;'>{cleaned_response}</div>"
|
161 |
+
|
162 |
+
st.markdown(cleaned_response, unsafe_allow_html=True)
|
163 |
+
st.session_state.messages.append({"role": "assistant", "content": cleaned_response})
|
164 |
+
|
165 |
except Exception as e:
|
166 |
+
error_response = {
|
167 |
+
"English": "Sorry, I encountered an error. Please try again later.",
|
168 |
+
"العربية": "عذرًا، حدث خطأ. يرجى المحاولة مرة أخرى لاحقًا."
|
169 |
+
}
|
170 |
+
st.error(error_response[language])
|
171 |
st.session_state.messages.append({
|
172 |
+
"role": "assistant",
|
173 |
+
"content": error_response[language]
|
174 |
})
|
175 |
|
176 |
+
# Sidebar with deployment-ready information
|
177 |
with st.sidebar:
|
178 |
+
st.header("ℹ️ " + ("About" if language == "English" else "حول"))
|
179 |
+
|
180 |
+
about_text = {
|
181 |
+
"English": """
|
182 |
+
**Tourism Expert Chatbot**
|
183 |
+
• Provides detailed travel information
|
184 |
+
• Offers cultural insights
|
185 |
+
• Available in English/Arabic
|
186 |
+
• Remembers conversation history
|
187 |
+
""",
|
188 |
+
"العربية": """
|
189 |
+
**مساعد سياحي خبير**
|
190 |
+
• يقدم معلوم��ت سفر مفصلة
|
191 |
+
• يوفر رؤى ثقافية
|
192 |
+
• متاح باللغتين الإنجليزية والعربية
|
193 |
+
• يحفظ تاريخ المحادثة
|
194 |
+
"""
|
195 |
+
}
|
196 |
+
|
197 |
+
st.markdown(about_text[language])
|
|
|
|
|
|