Download scripts/chat_ui.py from gibihm/gotti-mirror: direct link, hf CLI and curl.
- Browser
- Download file 9.28 kB
-
https://huggingface.co/datasets/gibihm/gotti-mirror/resolve/main/scripts/chat_ui.py
- Command line
-
hf download hf://datasets/gibihm/gotti-mirror/scripts/chat_ui.py
-
curl -L -o chat_ui.py https://huggingface.co/datasets/gibihm/gotti-mirror/resolve/main/scripts/chat_ui.py
9.28 kB
| #!/usr/bin/env python3 | |
| """ | |
| Hermes Chat-UI (Deutsch, ChatGPT-Style) | |
| Lokales Web-UI mit Themen-Sidebar und Verlauf (localStorage). | |
| Backend ruft `hermes chat` auf - kein eigener LLM-Key nötig. | |
| Start: python3 chat_ui.py | |
| Stop: kill $(cat /tmp/hermes_chat_ui.pid) | |
| Nur localhost. | |
| """ | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| from urllib.parse import urlparse | |
| HOST = "127.0.0.1" | |
| PORT = 8799 | |
| HERMES_BIN = os.path.expanduser("~/.local/bin/hermes") | |
| # ---------------------------------------------------------------- Backend | |
| def hermes_chat(query, model=None, provider=None, timeout=180): | |
| """Ruft `hermes chat -q` auf und gibt die Antwort als Text zurück.""" | |
| cmd = [HERMES_BIN, "chat", "-q", query, "--cli"] | |
| if model: | |
| cmd += ["-m", model] | |
| if provider: | |
| cmd += ["--provider", provider] | |
| try: | |
| r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) | |
| out = (r.stdout or "").strip() | |
| if not out and r.stderr: | |
| out = (r.stderr or "").strip() | |
| return out or "(keine Antwort)" | |
| except subprocess.TimeoutExpired: | |
| return "⚠ Zeitüberschreitung (das dauerte länger als erwartet)." | |
| except FileNotFoundError: | |
| return f"⚠ hermes nicht gefunden unter {HERMES_BIN}" | |
| except Exception as e: | |
| return f"⚠ Fehler: {e}" | |
| # ---------------------------------------------------------------- Frontend | |
| PAGE = """<!doctype html> | |
| <html lang="de"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>Hermes Chat</title> | |
| <style> | |
| :root{--bg:#0d1117;--side:#0a0e14;--card:#161b22;--line:#30363d;--txt:#e6edf3; | |
| --mut:#8b949e;--blu:#58a6ff;--grn:#3fb950;--usr:#1f6feb;--ai:#21262d} | |
| *{box-sizing:border-box;margin:0;padding:0} | |
| body{height:100vh;display:flex;font:15px/1.55 ui-sans-serif,system-ui,Segoe UI,Roboto,sans-serif; | |
| background:var(--bg);color:var(--txt)} | |
| /* Sidebar */ | |
| .side{width:260px;background:var(--side);border-right:1px solid var(--line); | |
| display:flex;flex-direction:column} | |
| .side h1{font-size:15px;padding:16px;color:var(--mut);border-bottom:1px solid var(--line)} | |
| .newbtn{margin:12px;padding:10px;border:1px solid var(--line);border-radius:8px; | |
| background:var(--card);color:var(--txt);cursor:pointer;text-align:center} | |
| .newbtn:hover{border-color:var(--blu)} | |
| .topics{flex:1;overflow-y:auto;padding:0 8px} | |
| .topic{padding:10px 12px;border-radius:8px;margin:4px 0;cursor:pointer; | |
| display:flex;justify-content:space-between;align-items:center;color:var(--mut)} | |
| .topic:hover{background:var(--card)} | |
| .topic.active{background:var(--card);color:var(--txt)} | |
| .topic .del{opacity:0;color:var(--mut);font-size:12px;padding:0 4px} | |
| .topic:hover .del{opacity:1} | |
| .topic .del:hover{color:var(--grn)} | |
| .foot{padding:12px;border-top:1px solid var(--line);color:var(--mut);font-size:12px} | |
| /* Main */ | |
| .main{flex:1;display:flex;flex-direction:column;min-width:0} | |
| .msgs{flex:1;overflow-y:auto;padding:24px} | |
| .wrap{max-width:760px;margin:0 auto} | |
| .msg{margin:14px 0;padding:12px 16px;border-radius:14px;white-space:pre-wrap;word-wrap:break-word} | |
| .msg.user{background:var(--usr);color:#fff;margin-left:60px;border-bottom-right-radius:4px} | |
| .msg.ai{background:var(--ai);border:1px solid var(--line);margin-right:60px;border-bottom-left-radius:4px} | |
| .msg .who{font-size:11px;color:var(--mut);margin-bottom:4px} | |
| .typing{color:var(--mut);font-style:italic} | |
| /* Input */ | |
| .bar{padding:16px;border-top:1px solid var(--line)} | |
| .bar .box{max-width:760px;margin:0 auto;display:flex;gap:10px} | |
| textarea{flex:1;resize:none;height:52px;padding:12px;border-radius:12px; | |
| background:var(--card);border:1px solid var(--line);color:var(--txt); | |
| font:inherit;outline:none} | |
| textarea:focus{border-color:var(--blu)} | |
| .send{padding:0 22px;border:none;border-radius:12px;background:var(--blu);color:#000; | |
| font-weight:600;cursor:pointer} | |
| .send:disabled{opacity:.5;cursor:default} | |
| code{background:#0a0e14;padding:1px 5px;border-radius:4px;font-size:13px} | |
| pre{background:#0a0e14;padding:12px;border-radius:8px;overflow:auto;margin:8px 0} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="side"> | |
| <h1>⚡ Hermes Chat</h1> | |
| <div class="newbtn" onclick="neu()">+ Neues Thema</div> | |
| <div class="topics" id="topics"></div> | |
| <div class="foot" id="foot">lokal · localhost</div> | |
| </div> | |
| <div class="main"> | |
| <div class="msgs" id="msgs"><div class="wrap" id="wrap"></div></div> | |
| <div class="bar"> | |
| <div class="box"> | |
| <textarea id="in" placeholder="Nachricht an Hermes… (Enter = senden, Shift+Enter = neue Zeile)"></textarea> | |
| <button class="send" id="send" onclick="send()">Senden</button> | |
| </div> | |
| </div> | |
| </div> | |
| <script> | |
| const LS="hermes_chat_topics_v1"; | |
| let state=JSON.parse(localStorage.getItem(LS)||"{}"); | |
| if(!state.topics) state.topics=[]; | |
| if(!state.active) state.active=null; | |
| function save(){localStorage.setItem(LS,JSON.stringify(state));render();} | |
| function uid(){return Date.now().toString(36)+Math.random().toString(36).slice(2,6);} | |
| function neu(){ | |
| const t={id:uid(),name:"Neues Thema "+(state.topics.length+1),msgs:[]}; | |
| state.topics.unshift(t);state.active=t.id;save(); | |
| } | |
| function del(id){ | |
| state.topics=state.topics.filter(t=>t.id!==id); | |
| if(state.active===id) state.active=state.topics[0]?.id||null; | |
| save(); | |
| } | |
| function active(){return state.topics.find(t=>t.id===state.active);} | |
| function render(){ | |
| const tb=document.getElementById("topics"); | |
| tb.innerHTML=state.topics.map(t=> | |
| `<div class="topic ${t.id===state.active?'active':''}" onclick="sel('${t.id}')"> | |
| <span>${esc(t.name)}</span> | |
| <span class="del" onclick="event.stopPropagation();del('${t.id}')">löschen</span> | |
| </div>`).join("") || '<div class="topic">keine Themen</div>'; | |
| const a=active(); | |
| const w=document.getElementById("wrap"); | |
| if(!a){w.innerHTML='<div class="typing">Links ein neues Thema erstellen, um loszulegen.</div>';return;} | |
| w.innerHTML=a.msgs.map(m=> | |
| `<div class="msg ${m.role}"><div class="who">${m.role==='user'?'Du':'Hermes'}</div>${esc(m.text)}</div>` | |
| ).join(""); | |
| const m=document.getElementById("msgs");m.scrollTop=m.scrollHeight; | |
| } | |
| function sel(id){state.active=id;save();} | |
| function esc(s){return s.replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]));} | |
| async function send(){ | |
| const a=active();if(!a){neu();return;} | |
| const ta=document.getElementById("in");const txt=ta.value.trim(); | |
| if(!txt)return; | |
| a.msgs.push({role:"user",text:txt});ta.value=""; | |
| a.msgs.push({role:"ai",text:"⏳ denkt nach…"});save(); | |
| const btn=document.getElementById("send");btn.disabled=true; | |
| try{ | |
| const r=await fetch("/api/chat",{method:"POST",headers:{"Content-Type":"application/json"}, | |
| body:JSON.stringify({query:txt})}); | |
| const d=await r.json(); | |
| a.msgs[a.msgs.length-1].text=d.reply||"(keine Antwort)"; | |
| }catch(e){ | |
| a.msgs[a.msgs.length-1].text="⚠ Verbindung fehlgeschlagen: "+e; | |
| } | |
| btn.disabled=false;save(); | |
| } | |
| document.getElementById("in").addEventListener("keydown",e=>{ | |
| if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send();} | |
| }); | |
| render(); | |
| </script> | |
| </body></html>""" | |
| # ---------------------------------------------------------------- HTTP | |
| class Handler(BaseHTTPRequestHandler): | |
| def _send(self, code, body, ctype="application/json"): | |
| if isinstance(body, dict) or isinstance(body, list): | |
| body = json.dumps(body, ensure_ascii=False) | |
| if not isinstance(body, bytes): | |
| body = body.encode("utf-8") | |
| self.send_response(code) | |
| self.send_header("Content-Type", ctype + "; charset=utf-8") | |
| self.send_header("Content-Length", str(len(body))) | |
| self.end_headers() | |
| self.wfile.write(body) | |
| def do_GET(self): | |
| if urlparse(self.path).path in ("/", "/index.html"): | |
| self._send(200, PAGE, "text/html") | |
| else: | |
| self._send(404, {"fehler": "nicht gefunden"}) | |
| def do_POST(self): | |
| if urlparse(self.path).path == "/api/chat": | |
| try: | |
| n = int(self.headers.get("Content-Length", 0)) | |
| data = json.loads(self.rfile.read(n) or b"{}") | |
| except Exception: | |
| data = {} | |
| query = (data.get("query") or "").strip() | |
| if not query: | |
| self._send(400, {"reply": "⚠ leere Nachricht"}) | |
| return | |
| reply = hermes_chat(query, | |
| model=data.get("model"), | |
| provider=data.get("provider")) | |
| self._send(200, {"reply": reply}) | |
| else: | |
| self._send(404, {"fehler": "nicht gefunden"}) | |
| def log_message(self, *a): | |
| pass | |
| def main(): | |
| srv = ThreadingHTTPServer((HOST, PORT), Handler) | |
| with open("/tmp/hermes_chat_ui.pid", "w") as f: | |
| f.write(str(os.getpid())) | |
| print(f"Hermes Chat-UI läuft → http://{HOST}:{PORT}") | |
| print("Beenden mit Strg+C") | |
| try: | |
| srv.serve_forever() | |
| except KeyboardInterrupt: | |
| print("\nServer gestoppt.") | |
| finally: | |
| srv.server_close() | |
| if __name__ == "__main__": | |
| main() | |