moosalah commited on
Commit
768bbb4
·
verified ·
1 Parent(s): 13a0fdd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -61
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(page_title="Tourism Chatbot", page_icon="🌍")
 
 
 
 
9
 
10
- # Title
11
- st.title("Tourism Assistant - مساعد السياحة")
 
 
 
 
12
 
13
- # Initialize session state for memory
14
  if "memory" not in st.session_state:
15
- st.session_state.memory = ConversationBufferMemory(return_messages=True)
 
 
 
16
 
17
- # Initialize session state for chat history
18
  if "messages" not in st.session_state:
19
  st.session_state.messages = []
20
 
21
- # Language selector
22
- language = st.selectbox("Choose Language / اختر اللغة", ["English", "العربية"])
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
- # Initialize the language model
34
- llm = HuggingFaceHub(
35
- repo_id=model_name,
36
- huggingface_api_token=hf_api_token,
37
- model_kwargs={"temperature": 0.7, "max_length": 512}
38
  )
39
 
40
- # Initialize conversation chain
41
- conversation = ConversationChain(
42
- llm=llm,
43
- memory=st.session_state.memory,
44
- verbose=True
45
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- # Display chat history
48
  for message in st.session_state.messages:
49
- with st.chat_message(message["role"]):
 
50
  st.markdown(message["content"])
51
 
52
- # User input
53
- if language == "English":
54
- prompt = st.chat_input("Ask about tourist destinations, recommendations, or travel tips...")
55
- else:
56
- prompt = st.chat_input("اسأل عن الوجهات السياحية أو التوصيات أو نصائح السفر...")
 
 
 
 
 
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 with a spinner
68
- with st.chat_message("assistant"):
69
- with st.spinner("Thinking..."):
70
- # Add context for tourism assistant
71
- if language == "English":
72
- full_prompt = f"You are a helpful tourism assistant. Answer the following question about travel and tourism: {prompt}"
73
- else:
74
- full_prompt = f"أنت مساعد سياحي مفيد. أجب عن السؤال التالي حول السفر والسياحة: {prompt}"
75
-
76
- response = conversation.predict(input=full_prompt)
77
- st.markdown(response)
78
-
79
- # Add assistant response to chat history
80
- st.session_state.messages.append({"role": "assistant", "content": response})
81
-
82
- # Sidebar with information
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  with st.sidebar:
84
- st.header("About this Chatbot")
 
85
  if language == "English":
86
- st.write(
87
- "This is a tourism assistant that can help you with travel recommendations, destination information, and travel tips.")
88
- st.write("Feel free to ask questions in English or Arabic!")
 
 
 
 
 
89
  else:
90
- st.write("هذا مساعد سياحي يمكنه مساعدتك في توصيات السفر ومعلومات الوجهة ونصائح السفر.")
91
- st.write("لا تتردد في طرح الأسئلة باللغة الإنجليزية أو العربية!")
 
 
 
 
 
 
 
 
 
 
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/)")