uniquechat 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
uniquechat/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """Local chat with Hugging Face models."""
2
+ import argparse
3
+
4
+
5
+ def launch(model=None, *, offline=False, inbrowser=True):
6
+ """Open the picker, or load a selected Hugging Face chat model."""
7
+ from .server import serve
8
+ return serve(model, offline=offline, inbrowser=inbrowser)
9
+
10
+
11
+ def main():
12
+ parser = argparse.ArgumentParser(description=__doc__)
13
+ parser.add_argument("model", nargs="?", help="Hugging Face repository ID")
14
+ parser.add_argument("--offline", action="store_true", help="Use cached files only")
15
+ args = parser.parse_args()
16
+ launch(args.model, offline=args.offline)
uniquechat/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ main()
uniquechat/engine.py ADDED
@@ -0,0 +1,80 @@
1
+ """Model loading and local inference. No remote inference clients."""
2
+ from pathlib import Path
3
+
4
+ TEXT = "HuggingFaceTB/SmolLM2-135M-Instruct"
5
+ VISION = "HuggingFaceTB/SmolVLM-256M-Instruct"
6
+ TEXT_EXT = {".txt", ".md", ".csv", ".json"}
7
+ IMAGE_EXT = {".png", ".jpg", ".jpeg", ".webp"}
8
+
9
+
10
+ def read_turn(prompt, files, vision):
11
+ parts = []
12
+ if len(files) > 3:
13
+ raise ValueError("Attach at most three files per message.")
14
+ for filename in files:
15
+ path = Path(filename)
16
+ ext = path.suffix.lower()
17
+ if ext in TEXT_EXT:
18
+ if path.stat().st_size > 32_768:
19
+ raise ValueError("Text attachments must be 32 KiB or smaller.")
20
+ body = path.read_text(encoding="utf-8-sig")
21
+ parts.append({"type": "text", "text": f"File: {path.name}\n{body}"})
22
+ elif vision and ext in IMAGE_EXT:
23
+ from PIL import Image
24
+ if path.stat().st_size > 8 * 1024**2:
25
+ raise ValueError("Images must be 8 MiB or smaller.")
26
+ with Image.open(path) as img:
27
+ if img.width * img.height > 16_000_000:
28
+ raise ValueError("Choose an image under 16 megapixels.")
29
+ parts.append({"type": "image", "image": img.convert("RGB")})
30
+ else:
31
+ raise ValueError(f"This model does not accept {ext or 'this file type'}.")
32
+ if prompt.strip():
33
+ parts.append({"type": "text", "text": prompt.strip()})
34
+ if not parts:
35
+ raise ValueError("Enter a message or attach a file.")
36
+ return {"role": "user", "content": parts}
37
+
38
+
39
+ class Engine:
40
+ def __init__(self, repo, cached):
41
+ import torch
42
+ from huggingface_hub.utils import validate_repo_id
43
+ from transformers import (AutoConfig, AutoModelForCausalLM,
44
+ AutoModelForImageTextToText, AutoProcessor, AutoTokenizer)
45
+ validate_repo_id(repo)
46
+ if Path(repo).exists():
47
+ raise ValueError("Enter a Hugging Face repository ID.")
48
+ options = dict(local_files_only=cached, trust_remote_code=False)
49
+ cfg = AutoConfig.from_pretrained(repo, **options)
50
+ self.vision = cfg.model_type in {"smolvlm", "idefics3"}
51
+ processor = AutoProcessor if self.vision else AutoTokenizer
52
+ self.processor = processor.from_pretrained(repo, **options)
53
+ if not getattr(self.processor, "chat_template", None):
54
+ raise ValueError("Choose an instruction model with a built-in chat template.")
55
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
56
+ loader = AutoModelForImageTextToText if self.vision else AutoModelForCausalLM
57
+ dtype = torch.float16 if self.device == "cuda" else torch.float32
58
+ self.model = loader.from_pretrained(repo, use_safetensors=True, torch_dtype=dtype,
59
+ **options).to(self.device).eval()
60
+ text_cfg = getattr(cfg, "text_config", cfg)
61
+ self.limit = getattr(text_cfg, "max_position_embeddings", 4096)
62
+
63
+ def reply(self, messages):
64
+ import torch
65
+ if self.vision:
66
+ inputs = self.processor.apply_chat_template(messages, tokenize=True,
67
+ add_generation_prompt=True, return_dict=True, return_tensors="pt")
68
+ else:
69
+ plain = [{"role": m["role"], "content": "\n".join(p["text"] for p in m["content"])}
70
+ for m in messages]
71
+ inputs = self.processor.apply_chat_template(plain, tokenize=True,
72
+ add_generation_prompt=True, return_dict=True, return_tensors="pt")
73
+ inputs = inputs.to(self.device)
74
+ length = inputs["input_ids"].shape[1]
75
+ budget = min(192, self.limit - length)
76
+ if budget < 1:
77
+ raise ValueError("The conversation exceeds this model's context. Clear chat or shorten the file.")
78
+ with torch.inference_mode():
79
+ output = self.model.generate(**inputs, max_new_tokens=budget, do_sample=False)
80
+ return self.processor.batch_decode(output[:, length:], skip_special_tokens=True)[0].strip()
uniquechat/server.py ADDED
@@ -0,0 +1,161 @@
1
+ """A loopback-only server for the bundled uniquechat interface."""
2
+ import base64
3
+ import json
4
+ import secrets
5
+ import tempfile
6
+ import threading
7
+ import webbrowser
8
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
9
+ from importlib.resources import files
10
+ from pathlib import Path
11
+
12
+ from .engine import Engine, TEXT, VISION, read_turn
13
+
14
+ MAX_BODY = 36 * 1024**2
15
+ ASSETS = {"/": ("index.html", "text/html"), "/app.js": ("app.js", "text/javascript"),
16
+ "/app.css": ("app.css", "text/css")}
17
+
18
+
19
+ def user_message(item, folder, vision):
20
+ prompt = item["text"]
21
+ attachments = item.get("files", [])
22
+ if not isinstance(prompt, str) or len(prompt) > 64000 or len(attachments) > 3:
23
+ raise ValueError("Shorten your message or choose at most three files.")
24
+ paths = []
25
+ for i, attachment in enumerate(attachments):
26
+ name = attachment["name"]
27
+ if not name or Path(name).name != name or name in {".", ".."} or "\\" in name:
28
+ raise ValueError("Invalid filename.")
29
+ directory = Path(folder) / str(i)
30
+ directory.mkdir()
31
+ path = directory / name
32
+ path.write_bytes(base64.b64decode(attachment["data"], validate=True))
33
+ paths.append(path)
34
+ return read_turn(prompt, paths, vision)
35
+
36
+
37
+ class Session:
38
+ def __init__(self, initial, offline):
39
+ self.initial = initial
40
+ self.offline = offline
41
+ self.lock = threading.Lock()
42
+ self.engine = None
43
+ self.state = dict(phase="idle", model="", message="", vision=False)
44
+ self.token = secrets.token_urlsafe(32)
45
+
46
+ def load(self, repo):
47
+ if not isinstance(repo, str) or not repo.strip() or len(repo) > 160:
48
+ raise ValueError("Enter a Hugging Face model ID.")
49
+ if not self.lock.acquire(blocking=False):
50
+ raise ValueError("Another operation is running.")
51
+ self.state = dict(phase="loading", model=repo, message="Checking local files…", vision=False)
52
+ threading.Thread(target=self._load, args=(repo,), daemon=True).start()
53
+
54
+ def _load(self, repo):
55
+ try:
56
+ self.engine = None
57
+ try:
58
+ engine = Engine(repo, cached=True)
59
+ except OSError:
60
+ if self.offline:
61
+ raise ValueError("Model files are missing. Load the model once while online.") from None
62
+ self.state = {**self.state, "message": "Downloading model files and loading weights…"}
63
+ engine = Engine(repo, cached=False)
64
+ self.engine = engine
65
+ self.state = dict(phase="ready", model=repo, message="Running locally", vision=engine.vision)
66
+ except Exception as exc:
67
+ self.state = dict(phase="error", model=repo, message=str(exc), vision=False)
68
+ finally:
69
+ self.lock.release()
70
+
71
+ def reply(self, data):
72
+ if not self.lock.acquire(blocking=False):
73
+ raise ValueError("A model operation is already running.")
74
+ try:
75
+ if self.engine is None or data.get("model") != self.state["model"]:
76
+ raise ValueError("Load the conversation's model first.")
77
+ turns = data["turns"]
78
+ if not isinstance(turns, list) or not 0 < len(turns) <= 101 or len(turns) % 2 != 1:
79
+ raise ValueError("Start a new chat or send a user message.")
80
+ messages = []
81
+ for i, turn in enumerate(turns):
82
+ if i % 2:
83
+ if turn["role"] != "assistant" or not isinstance(turn["text"], str):
84
+ raise ValueError("Invalid conversation.")
85
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": turn["text"]}]})
86
+ else:
87
+ if turn["role"] != "user":
88
+ raise ValueError("Invalid conversation.")
89
+ with tempfile.TemporaryDirectory() as folder:
90
+ messages.append(user_message(turn, folder, self.engine.vision))
91
+ return self.engine.reply(messages)
92
+ finally:
93
+ self.lock.release()
94
+
95
+
96
+ def handler(session):
97
+ class Handler(BaseHTTPRequestHandler):
98
+ def log_message(self, *args):
99
+ pass
100
+
101
+ def send_body(self, code, body, mime):
102
+ self.send_response(code)
103
+ self.send_header("Content-Type", mime)
104
+ self.send_header("Content-Length", str(len(body)))
105
+ self.send_header("Cache-Control", "no-store")
106
+ self.send_header("X-Content-Type-Options", "nosniff")
107
+ self.send_header("Content-Security-Policy",
108
+ "default-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'")
109
+ self.end_headers()
110
+ self.wfile.write(body)
111
+
112
+ def send_json(self, code, value):
113
+ self.send_body(code, json.dumps(value).encode(), "application/json")
114
+
115
+ def local_host(self):
116
+ return self.headers.get("Host") == f"127.0.0.1:{self.server.server_port}"
117
+
118
+ def do_GET(self):
119
+ if not self.local_host():
120
+ return self.send_error(403)
121
+ if self.path == "/api/config":
122
+ return self.send_json(200, dict(initial=session.initial, offline=session.offline,
123
+ token=session.token, models=[TEXT, VISION]))
124
+ if self.path == "/api/status":
125
+ return self.send_json(200, session.state)
126
+ if self.path not in ASSETS:
127
+ return self.send_error(404)
128
+ filename, mime = ASSETS[self.path]
129
+ self.send_body(200, files("uniquechat").joinpath("static", filename).read_bytes(), mime)
130
+
131
+ def do_POST(self):
132
+ if not self.local_host() or self.headers.get("X-Uniquechat") != session.token:
133
+ return self.send_error(403)
134
+ try:
135
+ size = int(self.headers.get("Content-Length", "0"))
136
+ if not 0 < size <= MAX_BODY:
137
+ return self.send_json(413, {"error": "Conversation too large. Start a new chat."})
138
+ data = json.loads(self.rfile.read(size))
139
+ if self.path == "/api/load":
140
+ session.load(data["model"])
141
+ return self.send_json(202, {"accepted": True})
142
+ if self.path == "/api/chat":
143
+ return self.send_json(200, {"text": session.reply(data)})
144
+ return self.send_error(404)
145
+ except Exception as exc:
146
+ self.send_json(400, {"error": str(exc)})
147
+ return Handler
148
+
149
+
150
+ def serve(initial=None, *, offline=False, inbrowser=True, bind="127.0.0.1"):
151
+ session = Session(initial, offline)
152
+ # A stable origin lets the browser reopen its locally saved conversations.
153
+ with ThreadingHTTPServer((bind, 7860), handler(session)) as http:
154
+ url = "http://127.0.0.1:7860"
155
+ print(f"uniquechat is running at {url}. Press Ctrl+C to stop.", flush=True)
156
+ if inbrowser:
157
+ webbrowser.open(url)
158
+ try:
159
+ http.serve_forever()
160
+ except KeyboardInterrupt:
161
+ pass
@@ -0,0 +1 @@
1
+ :root{font:16px/1.45 "Segoe UI",system-ui,sans-serif;color:#1d2825;background:#fff}*{box-sizing:border-box}body{margin:0;display:flex;height:100dvh}button,input,textarea{font:inherit}button{cursor:pointer;color:inherit;border:1px solid #d5ded9;border-radius:10px;background:#fff;padding:8px 14px}button:hover{background:#eaf2ee}button:disabled{cursor:wait;opacity:.55}aside{width:244px;flex:none;background:#f4f6f3;padding:24px 16px;display:flex;flex-direction:column;gap:18px;border-right:1px solid #dfe5df}.brand{font-size:22px;letter-spacing:-1px}.brand i,.mark{background:#185f4b;color:#fff;border-radius:11px;font-style:normal;padding:2px 9px}.mark{font-size:32px;width:48px;height:48px;margin:auto;font-weight:700}h3,label{font-size:13px;color:#52615b}h3{margin:12px 0 0}nav{flex:1;overflow:auto}nav button{display:block;text-align:left;border:0;background:transparent;width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}nav button.current{background:#dcebe2}small,#types,#details,p{color:#596960}main{flex:1;min-width:0;display:flex;flex-direction:column;position:relative}header{padding:14px 20px;border-bottom:1px solid #e6eae6;display:flex;align-items:center;gap:12px}.device{margin-left:auto;color:#24674e;font-size:13px}#menu{padding:4px 9px}.center{width:min(480px,90%);margin:auto;text-align:center}h1{font-size:clamp(28px,4vw,41px);letter-spacing:-1.8px;margin:18px 0 4px}p{margin-top:6px}#pick{text-align:left;border:1px solid #d9e3dc;border-radius:18px;padding:22px;margin-top:26px}label{display:block;font-weight:600}#model{margin:8px 0;width:100%;padding:10px;border:1px solid #b5c5bb;border-radius:7px}#details{font-size:14px;margin:0 0 18px}.primary{background:#185f4b;color:white;border:0}.primary:hover{background:#114936}#conversation{flex:1;min-height:0;width:min(780px,95%);margin:auto;display:flex;flex-direction:column}#messages{flex:1;overflow:auto;padding:26px 8px}.bubble{white-space:pre-wrap;overflow-wrap:anywhere;padding:12px 16px;margin:8px 0 22px;max-width:92%}.user{background:#eef2ef;border-radius:18px;width:fit-content;margin-left:auto}.assistant{border-left:3px solid #8bb59c}.empty{text-align:center;margin-top:15vh;color:#51685c}#compose{border:1px solid #bdcec2;border-radius:20px;padding:12px 14px;margin:12px 0 22px;box-shadow:0 4px 18px #1829200b}textarea{width:100%;resize:vertical;min-height:52px;border:0;padding:6px;outline-offset:-1px}.tools{display:flex;align-items:center;gap:10px}.tools button{border-radius:100px;padding:2px 0;width:36px;height:36px;font-size:22px}#send{margin-left:auto}#types{font-size:12px}#notice{color:#803f25;text-align:center;padding:0 10px;overflow-wrap:anywhere}#notice:not(:empty){padding:10px}#chips button{font-size:12px;margin:3px}.spinner{border:3px solid #dceae1;border-top-color:#185f4b;border-radius:50%;width:40px;height:40px;margin:auto;animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}[hidden]{display:none!important}@media(max-width:700px){aside{position:absolute;height:100%;z-index:2;box-shadow:8px 0 24px #0001}header{padding:12px}.device{font-size:11px}#types{max-width:65%}}
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ const el = id => document.getElementById(id);
3
+ const screens = ["picker", "loading", "conversation"];
4
+ let config, database, current, pending = [], busy = false;
5
+ const textTypes = ".txt,.md,.csv,.json";
6
+ const imageTypes = ".png,.jpg,.jpeg,.webp";
7
+
8
+ function show(id) {
9
+ screens.forEach(name => el(name).hidden = name !== id);
10
+ }
11
+ function notice(message = "") { el("notice").textContent = message; }
12
+ function button(text, click) {
13
+ const b = document.createElement("button");
14
+ b.type = "button"; b.textContent = text; b.onclick = click;
15
+ return b;
16
+ }
17
+ async function api(path, body) {
18
+ const options = body ? {method: "POST", headers: {"Content-Type": "application/json",
19
+ "X-Uniquechat": config.token}, body: JSON.stringify(body)} : {};
20
+ const result = await fetch("/api/" + path, options);
21
+ const value = await result.json();
22
+ if (!result.ok) throw Error(value.error || "Request failed.");
23
+ return value;
24
+ }
25
+ function openHistory() {
26
+ return new Promise((resolve, reject) => {
27
+ const request = indexedDB.open("uniquechat-history", 1);
28
+ request.onupgradeneeded = () => request.result.createObjectStore("chats", {keyPath: "id"});
29
+ request.onsuccess = () => resolve(request.result);
30
+ request.onerror = () => reject(request.error);
31
+ });
32
+ }
33
+ function historyOp(write, chat) {
34
+ return new Promise((resolve, reject) => {
35
+ const tx = database.transaction("chats", write ? "readwrite" : "readonly");
36
+ const store = tx.objectStore("chats");
37
+ const request = write ? store.put(chat) : store.getAll();
38
+ tx.oncomplete = () => resolve(request.result);
39
+ tx.onabort = () => reject(tx.error || Error("Could not save history."));
40
+ tx.onerror = () => reject(tx.error);
41
+ });
42
+ }
43
+ async function sidebar() {
44
+ if (!database) return;
45
+ const chats = await historyOp(false);
46
+ el("history").replaceChildren();
47
+ for (const chat of chats.sort((a,b) => b.time-a.time)) {
48
+ const b = button(chat.title, () => { if (!busy) load(chat.model, chat); });
49
+ if (current && chat.id === current.id) b.className = "current";
50
+ el("history").append(b);
51
+ }
52
+ }
53
+ function render() {
54
+ const list = el("messages");
55
+ list.replaceChildren();
56
+ if (!current.turns.length) {
57
+ const title = document.createElement("h2");
58
+ title.className = "empty"; title.textContent = "How can I help?";
59
+ list.append(title);
60
+ }
61
+ for (const entry of current.turns) {
62
+ const bubble = document.createElement("div");
63
+ bubble.className = "bubble " + entry.role;
64
+ bubble.textContent = [entry.text, ...(entry.files || []).map(f => "📎 " + f.name)]
65
+ .filter(Boolean).join("\n");
66
+ list.append(bubble);
67
+ }
68
+ list.scrollTop = list.scrollHeight;
69
+ }
70
+ function updateDetails() {
71
+ const selected = el("model").value.trim();
72
+ el("details").textContent = selected === config.models[0] ? "Text and documents · about 270 MB"
73
+ : selected === config.models[1] ? "Text, documents and images · about 510 MB" : "Compatible Hugging Face chat model";
74
+ }
75
+ function chips() {
76
+ el("chips").replaceChildren(...pending.map((f,i) => button(f.name + " ×", () => {
77
+ if (!busy) { pending.splice(i, 1); chips(); }
78
+ })));
79
+ }
80
+ async function load(repo, previous) {
81
+ if (busy) return;
82
+ busy = true;
83
+ if (innerWidth <= 700) el("side").hidden = true;
84
+ notice(); show("loading"); el("phase").textContent = "Checking local files…";
85
+ try {
86
+ let state = await api("status");
87
+ if (state.model !== repo || state.phase !== "ready") {
88
+ await api("load", {model:repo});
89
+ do {
90
+ state = await api("status");
91
+ el("phase").textContent = state.message;
92
+ if (state.phase === "loading") await new Promise(resolve => setTimeout(resolve, 400));
93
+ } while (state.phase === "loading");
94
+ if (state.phase !== "ready" || state.model !== repo) throw Error(state.message);
95
+ }
96
+ current = previous || {id:crypto.randomUUID(), model:repo, turns:[], title:"New chat", time:Date.now()};
97
+ el("modelName").textContent = repo.split("/").pop();
98
+ el("file").accept = textTypes + (state.vision ? "," + imageTypes : "");
99
+ el("types").textContent = state.vision ? "Images and text files" : "Text files";
100
+ pending = []; chips(); el("prompt").value = "";
101
+ show("conversation"); render(); await sidebar(); el("prompt").focus();
102
+ } catch (err) { show("picker"); notice(err.message); }
103
+ finally { busy = false; }
104
+ }
105
+ function encodeFile(file) {
106
+ return new Promise((resolve, reject) => {
107
+ const reader = new FileReader();
108
+ reader.onload = () => resolve({name:file.name, data:reader.result.split(",")[1]});
109
+ reader.onerror = () => reject(Error("Could not read " + file.name));
110
+ reader.readAsDataURL(file);
111
+ });
112
+ }
113
+ el("pick").onsubmit = e => { e.preventDefault(); load(el("model").value.trim()); };
114
+ el("model").oninput = updateDetails;
115
+ el("new").onclick = () => {
116
+ if (busy) return;
117
+ current = null; pending = []; notice(); show("picker");
118
+ el("modelName").textContent = "Model picker"; sidebar();
119
+ if (innerWidth <= 700) el("side").hidden = true;
120
+ };
121
+ el("menu").onclick = () => el("side").hidden = !el("side").hidden;
122
+ el("plus").onclick = () => { if (!busy) el("file").click(); };
123
+ el("file").onchange = () => {
124
+ const list = [...el("file").files]; el("file").value = "";
125
+ if (pending.length + list.length > 3) return notice("Choose up to three files.");
126
+ for (const f of list) {
127
+ const ext = "." + f.name.split(".").pop().toLowerCase();
128
+ if (!el("file").accept.split(",").includes(ext)) return notice("Unsupported file type: " + f.name);
129
+ const limit = imageTypes.split(",").includes(ext) ? 8*1024*1024 : 32768;
130
+ if (f.size > limit) return notice("This file is too large: " + f.name);
131
+ }
132
+ pending.push(...list); notice(); chips();
133
+ };
134
+ el("prompt").onkeydown = e => {
135
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); el("compose").requestSubmit(); }
136
+ };
137
+ el("compose").onsubmit = async e => {
138
+ e.preventDefault();
139
+ const text = el("prompt").value.trim();
140
+ if (busy || (!text && !pending.length)) return;
141
+ busy = true; el("send").disabled = true; el("prompt").disabled = true;
142
+ const original = current.turns;
143
+ try {
144
+ const files = await Promise.all(pending.map(encodeFile));
145
+ current.turns = [...original, {role:"user", text, files}];
146
+ render(); notice("Generating locally…");
147
+ const response = await api("chat", {model:current.model, turns:current.turns});
148
+ current.turns.push({role:"assistant", text:response.text});
149
+ current.title = current.turns[0].text.slice(0,60) || current.turns[0].files[0].name;
150
+ current.time = Date.now(); pending = []; chips(); el("prompt").value = "";
151
+ render(); notice();
152
+ try {
153
+ if (!database) throw Error();
154
+ await historyOp(true, current); await sidebar();
155
+ } catch { notice("Chat is open, but browser storage could not save it."); }
156
+ } catch (err) { current.turns = original; render(); notice(err.message); }
157
+ finally { busy = false; el("send").disabled = false; el("prompt").disabled = false; el("prompt").focus(); }
158
+ };
159
+ async function init() {
160
+ el("side").hidden = innerWidth <= 700;
161
+ config = await api("config");
162
+ try { database = await openHistory(); await sidebar(); }
163
+ catch { notice("Browser history storage is unavailable."); }
164
+ for (const model of config.models) {
165
+ const option = document.createElement("option"); option.value = model; el("models").append(option);
166
+ }
167
+ el("model").value = config.initial || config.models[0]; updateDetails();
168
+ if (config.initial) await load(config.initial);
169
+ }
170
+ init().catch(err => notice(err.message));
@@ -0,0 +1,8 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>uniquechat</title><link rel="stylesheet" href="/app.css"><script defer src="/app.js"></script></head>
3
+ <body><aside id="side"><strong class="brand"><i>u</i> uniquechat</strong><button id="new">+ New chat</button><h3>Chat history</h3><nav id="history"></nav><small>Saved in this browser</small></aside>
4
+ <main><header><button id="menu" aria-label="Toggle chat history">☰</button><b id="modelName">Model picker</b><span class="device">● On this device</span></header>
5
+ <section id="picker" class="center"><div class="mark">u</div><h1>Choose your model</h1><p>Download once. Chat locally, even offline.</p><form id="pick"><label for="model">Hugging Face model</label><input id="model" list="models" autocomplete="off" required><datalist id="models"></datalist><div id="details"></div><button class="primary">Load model →</button></form></section>
6
+ <section id="loading" class="center" hidden><div class="spinner"></div><h1>Loading model</h1><p id="phase" role="status"></p></section>
7
+ <section id="conversation" hidden><div id="messages" aria-live="polite"></div><form id="compose"><div id="chips"></div><textarea id="prompt" placeholder="Message your local model…" aria-label="Message"></textarea><div class="tools"><button type="button" id="plus" aria-label="Attach files" title="Attach files">+</button><span id="types"></span><button id="send" class="primary" aria-label="Send message">↑</button></div><input type="file" id="file" hidden multiple></form></section>
8
+ <div id="notice" role="status"></div></main></body></html>
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: uniquechat
3
+ Version: 0.1.0
4
+ Summary: Pick a Hugging Face model and chat with it on your own computer.
5
+ Author: Unique50101
6
+ Requires-Python: <3.14,>=3.10
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: transformers<5,>=4.56
9
+ Requires-Dist: torch<3,>=2.4
10
+ Requires-Dist: torchvision<1,>=0.19
11
+ Requires-Dist: Pillow<13,>=10
12
+ Requires-Dist: huggingface-hub<1,>=0.34
13
+
14
+ # uniquechat
15
+
16
+ Choose a Hugging Face model in your browser, attach a file, and chat on your computer. **Once the package and model files are downloaded, the AI can work without internet.**
17
+
18
+ ![Illustrated walkthrough of running the Python script, selecting a model, loading it, and chatting locally](https://raw.githubusercontent.com/Unique50101/uniquechat/main/docs/quickstart.gif)
19
+
20
+ The animation illustrates the interaction with an example reply. An offline copy is included in `docs/quickstart.gif`.
21
+
22
+ ## Run it
23
+
24
+ Use Python 3.10–3.13 in a virtual environment. From an extracted source checkout, install with `python -m pip install .`. For a downloaded wheel, use `python -m pip install uniquechat-0.1.0-py3-none-any.whl`. After publication on PyPI, the install command is `python -m pip install uniquechat`.
25
+
26
+ Save this as `chat.py` and run `python chat.py`:
27
+
28
+ ```python
29
+ from uniquechat import launch
30
+ launch()
31
+ ```
32
+
33
+ Select a model and click **Load model**. The first load needs internet for any missing files and can take several minutes. The chat opens when the model is ready. Type a question, or use the **+** button and then send your prompt. Choose **+ New chat** to start again or switch models. Previous chats appear in the sidebar, saved with their attachments in this browser on this device. Stop the local server with Ctrl+C.
34
+
35
+ | Starter model | Inputs | Approximate weight download |
36
+ | --- | --- | --- |
37
+ | HuggingFaceTB/SmolLM2-135M-Instruct | Text and UTF-8 documents | 270 MB |
38
+ | HuggingFaceTB/SmolVLM-256M-Instruct | Text, UTF-8 documents and images | 510 MB |
39
+
40
+ Text files can be TXT, Markdown, CSV or JSON. Supported images are PNG, JPEG and WebP. Attach up to three files per message. Text files must fit the model's context window, even when smaller than the 32 KiB upload limit. Images are limited to 8 MiB and 16 megapixels each. Model weights, installed dependencies and runtime memory have separate space requirements.
41
+
42
+ ## Run offline
43
+
44
+ Download a model by loading it once while online. On the same computer, using the same Hugging Face cache, run:
45
+
46
+ ```python
47
+ from uniquechat import launch
48
+ launch(offline=True)
49
+ ```
50
+
51
+ Choose your downloaded model. Offline mode loads model files from the cache and reports missing files. Chat generation runs on your CPU or available CUDA GPU. Prompts and attachments are processed on your computer. The browser connects to a loopback server. The first package installation and model download require internet unless their files have already been supplied locally.
52
+
53
+ ## Skip the picker
54
+
55
+ ```python
56
+ from uniquechat import launch
57
+ launch("HuggingFaceTB/SmolVLM-256M-Instruct")
58
+ ```
59
+
60
+ From a terminal, use `uniquechat` or `uniquechat --offline HuggingFaceTB/SmolLM2-135M-Instruct`. You can enter other Transformers causal chat model IDs with built-in chat templates and safetensors weights. Image chat support targets Idefics3 and SmolVLM. Custom model code, GGUF files and image generation models are outside this version's scope.
61
+
62
+ ## Maintainer release
63
+
64
+ Register a pending PyPI Trusted Publisher for project `uniquechat`, owner `Unique50101`, repository `uniquechat`, workflow `release.yml`, environment `pypi`. Push a version tag matching the package metadata, such as `v0.1.0`. The workflow builds the wheel and source archive, installs the wheel, generates a reply with both starter models using cached weights, uploads to PyPI, and attaches the distributions to a GitHub Release. Manual workflow runs verify the package without publishing.
65
+
66
+ ## Run the GitHub Packages container
67
+
68
+ Run this command and open `http://127.0.0.1:7860` in Chrome. The named volume keeps downloaded models between runs.
69
+
70
+ ```shell
71
+ docker run --rm -p 127.0.0.1:7860:7860 -v uniquechat-models:/cache ghcr.io/unique50101/uniquechat:0.1.0
72
+ ```
@@ -0,0 +1,12 @@
1
+ uniquechat/__init__.py,sha256=xkBwlMnlJMuFBWXqno2KpLgV7aqit-XXjjcRrDEhmXw,597
2
+ uniquechat/__main__.py,sha256=ubt6XyZvcHwdjCQ90B_U4MeP-3YJduz5GWUC9yOgkrg,27
3
+ uniquechat/engine.py,sha256=nCaE5vvNz9f5mqQxhpMf6TPOtlnIw5w1uefcXDZ1FKE,4046
4
+ uniquechat/server.py,sha256=BT0Nusz7iPjxp5peK45TA9PpAwfDbeKoOgtgNoZs048,7075
5
+ uniquechat/static/app.css,sha256=K_xawG_OHxnugt0YMlgYwQrS-KnK0vwXlD2lUsC22NQ,3121
6
+ uniquechat/static/app.js,sha256=Ooo_ZjPhGjyhOiOlmyep5osim4XUVMsWGJiAhQvUb_Q,7520
7
+ uniquechat/static/index.html,sha256=D24Roa-tPHtHIUkyUKKb62e3USArPW2aXSsiPes0TNg,1666
8
+ uniquechat-0.1.0.dist-info/METADATA,sha256=4lZ_hY2muFPDrdPA0tWveF-CjQlAl2LFLcF-1MhF_RI,4153
9
+ uniquechat-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ uniquechat-0.1.0.dist-info/entry_points.txt,sha256=WDDrfG7kEbxS_g_gpXbnRunzdkZ4PFYQs2dk-uas9ts,47
11
+ uniquechat-0.1.0.dist-info/top_level.txt,sha256=hlad6GtzJMx6otBqAqLY2ps3pAPbQextmL9E7BJaYOc,11
12
+ uniquechat-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ uniquechat = uniquechat:main
@@ -0,0 +1 @@
1
+ uniquechat