Skip to content

Commit 13da986

Browse files
committed
added stream mode
1 parent 03fe95c commit 13da986

11 files changed

+143
-77
lines changed

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
# https://packaging.python.org/en/latest/guides/distributing-packages-using-setuptools/
4242
setup(
4343
name=package,
44-
version="0.1.07",
44+
version="0.1.12",
4545
python_requires=">=3.8, <3.13",
4646
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",
4747
long_description=long_description,

uniquebible/latest_changes.txt

+12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
11
PIP package:
22

3+
0.1.09-12
4+
5+
* added a 'stream' mode to work with stdin and stdout, e.g.
6+
7+
> uniquebible stream John 3:16-18
8+
9+
> echo 3:16-18 | uniquebible stream John
10+
11+
0.1.03-0.1.08
12+
13+
* integrated with Toolmate AI, read https://github.com/eliranwong/toolmate
14+
315
0.1.02
416

517
* fixed plugin menu

uniquebible/main.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
os.environ[key] = value
4040

4141
# check runmode and initial command
42-
config.noQt = True if config.runMode in ("terminal", "ssh-server", "telnet-server", "http-server", "api-server", "execute-macro") else False
42+
config.noQt = True if config.runMode in ("stream", "terminal", "ssh-server", "telnet-server", "http-server", "api-server", "execute-macro") or os.path.isdir("/data/data/com.termux/files/home") else False
4343
config.cli = True if config.runMode == "cli" else False
4444
config.enableCli = True if config.runMode in ("cli", "gui", "docker") else False
4545
config.enableApiServer = True if config.runMode == "api-server" else False
@@ -121,7 +121,9 @@
121121
# ("terminal", "ssh-server", "telnet-server", "http-server", "api-server", "execute-macro")
122122
if config.noQt:
123123
from uniquebible.startup.nonGui import *
124-
if config.runMode == "terminal":
124+
if config.runMode == "stream":
125+
run_stream_mode()
126+
elif config.runMode == "terminal":
125127
run_terminal_mode()
126128
elif config.runMode == "ssh-server":
127129
run_ssh_server(host=config.sshServerHost, port=config.sshServerPort, server_host_keys=config.sshServerHostKeys, passphrase=config.sshServerPassphrase)

uniquebible/startup/nonGui.py

+17
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,23 @@ def run_terminal_mode():
225225
clear_title()
226226
sys.exit(0)
227227

228+
# raw mode
229+
def run_stream_mode():
230+
from uniquebible.util.LocalCliHandler import LocalCliHandler
231+
232+
input_text = sys.stdin.read() if not sys.stdin.isatty() else ""
233+
234+
# Set initial command
235+
command = config.initial_command if config.initial_command else " ".join(sys.argv[2:]).strip()
236+
if input_text:
237+
command = f"{command} {input_text}"
238+
if command.strip():
239+
config.mainWindow = LocalCliHandler()
240+
output_text = config.mainWindow.getContent(command)
241+
else:
242+
output_text = "Command not given!"
243+
print(output_text, file=sys.stdout)
244+
228245
# ssh-server
229246
# read setup guide at https://github.com/eliranwong/UniqueBible/wiki/Run-SSH-Server
230247
def run_ssh_server(host="", port=2222, server_host_keys="", passphrase="the_best_bible_app"):

uniquebible/uba.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def main():
1616

1717
# check running mode and initial command
1818
runMode = sys.argv[1] if len(sys.argv) > 1 else ""
19-
enableCli = True if runMode.lower() in ("cli", "cli.py", "gui", "terminal", "docker", "telnet-server", "http-server", "execute-macro", "api-server") else False
19+
enableCli = True if runMode.lower() in ("stream", "cli", "cli.py", "gui", "terminal", "docker", "telnet-server", "http-server", "execute-macro", "api-server") else False
2020
initialCommand = input("Enter command: ").strip() if runMode == "-i" else " ".join(sys.argv[1:]).strip()
2121
initialCommand = initialCommand.strip()
2222

uniquebible/util/CatalogUtil.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
from uniquebible import config
33
from uniquebible.util.FileUtil import FileUtil
44
from uniquebible.util.GitHubRepoInfo import GitHubRepoInfo
5-
if not config.noQt:
6-
from uniquebible.util.GithubUtil import GithubUtil
75

86

97
class CatalogUtil:
@@ -93,6 +91,7 @@ def loadRemoteCatalog():
9391

9492
@staticmethod
9593
def loadRemoteFiles(type, repo):
94+
from uniquebible.util.GithubUtil import GithubUtil
9695
data = []
9796
github = GithubUtil(repo[0])
9897
repoData = github.getRepoData()

uniquebible/util/ConfigUtil.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,15 @@ def setup(noQt=None, cli=None, enableCli=None, enableApiServer=None, enableHttpS
6262
config.ubaDir = os.getcwd()
6363

6464
# check running mode
65-
config.runMode = sys.argv[1].lower() if len(sys.argv) > 1 else ""
66-
if config.runMode and not config.runMode in ("setup-only", "cli", "gui", "terminal", "docker", "telnet-server", "http-server", "execute-macro", "api-server"):
65+
config.runMode = sys.argv[1] if len(sys.argv) > 1 else ""
66+
if " " in config.runMode:
67+
import re
68+
config.runMode, config.initial_command = config.runMode.split(" ", 1)
69+
else:
70+
config.initial_command = ""
71+
config.runMode = config.runMode.lower()
72+
73+
if config.runMode and not config.runMode in ("stream", "setup-only", "cli", "gui", "terminal", "docker", "telnet-server", "http-server", "execute-macro", "api-server"):
6774
config.runMode = ""
6875

6976
# Check current version
@@ -136,7 +143,7 @@ def getCurrentVenvDir():
136143
[])
137144
setConfig("disabled", """
138145
# Disabled modules""",
139-
[])
146+
['Pygithub', 'Textract', 'Pydnsbl', 'Pocketsphinx'] if os.path.isdir("/data/data/com.termux/files/home") else [])
140147
venvDir = getCurrentVenvDir()
141148
setConfig("venvDir", """
142149
# virtual environment directory""",

uniquebible/util/LocalCliHandler.py

+73-49
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from base64 import b64decode
99
#import urllib.request
1010
from ast import literal_eval
11+
from haversine import haversine
12+
1113
from uniquebible.db.BiblesSqlite import Bible
1214
from uniquebible.db.JournalSqlite import JournalSqlite
1315
from uniquebible.db.ToolsSqlite import Book
@@ -31,23 +33,25 @@
3133
from uniquebible.util.HBN import HBN
3234
from uniquebible.util.terminal_text_editor import TextEditor
3335
from uniquebible.util.terminal_system_command_prompt import SystemCommandPrompt
34-
from uniquebible.util.terminal_mode_dialogs import TerminalModeDialogs
35-
from uniquebible.util.get_path_prompt import GetPath
36+
if not config.runMode == "stream":
37+
from uniquebible.util.terminal_mode_dialogs import TerminalModeDialogs
38+
from uniquebible.util.get_path_prompt import GetPath
3639
from uniquebible.util.PromptValidator import NumberValidator, NoAlphaValidator
3740
from uniquebible.util.prompt_shared_key_bindings import prompt_shared_key_bindings
3841
from uniquebible.util.prompt_multiline_shared_key_bindings import prompt_multiline_shared_key_bindings
3942
from uniquebible.util.ConfigUtil import ConfigUtil
4043
from uniquebible.util.exlbl import allLocations
41-
from prompt_toolkit import PromptSession, prompt, print_formatted_text, HTML
42-
from prompt_toolkit.shortcuts import clear, confirm
43-
from prompt_toolkit.filters import Condition
44-
#from prompt_toolkit.application import run_in_terminal
45-
from prompt_toolkit.key_binding import KeyBindings, merge_key_bindings
46-
from prompt_toolkit.completion import WordCompleter, NestedCompleter, ThreadedCompleter, FuzzyCompleter
47-
from prompt_toolkit.history import FileHistory
48-
from prompt_toolkit.styles import Style
49-
#from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
50-
from haversine import haversine
44+
45+
if not config.runMode == "stream":
46+
from prompt_toolkit import PromptSession, prompt, print_formatted_text, HTML
47+
from prompt_toolkit.shortcuts import clear, confirm
48+
from prompt_toolkit.filters import Condition
49+
#from prompt_toolkit.application import run_in_terminal
50+
from prompt_toolkit.key_binding import KeyBindings, merge_key_bindings
51+
from prompt_toolkit.completion import WordCompleter, NestedCompleter, ThreadedCompleter, FuzzyCompleter
52+
from prompt_toolkit.history import FileHistory
53+
from prompt_toolkit.styles import Style
54+
#from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
5155

5256

5357
class LocalCliHandler:
@@ -61,12 +65,14 @@ def __init__(self, command="John 3:16"):
6165
self.crossPlatform.setupResourceLists()
6266
self.html = "<ref >Unique Bible App</ref>"
6367
self.plainText = "Unique Bible App"
64-
self.setupDialogs()
68+
if not config.runMode == "stream":
69+
self.setupDialogs()
6570
self.audioPlayer = None
6671
self.command = command
67-
self.dotCommands = self.getDotCommands()
72+
self.dotCommands = {} if config.runMode == "stream" else self.getDotCommands()
6873
self.addShortcuts()
69-
self.initPromptElements()
74+
if not config.runMode == "stream":
75+
self.initPromptElements()
7076
self.setOsOpenCmd()
7177
self.ttsLanguages = self.getTtsLanguages()
7278
self.ttsLanguageCodes = list(self.ttsLanguages.keys())
@@ -85,14 +91,15 @@ def __init__(self, command="John 3:16"):
8591
self.startupException2 = "^(_setconfig:::|\.edit|\.change|\.toggle|\.stop|\.exec|mp3:::|mp4:::|cmd:::|\.backup|\.restore|gtts:::|speak:::|download:::|read:::|readsync:::|semantic:::)"
8692
#config.cliTtsProcess = None
8793
config.audio_playing_file = os.path.join("temp", "000_audio_playing.txt")
88-
self.getPath = GetPath(
89-
cancel_entry=config.terminal_cancel_action,
90-
promptIndicatorColor=config.terminalPromptIndicatorColor2,
91-
promptEntryColor=config.terminalCommandEntryColor2,
92-
subHeadingColor=config.terminalHeadingTextColor,
93-
itemColor=config.terminalResourceLinkColor,
94-
)
95-
self.shareKeyBindings()
94+
if not config.runMode == "stream":
95+
self.getPath = GetPath(
96+
cancel_entry=config.terminal_cancel_action,
97+
promptIndicatorColor=config.terminalPromptIndicatorColor2,
98+
promptEntryColor=config.terminalCommandEntryColor2,
99+
subHeadingColor=config.terminalHeadingTextColor,
100+
itemColor=config.terminalResourceLinkColor,
101+
)
102+
self.shareKeyBindings()
96103

97104
def setupDialogs(self):
98105
self.dialogs = TerminalModeDialogs(self)
@@ -357,7 +364,7 @@ def addShortcuts(self):
357364
self.dotCommands[key] = (f"an alias to '{value}'", partial(self.getContent, value))
358365

359366
def getDotCommands(self):
360-
return {
367+
return {} if config.runMode == "stream" else {
361368
config.terminal_cancel_action: ("cancel action in current prompt", self.cancelAction),
362369
".togglecolorbrightness": ("toggle color brightness", self.togglecolorbrightness),
363370
".togglecolourbrightness": ("an alias to '.togglecolorbrightness'", self.togglecolorbrightness),
@@ -629,7 +636,7 @@ def getDotCommands(self):
629636
".portablepython": ("build portable python", self.buildPortablePython),
630637
".system": ("system command prompt", SystemCommandPrompt().run),
631638
".sys": ("an alias to '.system'", SystemCommandPrompt().run),
632-
".clear": ("clear screen", clear),
639+
".clear": ("clear screen", self.clear_screen),
633640
".wordnet": ("wordnet dictionary", self.wordnet),
634641
".customize": ("an alias to '.customise'", self.customise),
635642
".mp3": ("play mp3 files in music folder", self.mp3),
@@ -646,6 +653,9 @@ def getDotCommands(self):
646653
#".image": ("bible chat", self.generateImage),
647654
}
648655

656+
def clear_screen(self):
657+
clear()
658+
649659
def calculate(self):
650660
userInput = ""
651661
self.print("Calculate:")
@@ -1421,7 +1431,11 @@ def showdata(self):
14211431
def showdownloads(self):
14221432
content = ""
14231433
from uniquebible.util.DatafileLocation import DatafileLocation
1424-
from uniquebible.util.GithubUtil import GithubUtil
1434+
try:
1435+
from uniquebible.util.GithubUtil import GithubUtil
1436+
githubutilEnabled = True
1437+
except:
1438+
githubutilEnabled = False
14251439
# ["marveldata", "marvelbible", "marvelcommentary", "GitHubBible", "GitHubCommentary", "GitHubBook", "GitHubMap", "GitHubPdf", "GitHubEpub"]
14261440
resources = (
14271441
("Marvel Datasets", DatafileLocation.marvelData, "marveldata"),
@@ -1435,21 +1449,22 @@ def showdownloads(self):
14351449
content += """[ {1} ] {0}<br>""".format(k, config.thisTranslation["installed"])
14361450
else:
14371451
content += """[<ref>DOWNLOAD:::{0}:::{1}</ref> ]<br>""".format(keyword, k)
1438-
resources = (
1439-
("GitHub Bibles", "GitHubBible", GitHubRepoInfo.bibles[0], (config.marvelData, "bibles"), ".bible"),
1440-
("GitHub Commentaries", "GitHubCommentary", GitHubRepoInfo.commentaries[0], (config.marvelData, "commentaries"), ".commentary"),
1441-
("GitHub Books", "GitHubBook", GitHubRepoInfo.books[0], (config.marvelData, "books"), ".book"),
1442-
("GitHub Maps", "GitHubMap", GitHubRepoInfo.maps[0], (config.marvelData, "books"), ".book"),
1443-
("GitHub PDF", "GitHubPdf", GitHubRepoInfo.pdf[0], (config.marvelData, "pdf"), ".pdf"),
1444-
("GitHub EPUB", "GitHubEpub", GitHubRepoInfo.epub[0], (config.marvelData, "epub"), ".epub"),
1445-
)
1446-
for collection, type, repo, location, extension in resources:
1447-
content += "<h2>{0}</h2>".format(collection)
1448-
for file in GithubUtil(repo).getRepoData():
1449-
if os.path.isfile(os.path.join(*location, file)):
1450-
content += """[ {1} ] {0}<br>""".format(file.replace(extension, ""), config.thisTranslation["installed"])
1451-
else:
1452-
content += """[<ref>DOWNLOAD:::{1}:::{0}</ref> ]<br>""".format(file.replace(extension, ""), type)
1452+
if githubutilEnabled:
1453+
resources = (
1454+
("GitHub Bibles", "GitHubBible", GitHubRepoInfo.bibles[0], (config.marvelData, "bibles"), ".bible"),
1455+
("GitHub Commentaries", "GitHubCommentary", GitHubRepoInfo.commentaries[0], (config.marvelData, "commentaries"), ".commentary"),
1456+
("GitHub Books", "GitHubBook", GitHubRepoInfo.books[0], (config.marvelData, "books"), ".book"),
1457+
("GitHub Maps", "GitHubMap", GitHubRepoInfo.maps[0], (config.marvelData, "books"), ".book"),
1458+
("GitHub PDF", "GitHubPdf", GitHubRepoInfo.pdf[0], (config.marvelData, "pdf"), ".pdf"),
1459+
("GitHub EPUB", "GitHubEpub", GitHubRepoInfo.epub[0], (config.marvelData, "epub"), ".epub"),
1460+
)
1461+
for collection, kind, repo, location, extension in resources:
1462+
content += "<h2>{0}</h2>".format(collection)
1463+
for file in GithubUtil(repo).getRepoData():
1464+
if os.path.isfile(os.path.join(*location, file)):
1465+
content += """[ {1} ] {0}<br>""".format(file.replace(extension, ""), config.thisTranslation["installed"])
1466+
else:
1467+
content += """[<ref>DOWNLOAD:::{1}:::{0}</ref> ]<br>""".format(file.replace(extension, ""), kind)
14531468
content += "<h2>Third-party Resources</h2><p>Read <ref>https://github.com/eliranwong/UniqueBible/wiki/Third-party-resources</ref> about third-party resources.</a></p>"
14541469
self.html = content
14551470
self.plainText = TextUtil.htmlToPlainText(content).strip()
@@ -1701,8 +1716,8 @@ def printMultilineNote(self):
17011716

17021717
def getclipboardtext(self, confirmMessage=True):
17031718
try:
1704-
if config.terminalEnableTermuxAPI:
1705-
clipboardText = self.getCliOutput("termux-clipboard-get")
1719+
if shutil.which("termux-clipboard-get"):
1720+
clipboardText = subprocess.run("termux-clipboard-get", shell=True, capture_output=True, text=True).stdout
17061721
elif ("Pyperclip" in config.enabled):
17071722
import pyperclip
17081723
clipboardText = pyperclip.paste()
@@ -1798,8 +1813,11 @@ def share(self, command=""):
17981813
pydoc.pipepager(plainText, cmd="termux-share -a send")
17991814
return ""
18001815
else:
1801-
import pyperclip
1802-
pyperclip.copy(weblink)
1816+
if shutil.which("termux-clipboard-set"):
1817+
pydoc.pipepager(weblink, cmd="termux-clipboard-set")
1818+
else:
1819+
import pyperclip
1820+
pyperclip.copy(weblink)
18031821
self.print(f"The following link is copied to clipboard:\n")
18041822
self.print(weblink)
18051823
self.print("\nOpen it in a web browser or share with others.")
@@ -1814,8 +1832,11 @@ def copy(self, content="", confirmMessage=True):
18141832
if config.terminalEnableTermuxAPI:
18151833
pydoc.pipepager(content, cmd="termux-clipboard-set")
18161834
else:
1817-
import pyperclip
1818-
pyperclip.copy(content)
1835+
if shutil.which("termux-clipboard-set"):
1836+
pydoc.pipepager(weblink, cmd="termux-clipboard-set")
1837+
else:
1838+
import pyperclip
1839+
pyperclip.copy(content)
18191840
if confirmMessage:
18201841
self.print("Content is copied to clipboard.")
18211842
return ""
@@ -1829,8 +1850,11 @@ def copyHtml(self, content="", confirmMessage=True):
18291850
if config.terminalEnableTermuxAPI:
18301851
pydoc.pipepager(content, cmd="termux-clipboard-set")
18311852
else:
1832-
import pyperclip
1833-
pyperclip.copy(content)
1853+
if shutil.which("termux-clipboard-set"):
1854+
pydoc.pipepager(weblink, cmd="termux-clipboard-set")
1855+
else:
1856+
import pyperclip
1857+
pyperclip.copy(content)
18341858
if confirmMessage:
18351859
self.print("HTML content is copied to clipboard.")
18361860
return ""

0 commit comments

Comments
 (0)