Skip to content

Commit

Permalink
working on web chat
Browse files Browse the repository at this point in the history
  • Loading branch information
eliranwong committed Nov 16, 2024
1 parent 50025c7 commit 72f0fb3
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 11 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
# https://packaging.python.org/en/latest/guides/distributing-packages-using-setuptools/
setup(
name=package,
version="0.1.84",
version="0.1.85",
python_requires=">=3.8, <3.13",
description=f"UniqueBible App is a cross-platform & offline bible application, integrated with high-quality resources and unique features. Developers: Eliran Wong and Oliver Tseng",
long_description=long_description,
Expand Down
2 changes: 1 addition & 1 deletion uniquebible/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def getChatResponse(backend, chatMessages) -> Optional[str]:
textOutput = completion.choices[0].message.content
# update the message chain in the config, to work with command `chat`
config.chatMessages = chatMessages
config.chatMessages.append({"role": "user", "content": textOutput})
config.chatMessages.append({"role": "assistant", "content": textOutput})
except:
textOutput = "Failed to connect! Please try again later."
if hasattr(config, "displayLanguage") and config.displayLanguage == "zh_HANT":
Expand Down
18 changes: 15 additions & 3 deletions uniquebible/util/RemoteHttpHandler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# https://docs.python.org/3/library/http.server.html
# https://ironpython-test.readthedocs.io/en/latest/library/simplehttpserver.html
import hashlib
import json
import json, markdown
import logging
import os, re, pprint, glob
from uniquebible import config
Expand Down Expand Up @@ -518,6 +518,7 @@ def loadContent(self):
"logout": self.logout,
"search": self.searchContent,
"qna": self.qnaContent,
"chat": self.chatContent,
"maps": self.mapsContent,
"days": self.dailyReadingContent,
"theme": self.swapTheme,
Expand Down Expand Up @@ -1048,13 +1049,14 @@ def getSideNavContent(self):
(config.thisTranslation["biblePromises"], ".promises"),
(config.thisTranslation["bibleHarmonies"], ".parallels"),
(config.thisTranslation["bibleAnswers"], ".qna") if config.addBibleQnA else None,
("AI " + config.thisTranslation["chat"], ".chat"),
(config.thisTranslation["readingPlan"], ".days"),
("{0} &#x1F50E;&#xFE0E;".format(config.thisTranslation["menu_search"]), ".search"),
(config.thisTranslation["download"], ".download"),
(config.thisTranslation["ubaCommands"], ".help"),
)
for item in sideNavItems:
if item is not None:
if item is not None and not (item[0].startswith("AI ") and not config.webHomePage==f"{config.webPrivateHomePage}.html"):
html += """<a href="#" onclick="submitCommand('{1}')">{0}</a>""".format(*item)
html += """<a href="{1}" target="_blank">{0}</a>""".format(config.thisTranslation["userManual"], self.getUserManual())
html += "<hr>"
Expand Down Expand Up @@ -1936,9 +1938,19 @@ def qnaContent(self):

def chatContent(self):
content = "<h2>AI {0}</h2>".format(config.thisTranslation["chat"])

if config.displayLanguage == "zh_HANT":
content += """<p>請輸入您的提問,然後按下按鈕「{0}」。</p>""".format(config.thisTranslation["send"])
elif config.displayLanguage == "zh_HANS":
content += """<p>请输入您的提问,然后按下按钮「{0}」。</p>""".format(config.thisTranslation["send"])
else:
content += """<p>Please enter your query and click the button '{0}'.</p>""".format(config.thisTranslation["send"])
content += "<p><input type='text' id='chatInput' style='width:95%' autofocus></p>"
content += "<p><button id='openChatInputButton' type='button' onclick='bibleChat();' class='ubaButton'>{0}</button></p>".format(config.thisTranslation["send"])

content += "<hr>"
content += "\n\n".join([f'''# {i.get("role", "")}\n\n{i.get("content", "")}'''for i in config.chatMessages])
textOutput = markdown.markdown(textOutput)

content += """
<script>
function bibleChat() {0}
Expand Down
45 changes: 39 additions & 6 deletions uniquebible/util/TextCommandParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,10 +413,15 @@ def __init__(self, parent):
"chat": (self.textChat, """
# [KEYWORD] CHAT
# Feature - Chat with AI or follow up previous conversation.
# Usage - CHAT:::[BACKEND]:::[QUERY]
# Usage - CHAT:::[BACKEND]:::[OPERATOR]:::[QUERY]
# BACKEND options: openai, google, groq, mistral
# Use value of `config.llm_backend` as backend if BACKEND is not given.
# e.g. CHAT:::Tell me more"""),
# OPERATOR options: new, show [optional]
new - start a new conversation
show - show the whole conversation
# e.g. CHAT:::NEW:::Hi!
# e.g. CHAT:::Tell me more
# e.g. CHAT:::SHOW"""),
"map": (self.textMap, """
# [KEYWORD] MAP
# Feature - Open a Google map with bible locations pinned
Expand Down Expand Up @@ -4537,7 +4542,9 @@ def textAiCommentary(self, command, source="", systemMessage="", goBack=""):
{textOutput}"""
return ("study", textOutput, {'tab_title': "AI"})

def textChat(self, command, source):
def textChat(self, command, _):
if config.runMode == "http-server" and hasattr(config, "webHomePage") and not config.webHomePage==f"{config.webPrivateHomePage}.html":
return self.invalidCommand()
if command.strip():
command = command.strip()
backendPattern = "|".join(config.llm_backends)
Expand All @@ -4561,14 +4568,14 @@ def textChat(self, command, source):
feature = ""
if not command.strip():
return self.invalidCommand()
if not hasattr(config, "chatMessages") or not config.chatMessages or feature.lower() == "new":::
if not hasattr(config, "chatMessages") or not config.chatMessages or feature.lower() == "new":
config.chatMessages = [
{"role": "system", "content": bibleChat_systemMessage},
{"role": "system", "content": config.bibleChat_systemMessage},
{"role": "user", "content": command.strip()},
]
else:
config.chatMessages.append({"role": "user", "content": command.strip()})
textOutput = getChatResponse(backend, chatMessages)
textOutput = getChatResponse(backend, config.chatMessages)
if textOutput is None:
return ("study", "<p>AI Backend API key not found!</p>", {'tab_title': "AI"})
if not config.rawOutput:
Expand All @@ -4578,8 +4585,34 @@ def textChat(self, command, source):
bibleVerseParser = BibleVerseParser(config.parserStandarisation)
textOutput = bibleVerseParser.parseText(textOutput, splitInChunks=True, parseBooklessReferences=False, canonicalOnly=True)
if config.runMode == "http-server":

if config.displayLanguage == "zh_HANT":
textOutput += """<hr><p>如想繼續查詢,請輸入您的提問,然後按下按鈕「{0}」。</p>""".format(config.thisTranslation["send"])
elif config.displayLanguage == "zh_HANS":
textOutput += """<hr><p>如想继续查询,请输入您的提问,然后按下按钮「{0}」。</p>""".format(config.thisTranslation["send"])
else:
textOutput += """<hr><p>To continue, enter your query and click the button '{0}'.</p>""".format(config.thisTranslation["send"])
textOutput += "<p><input type='text' id='chatInput' style='width:95%' autofocus> "
textOutput += "<button id='openChatInputButton' type='button' onclick='bibleChat();' class='ubaButton'>{0}</button></p>".format(config.thisTranslation["send"])

goBack = 'document.title=".chat"'
textOutput += """<hr><p><button type='button' onclick='{0}' class='ubaButton'>{1}</button></p>""".format(goBack, config.thisTranslation["youtube_back"])

textOutput += """
<script>
function bibleChat() {0}
var searchString = document.getElementById('chatInput').value;
document.title = "CHAT":::"+searchString;
{1}
var input = document.getElementById('chatInput');
input.addEventListener('keyup', function(event) {0}
if (event.keyCode === 13) {0}
event.preventDefault();
document.getElementById('openChatInputButton').click();
{1}
{1});
</script>""".format("{", "}")

# Disclaimer
textOutput += getAiFeatureDisclaimer()
return ("study", textOutput, {'tab_title': "AI"})
Expand Down

0 comments on commit 72f0fb3

Please sign in to comment.