galuhalifani commited on
Commit
ea729ef
·
1 Parent(s): 4d31eb2

add time bound

Browse files
Files changed (4) hide show
  1. src/app.py +69 -59
  2. src/handler.py +13 -1
  3. src/prompt.py +9 -14
  4. src/test.ipynb +0 -152
src/app.py CHANGED
@@ -16,10 +16,11 @@ from streamlit_option_menu import option_menu
16
  import os
17
  import re
18
  from model import ask
19
- from handler import save_feedback, translate_answer, check_question_feedback
20
  from text import feedback_instr, no_affiliation, description, no_replacement_for_official_advice, source_of_answer_short, source_of_answer
21
  from langdetect import detect
22
  from deep_translator import GoogleTranslator
 
23
 
24
  primary_color = "#ffffff"
25
  secondary_color = "#1E1E1E"
@@ -86,6 +87,8 @@ st.markdown(f"""
86
  </style>
87
  """, unsafe_allow_html=True)
88
 
 
 
89
  # Sidebar Menu
90
  with st.sidebar:
91
 
@@ -194,72 +197,79 @@ if selected == "Chatbot":
194
  "content": "Hello! I'm Instant. How can I help you today?"
195
  }]
196
 
 
197
  # Display Chat History
198
- for message in st.session_state.messages:
199
- if message["role"] == "user":
200
- st.markdown(f"""
201
- <div class="chat-container">
202
- <div class="user-message">
203
- 😀 <strong>You</strong><br>
204
- {message["content"]}
 
205
  </div>
206
- </div>
207
- """, unsafe_allow_html=True)
208
- else:
209
- st.markdown(f"""
210
- <div class="chat-container">
211
- <div class="assistant-message">
212
- 🤖 <strong>Instant Bot</strong><br>
213
- {message["content"]}
214
  </div>
215
- </div>
216
- """, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
- query = st.chat_input("Ask your question here... (Example: How to apply for KITAS?)")
219
-
220
- if query:
221
- if len(query) > 500:
222
- char_too_long = "Sorry, your message is too long. Please shorten it to less than 500 characters."
223
- st.session_state.messages.append({
224
- "role": "assistant",
225
- "type": "warning",
226
- "content": char_too_long
227
- })
228
- st.rerun()
229
- else:
230
- is_feedback = check_question_feedback(query, "anonymous")
231
-
232
- if is_feedback['is_feedback']:
233
- st.session_state.messages.append({"role": "user", "type": "feedback", "content": query})
234
- last_question = is_feedback['last_qna']['question']
235
-
236
- if not last_question:
237
- resp = "Sorry, you have not asked a question, or the session has been reset. Please ask a question first before providing feedback."
238
- st.session_state.messages.append({
239
- "role": "assistant",
240
- "type": "warning",
241
- "content": resp
242
- })
243
- st.rerun()
244
  else:
245
- feedback_obj = is_feedback['feedback_obj']
246
- last_qna = is_feedback['last_qna']
247
-
248
- response = save_feedback(feedback_obj, last_qna)
249
- if "error" not in response:
250
- st.toast("Feedback recorded!", icon="💾")
251
-
252
- st.markdown(response)
253
 
254
- else:
255
- st.session_state.messages.append({"role": "user", "type": "question", "content": query})
256
-
257
- with st.spinner("Looking up..."):
258
- answer = ask(query)
259
 
260
- st.session_state.messages.append({"role": "assistant", "type": "answer", "content": answer})
261
- st.rerun()
262
 
 
 
 
 
263
  elif selected == "About":
264
  st.markdown("### 📟 About Instant")
265
  st.markdown(f"""
 
16
  import os
17
  import re
18
  from model import ask
19
+ from handler import save_feedback, translate_answer, check_question_feedback, translate_text, deduct_chat_balance, check_user_balance
20
  from text import feedback_instr, no_affiliation, description, no_replacement_for_official_advice, source_of_answer_short, source_of_answer
21
  from langdetect import detect
22
  from deep_translator import GoogleTranslator
23
+ from datetime import datetime
24
 
25
  primary_color = "#ffffff"
26
  secondary_color = "#1E1E1E"
 
87
  </style>
88
  """, unsafe_allow_html=True)
89
 
90
+ current_hour = datetime.now().hour
91
+
92
  # Sidebar Menu
93
  with st.sidebar:
94
 
 
197
  "content": "Hello! I'm Instant. How can I help you today?"
198
  }]
199
 
200
+ if (10 <= current_hour < 13) or (17 <= current_hour < 20):
201
  # Display Chat History
202
+ for message in st.session_state.messages:
203
+ if message["role"] == "user":
204
+ st.markdown(f"""
205
+ <div class="chat-container">
206
+ <div class="user-message">
207
+ 😀 <strong>You</strong><br>
208
+ {message["content"]}
209
+ </div>
210
  </div>
211
+ """, unsafe_allow_html=True)
212
+ else:
213
+ st.markdown(f"""
214
+ <div class="chat-container">
215
+ <div class="assistant-message">
216
+ 🤖 <strong>Instant Bot</strong><br>
217
+ {message["content"]}
218
+ </div>
219
  </div>
220
+ """, unsafe_allow_html=True)
221
+
222
+ query = st.chat_input("Ask your question here... (Example: How to apply for KITAS?)")
223
+
224
+ if query:
225
+ lang = detect(query)
226
+ if len(query) > 150:
227
+ char_too_long = "Sorry, your message is too long. Please shorten it to less than 150 characters."
228
+ exceed_length_resp = translate_text(lang, char_too_long)
229
+ st.session_state.messages.append({
230
+ "role": "assistant",
231
+ "type": "warning",
232
+ "content": exceed_length_resp
233
+ })
234
+ st.rerun()
235
+ else:
236
+ is_feedback = check_question_feedback(query, "anonymous")
237
+
238
+ if is_feedback['is_feedback']:
239
+ st.session_state.messages.append({"role": "user", "type": "feedback", "content": query})
240
+ last_question = is_feedback['last_qna']['question']
241
+
242
+ if not last_question:
243
+ resp = "Sorry, you have not asked a question, or the session has been reset. Please ask a question first before providing feedback."
244
+ st.session_state.messages.append({
245
+ "role": "assistant",
246
+ "type": "warning",
247
+ "content": resp
248
+ })
249
+ st.rerun()
250
+ else:
251
+ feedback_obj = is_feedback['feedback_obj']
252
+ last_qna = is_feedback['last_qna']
253
+
254
+ response = save_feedback(feedback_obj, last_qna)
255
+ if "error" not in response:
256
+ st.toast("Feedback recorded!", icon="💾")
257
+
258
+ st.markdown(response)
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  else:
261
+ st.session_state.messages.append({"role": "user", "type": "question", "content": query})
 
 
 
 
 
 
 
262
 
263
+ with st.spinner("Looking up..."):
264
+ answer = ask(query)
 
 
 
265
 
266
+ st.session_state.messages.append({"role": "assistant", "type": "answer", "content": answer})
267
+ st.rerun()
268
 
269
+ else:
270
+ st.info("Sorry, due to usage control, the web-based bot is only available between 9 AM - 1 PM and between 5 PM - 8 PM.\nFor 24-hour access, you can utilize our WhatsApp Bot at +1 234 423 4277.\n\n")
271
+ query = None
272
+
273
  elif selected == "About":
274
  st.markdown("### 📟 About Instant")
275
  st.markdown(f"""
src/handler.py CHANGED
@@ -114,4 +114,16 @@ def translate_list(question, list_of_answers):
114
  translated.append(answer)
115
  return translated
116
  else:
117
- return list_of_answers
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  translated.append(answer)
115
  return translated
116
  else:
117
+ return list_of_answers
118
+
119
+
120
+ def translate_text(lang, text):
121
+ supported_languages = ['en', 'id', 'fr', 'de', 'th', 'es', 'it', 'pt', 'ja', 'ko', 'zh-cn', 'zh-tw', 'ru']
122
+ try:
123
+ if lang in supported_languages:
124
+ translated = GoogleTranslator(source='auto', target=lang).translate(text)
125
+ return translated
126
+ else:
127
+ return text
128
+ except Exception as e:
129
+ return text
src/prompt.py CHANGED
@@ -8,31 +8,26 @@ PROFESSIONAL_PROMPT = PromptTemplate(
8
  You are NOT affiliated with the Indonesian government or Immigration Office. Do not imply any official role.
9
 
10
  Your main tasks:
11
- - Answer questions about Indonesian immigration
12
- - Explain procedures or regulations in simple terms
13
- - Guide users through steps, documents, or troubleshooting
14
  - Translate queries to Indonesian for context searching, then respond in the original query language
15
 
16
  Situational behavior:
17
- - If input looks like feedback, confirm and explain the format: “helpful” or “not helpful” followed by comment
18
  - If asked about storing conversation history, clarify it's only stored session-based and erased after 3 hours of inactivity or session closure
19
- - If multiple questions are asked in one sentence, try answering all or provide conditional possibilities.
20
- - If the question is not clear or too vague, ask for clarification and more details in a polite manner, except when they are asking about the scope of your service in general.
21
- - If the question is very specific to a certain scenario or case, provide a general but thorough answer, and politely suggest them to contact the official support for further assistance (provide link or contact).
22
- - For specific details such as fees, duration, other questions that are not covered in the context, or answers with low confidence, you can ask user whether they are ok for you to search the web for the answer, and if the user agrees to search the web, you can use the web search tool to find the answer and provide it to the user by adding the source of the information in the answer.
23
-
24
  Response rules:
25
- - Only respond to questions about Indonesian immigration or related to your scope of service or capabilities; politely decline others
26
  - Be formal, helpful, and concise
27
- - If the question appears in English, respond in English.
28
  - If the question appears in Indonesian, respond in Indonesian.
29
  - If the question is in another language, detect the language and respond in that language.
30
  - If you are uncertain of the question's language, respond in English.
31
- - Try to avoid including "others", "etc.", or "typically" when referring to documents or requirements and instead, provide a thorough & complete list and mention that the list might vary depending on cases.
32
- - For duration or fees, if the answer varies, provide ballpark estimate or ranges, and include the general conditions that apply for those range if applicable.
33
  - Include Reference starting with “Read more at [Reference URL]” on a new line if a reference exists — omit if not
34
  - Do not label the question or the context — output only the answer
35
- - Answer questions in a detailed and thorough manner: include list of documents required, requirements, fee ranges and details, step-by-step instructions, and conditional situations if applicable.
36
  - End your answer with:
37
  (two line breaks)
38
  To provide feedback, you can type 'helpful' or 'not helpful' followed by your comment.
 
8
  You are NOT affiliated with the Indonesian government or Immigration Office. Do not imply any official role.
9
 
10
  Your main tasks:
11
+ - Only respond to questions about Indonesian immigration or your scope of service; politely decline others
12
+ - Explain in simple terms
 
13
  - Translate queries to Indonesian for context searching, then respond in the original query language
14
 
15
  Situational behavior:
 
16
  - If asked about storing conversation history, clarify it's only stored session-based and erased after 3 hours of inactivity or session closure
17
+ - If the question is not clear or too vague, ask for clarification and more details in a polite manner, except when it's about the scope of your service in general.
18
+ - If the question is very specific to a certain scenario, provide a general but thorough answer, and politely suggest to contact the official support for further assistance (provide link or contact).
19
+ - If input seems like a feedback, confirm and explain the format: type “helpful” or “not helpful” followed by comment
20
+
 
21
  Response rules:
 
22
  - Be formal, helpful, and concise
 
23
  - If the question appears in Indonesian, respond in Indonesian.
24
  - If the question is in another language, detect the language and respond in that language.
25
  - If you are uncertain of the question's language, respond in English.
26
+ - Try to avoid including "others", "etc.", or "typically", and instead, provide a complete list or options, and mention that it might vary depending on cases.
27
+ - For duration or fees, if the answer varies, provide ballpark estimate or ranges, and explain this range.
28
  - Include Reference starting with “Read more at [Reference URL]” on a new line if a reference exists — omit if not
29
  - Do not label the question or the context — output only the answer
30
+ - Answer questions in a detailed manner but concise: include list of documents required, requirements, fee ranges, step-by-step instructions.
31
  - End your answer with:
32
  (two line breaks)
33
  To provide feedback, you can type 'helpful' or 'not helpful' followed by your comment.
src/test.ipynb DELETED
@@ -1,152 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": 15,
6
- "id": "a9e1ee7b",
7
- "metadata": {},
8
- "outputs": [
9
- {
10
- "name": "stdout",
11
- "output_type": "stream",
12
- "text": [
13
- "Collecting pycld3\n",
14
- " Downloading pycld3-0.22.tar.gz (726 kB)\n",
15
- " ---------------------------------------- 0.0/726.2 kB ? eta -:--:--\n",
16
- " -------------------------------------- 726.2/726.2 kB 7.4 MB/s eta 0:00:00\n",
17
- " Preparing metadata (setup.py): started\n",
18
- " Preparing metadata (setup.py): finished with status 'done'\n",
19
- "Building wheels for collected packages: pycld3\n",
20
- " Building wheel for pycld3 (setup.py): started\n",
21
- " Building wheel for pycld3 (setup.py): finished with status 'error'\n",
22
- " Running setup.py clean for pycld3\n",
23
- "Failed to build pycld3\n",
24
- "Note: you may need to restart the kernel to use updated packages.\n"
25
- ]
26
- },
27
- {
28
- "name": "stderr",
29
- "output_type": "stream",
30
- "text": [
31
- " error: subprocess-exited-with-error\n",
32
- " \n",
33
- " × python setup.py bdist_wheel did not run successfully.\n",
34
- " │ exit code: 1\n",
35
- " ╰─> [33 lines of output]\n",
36
- " c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\config\\setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead.\n",
37
- " warnings.warn(msg, warning_class)\n",
38
- " running bdist_wheel\n",
39
- " running build\n",
40
- " Traceback (most recent call last):\n",
41
- " File \"<string>\", line 2, in <module>\n",
42
- " File \"<pip-setuptools-caller>\", line 34, in <module>\n",
43
- " File \"C:\\Users\\galuh\\AppData\\Local\\Temp\\pip-install-w5qpinu3\\pycld3_f438ade9f53247f9b314b266b14146d1\\setup.py\", line 173, in <module>\n",
44
- " setup(\n",
45
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\__init__.py\", line 87, in setup\n",
46
- " return distutils.core.setup(**attrs)\n",
47
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\_distutils\\core.py\", line 185, in setup\n",
48
- " return run_commands(dist)\n",
49
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\_distutils\\core.py\", line 201, in run_commands\n",
50
- " dist.run_commands()\n",
51
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\_distutils\\dist.py\", line 968, in run_commands\n",
52
- " self.run_command(cmd)\n",
53
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\dist.py\", line 1217, in run_command\n",
54
- " super().run_command(command)\n",
55
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\_distutils\\dist.py\", line 987, in run_command\n",
56
- " cmd_obj.run()\n",
57
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\wheel\\_bdist_wheel.py\", line 387, in run\n",
58
- " self.run_command(\"build\")\n",
59
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\_distutils\\cmd.py\", line 319, in run_command\n",
60
- " self.distribution.run_command(command)\n",
61
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\dist.py\", line 1217, in run_command\n",
62
- " super().run_command(command)\n",
63
- " File \"c:\\Users\\galuh\\miniconda\\envs\\py10\\lib\\site-packages\\setuptools\\_distutils\\dist.py\", line 987, in run_command\n",
64
- " cmd_obj.run()\n",
65
- " File \"C:\\Users\\galuh\\AppData\\Local\\Temp\\pip-install-w5qpinu3\\pycld3_f438ade9f53247f9b314b266b14146d1\\setup.py\", line 109, in run\n",
66
- " raise RuntimeError(\n",
67
- " RuntimeError: The Protobuf compiler, `protoc`, which is required for building this package, could not be found.\n",
68
- " See https://github.com/protocolbuffers/protobuf for information on installing Protobuf.\n",
69
- " [end of output]\n",
70
- " \n",
71
- " note: This error originates from a subprocess, and is likely not a problem with pip.\n",
72
- " ERROR: Failed building wheel for pycld3\n",
73
- "ERROR: Failed to build installable wheels for some pyproject.toml based projects (pycld3)\n"
74
- ]
75
- }
76
- ],
77
- "source": [
78
- "%pip install pycld3"
79
- ]
80
- },
81
- {
82
- "cell_type": "code",
83
- "execution_count": 16,
84
- "id": "92d4ce64",
85
- "metadata": {},
86
- "outputs": [
87
- {
88
- "ename": "ModuleNotFoundError",
89
- "evalue": "No module named 'pycld3'",
90
- "output_type": "error",
91
- "traceback": [
92
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
93
- "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
94
- "Cell \u001b[1;32mIn[16], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mpycld3\u001b[39;00m\n\u001b[0;32m 3\u001b[0m result \u001b[38;5;241m=\u001b[39m pycld3\u001b[38;5;241m.\u001b[39mget_language(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgimana cara apply kitas\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(result\u001b[38;5;241m.\u001b[39mlanguage) \u001b[38;5;66;03m# e.g. 'id'\u001b[39;00m\n",
95
- "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'pycld3'"
96
- ]
97
- }
98
- ],
99
- "source": [
100
- "import pycld3\n",
101
- "\n",
102
- "result = pycld3.get_language(\"gimana cara apply kitas\")\n",
103
- "print(result.language) # e.g. 'id'\n",
104
- "print(result.probability) # e.g. 0.93"
105
- ]
106
- },
107
- {
108
- "cell_type": "code",
109
- "execution_count": 12,
110
- "id": "579398bb",
111
- "metadata": {},
112
- "outputs": [
113
- {
114
- "name": "stdout",
115
- "output_type": "stream",
116
- "text": [
117
- "[tl:0.999996238892189]\n"
118
- ]
119
- }
120
- ],
121
- "source": [
122
- "from langdetect import detect_langs\n",
123
- "\n",
124
- "text = 'gimana cara apply kitas?'\n",
125
- "langs = detect_langs(text)\n",
126
- "\n",
127
- "print(langs)\n"
128
- ]
129
- }
130
- ],
131
- "metadata": {
132
- "kernelspec": {
133
- "display_name": "py10",
134
- "language": "python",
135
- "name": "python3"
136
- },
137
- "language_info": {
138
- "codemirror_mode": {
139
- "name": "ipython",
140
- "version": 3
141
- },
142
- "file_extension": ".py",
143
- "mimetype": "text/x-python",
144
- "name": "python",
145
- "nbconvert_exporter": "python",
146
- "pygments_lexer": "ipython3",
147
- "version": "3.10.16"
148
- }
149
- },
150
- "nbformat": 4,
151
- "nbformat_minor": 5
152
- }