Compare commits

...

4 Commits

  1. 4
      chatbug/__main__.py
  2. 4
      chatbug/file_append.py
  3. 4
      chatbug/llama.py
  4. 6
      chatbug/tool_functions.py
  5. 0
      chatbug/ui/__init__.py
  6. 20
      chatbug/ui/__main__.py
  7. 3771
      chatbug/ui/bottle.py
  8. 50
      chatbug/ui/bottle_svr.py
  9. 47
      chatbug/ui/file_watchdog.py
  10. 10
      chatbug/ui/server.py
  11. 29
      chatbug/ui/serverwait.py
  12. 30
      chatbug/ui/ui.py
  13. 16
      setup.py
  14. 61
      web/index.html
  15. 25
      web/main.js
  16. 117
      web/stylesheet.css
  17. 67
      web/watchdog.js

4
chatbug/__main__.py

@ -1,7 +1,7 @@
print("running __main__.-py") print("running __main__.-py")
from chatbug.llama import main from chatbug.llama import main_func
if __name__ == "__main__": if __name__ == "__main__":
main() main_func()

4
chatbug/file_append.py

@ -10,10 +10,12 @@ def check_append_file(prompt: str) -> str:
filename = part[1:] filename = part[1:]
try: try:
if os.path.exists(filename): if os.path.exists(filename):
with open(filename, "r") as f: with open(filename, "r", encoding="utf-8") as f:
content.append("%s:'''\n%s'''" % (filename, f.read())) content.append("%s:'''\n%s'''" % (filename, f.read()))
except FileNotFoundError: except FileNotFoundError:
print(f"File '{filename}' not found.") print(f"File '{filename}' not found.")
except Exception as e:
print("exception encountered %s", e)
content.append(prompt) content.append(prompt)
return "\n".join(content) return "\n".join(content)
return prompt return prompt

4
chatbug/llama.py

@ -36,11 +36,11 @@ def initialize_config(inference: Inference) -> Terminal:
return terminal return terminal
def main(): def main_func():
inference = Inference(model_selection.get_model()) inference = Inference(model_selection.get_model())
terminal = initialize_config(inference) terminal = initialize_config(inference)
terminal.join() terminal.join()
if __name__ == "__main__": if __name__ == "__main__":
main() main_func()

6
chatbug/tool_functions.py

@ -2,8 +2,6 @@ import random
import datetime import datetime
from chatbug.tool_helper import tool from chatbug.tool_helper import tool
import chatbug.matheval as matheval import chatbug.matheval as matheval
# from chatbug.matheval import interpreter, lexer
# from chatbug.matheval.ast import Parser
import chatbug.utils as utils import chatbug.utils as utils
@ -58,10 +56,10 @@ Args:
expression = "solve " + " and ".join(equations) + " for " + " and ".join(variables) expression = "solve " + " and ".join(equations) + " for " + " and ".join(variables)
print(expression) print(expression)
tokens = lexer.tokenize(expression) tokens = matheval.lexer.tokenize(expression)
parser = ast.Parser() parser = ast.Parser()
ast = parser.parse(tokens) ast = parser.parse(tokens)
return interpreter.interpret(ast) return matheval.interpreter.interpret(ast)
except Exception as e: except Exception as e:
utils.print_error("Tool call evaluation failed. - " + str(e)) utils.print_error("Tool call evaluation failed. - " + str(e))
return "Tool call evaluation failed." return "Tool call evaluation failed."

0
chatbug/ui/__init__.py

20
chatbug/ui/__main__.py

@ -0,0 +1,20 @@
from .server import start_server
from .serverwait import wait_for_server
from .ui import start_ui, _start_sandboxed
def start_ui():
svr = start_server(start_thread=False)
url = f"http://localhost:{svr.port}"
# wait_for_server(url)
# # start_ui(threaded=False)
# import webview
# w = webview.create_window('asdf', '../../web/index.html', min_size=(1200, 900), zoomable=True)
# webview.start(ssl=True)
if __name__ == "__main__":
start_ui()

3771
chatbug/ui/bottle.py

File diff suppressed because it is too large

50
chatbug/ui/bottle_svr.py

@ -0,0 +1,50 @@
#tornado needs this or it does not run
import asyncio
try:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
except AttributeError:
print("Probably running on linux")
from bottle import route, run, response, static_file, request, post
from .file_watchdog import FileWatchdog
class BottleServer:
def __init__(self, listen="0.0.0.0", port=8080, start_thread=True, root="web"):
self.root = root
self.port = port
self.listen = listen
self.wdt = FileWatchdog(self.root)
if start_thread:
import threading
self.thread = threading.Thread(target=self._run, args=())
self.thread.name = "BottleServerThread"
self.thread.daemon = True
self.thread.start()
else:
self._run()
def _home(self):
return static_file("index.html", root= self.root)
def _watchdog(self):
return str(self.wdt.time)
def _files(self, name):
if name.endswith(".vue"):
return static_file(name, root= self.root, mimetype="text/html")
return static_file(name, root= self.root)
def _run(self):
route('/')(self._home)
route('/watchdog')(self._watchdog)
route('/<name:path>')(self._files)
print(f"Starting server at {self.listen}:{self.port}")
run(host=self.listen, port=self.port, debug=False, threaded=True, quiet=True)

47
chatbug/ui/file_watchdog.py

@ -0,0 +1,47 @@
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def __init__(self, function):
self.function = function
def on_any_event(self, _event):
# Handle the event (e.g., file created, modified, deleted)
self.function()
class FileWatchdog:
def __init__(self, path):
self.path = path
self.time = 0
event_handler = MyHandler(lambda: self.event_handler())
self.observer = Observer()
self.observer.schedule(event_handler, path, recursive=True)
self.observer.start()
def event_handler(self):
#print("change detected")
self.time = time.time()
def stop(self):
self.observer.stop()
if __name__ == "__main__":
wdt = FileWatchdog("./web")
try:
while True:
time.sleep(1)
print(wdt.time)
except KeyboardInterrupt:
wdt.stop()

10
chatbug/ui/server.py

@ -0,0 +1,10 @@
from .bottle_svr import BottleServer
def start_server(start_thread=False):
print("server start")
return BottleServer(start_thread=start_thread, root="web")
if __name__ == "__main__":
start_server()

29
chatbug/ui/serverwait.py

@ -0,0 +1,29 @@
import time
import requests
import socket
def wait_for_server(url, timeout=10, retry_interval=0.5):
"""
Waits for a web server to become available by polling its URL.
"""
start_time = time.monotonic()
while time.monotonic() - start_time < timeout:
try:
# First, try a simple TCP connection to check if the port is open
hostname, port = url.split("//")[1].split(":")
port = int(port)
with socket.create_connection((hostname, port), timeout=retry_interval):
pass # If the connection succeeds, continue to the HTTP check
# Then, make an HTTP request to ensure the server is responding correctly
response = requests.get(url, timeout=retry_interval)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
return # Server is up and responding correctly
except (requests.exceptions.RequestException, socket.error) as e:
print(f"Server not yet available: {e}. Retrying in {retry_interval} seconds...")
time.sleep(retry_interval)
raise TimeoutError(f"Server at {url} did not become available within {timeout} seconds.")

30
chatbug/ui/ui.py

@ -0,0 +1,30 @@
import webview
from threading import Thread
def start_ui(threaded=False):
if threaded:
_start_threaded()
else:
_start_normal()
def _start_threaded():
t = Thread(target=start_ui, args=[False])
t.run()
def _start_normal():
webview.create_window('Geargenerator', 'http://localhost:8080', min_size=(1200, 900), zoomable=True)
webview.start()
def _start_sandboxed():
webview.create_window('Geargenerator', 'web_v2/geargenerator.html', min_size=(1200, 900), zoomable=True)
webview.start(ssl=True)
if __name__ == "__main__":
_start_sandboxed()
# start_ui(threaded=False)

16
setup.py

@ -14,9 +14,15 @@ setup(
'pytest', 'pytest',
'pywebview', 'pywebview',
], ],
# entry_points={ entry_points={
# 'console_scripts': [ 'console_scripts': [
# 'chatbug=chatbug.app:main', 'chatbug=chatbug.llama:main_func',
# ], # a^ b^ c^ d^
# }, # a => the command line argument
# b => the package name
# c => the file name in the package (same as imports)
# d => the function to call
'chatbugui=chatbug.ui.__main__:start_ui',
],
},
) )

61
web/index.html

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en">
<head>
<!-- <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script> -->
<link rel="stylesheet" href="stylesheet.css">
<script src="alpine.min.js"></script>
<script src="main.js"></script>
<script src="watchdog.js"></script>
</head>
<body>
<div class="sidebar">
<h1>Chatbug 🪲</h1>
<div class="button">🐛 New Chat</div>
<div class="title">Today</div>
<div class="button">Building Web UI with Bottle & Alpine.js</div>
<div class="button">Coding in python</div>
<div class="title">Last Week</div>
<div class="title">Older</div>
</div>
<div class="mainarea">
<!-- <h1 x-data="{ message: 'I ❤️ Alpine' }" x-text="message"></h1> -->
<div class="message">
<div class="bubble">Hello world</div>
</div>
<div class="response">
<div class="">Hello! Nice to meet you. What's up?</div>
</div>
<div class="message">
<div class="bubble">ah, just holding an example conversation with you</div>
</div>
<div class="response">
<div class="">Got it! Fun stuff. What kind of projects are you working on these days?</div>
</div>
<div class="message">
<div class="bubble">LLM chatbot named chatbug 🪲</div>
</div>
<div class="response">
<div class="">Cool name! Chatbug sounds like a friendly one. How's it going?</div>
</div>
<div class="message">
<div class="bubble">making a web ui with bottle and alpinejs</div>
</div>
<div class="input">
<!-- toolbutton for tool submenu, normally hidden unless pressed -->
<div class="button">+</div>
<div class="tool list" style="display:none">
<div class="tool button">attach file</div>
<div class="tool button">regenerate</div>
<div class="tool button">undo</div>
</div>
<input type="text">
<!-- send -->
<div class="button"></div>
</div>
</div>
</body>
</html>

25
web/main.js

@ -0,0 +1,25 @@
// import {createApp, ref, reactive} from 'vue';
// const app = createApp({
// data() {
// let msg = ref("hello world")
// try {
// msg.value = "" + pywebview.api
// } catch (e) {
// msg.value = "did not invoke " + e
// }
// window.msg = msg
// return {
// message: msg
// };
// }
// });
// app.mount('#app');

117
web/stylesheet.css

@ -0,0 +1,117 @@
body {
background-color: black;
color: white;
font-family: Arial, Helvetica, sans-serif;
margin: 0px;
height: 100%;
}
.sidebar {
width: 250px;
background-color: #2a262a;
float: left;
height: 100%;
position: absolute;
}
.sidebar h1 {
margin: 20px;
}
.sidebar .title {
font-size: 8pt;
margin: 20px;
margin-top: 30px;
margin-bottom: 10px;
}
.sidebar .button {
margin-left: 10px;
margin-right: 10px;
padding: 10px;
border-radius: 10px;
}
.sidebar .button:hover {
background-color: #423a42;
}
.mainarea {
margin-left: 260px;
height: 100%;
position: absolute;
right: 0;
left: 0;
}
.message {
display: flex;
margin-left: 40px;
margin-right: 10px;
}
.bubble {
padding: 10px;
border-radius: 10px;
background-color: #416146;
margin-left: auto;
float: right;
position: relative;
}
.response {
display: flex;
margin: 30px;
position: relative;
}
.response::before {
content: '🪲';
position: absolute;
top: -4px;
left: -30px;
}
.input {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
background-color: #2a262a;
border-radius: 10px;
width: 70%;
margin: auto;
position: absolute;
bottom: 40px;
}
.tool.list {
display: none;
background-color: #fff;
border: 1px solid #ccc;
position: absolute;
top: 100%;
left: 0;
z-index: 1;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
.tool.button {
cursor: pointer;
padding: 5px 10px;
margin: 5px;
}
.input input {
flex-grow: 1;
padding: 10px;
border: 0px solid #ccc;
background: none;
color: white;
}
.input input:focus {
outline: 0px solid black; /* Custom focus outline */
}

67
web/watchdog.js

@ -0,0 +1,67 @@
wdt = {
last_wdt_time: 0,
watchdog_counter: 0
}
pollFileChange = () => {
setTimeout(() => {
wdt.watchdog_counter++
console.log(wdt.watchdog_counter)
if (wdt.watchdog_counter > 20) {
return
}
ajax({
type: "GET",
url: "/watchdog",
success: (data) => {
var time = Number(data)
if (wdt.last_wdt_time == 0) {
wdt.last_wdt_time = time
pollFileChange()
} else if (time > wdt.last_wdt_time) {
location.reload();
} else {
pollFileChange()
}
},
})
}, 10000)
}
function ajax(setting) {
if (typeof(shutdown) !== 'undefined') return
var request = new XMLHttpRequest();
request.open(setting.type, setting.url, true);
request.setRequestHeader('Content-Type', setting.dataType)
request.onload = function(data) {
if (typeof(shutdown) !== 'undefined') return
if (this.status >= 200 && this.status < 400) {
if (setting.success) {
setting.success(this.response)
}
} else {
if (setting.error) {
setting.error(this.response)
}
}
}
request.onerror = function(data) {
if (typeof(shutdown) !== 'undefined') return
if (setting.error) {
setting.error(data)
}
}
if (setting.data) {
request.send(setting.data)
} else {
request.send()
}
}
pollFileChange()
Loading…
Cancel
Save