From f268d851cff209ffc7f97311d7b98642e3278cb8 Mon Sep 17 00:00:00 2001 From: blankie Date: Thu, 26 Mar 2026 18:44:26 -0700 Subject: [PATCH 01/80] added entrypoint for Reticulum in Docker Replaces static CMD with an entrypoint that generates RNS config from environment variables (RNS_TCP_HOST/PORT), enabling TCP transport for environments without LAN auto-discovery (e.g. Docker on macOS). --- Dockerfile | 4 +++- app.py | 2 +- docker-compose.yml | 6 ++++++ entrypoint.sh | 39 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 2 deletions(-) create mode 100755 entrypoint.sh diff --git a/Dockerfile b/Dockerfile index 76fcb4e..9895f65 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,6 +11,8 @@ RUN mkdir -p /data \ && ln -sf /data/index.db index.db \ && ln -sf /data/tinyweb_identity tinyweb_identity +ENV PYTHONUNBUFFERED=1 + EXPOSE 8080 -CMD ["python", "app.py"] +ENTRYPOINT ["./entrypoint.sh"] diff --git a/app.py b/app.py index 01c4541..2149429 100644 --- a/app.py +++ b/app.py @@ -42,7 +42,7 @@ def start_gateway(reticulum): def main(): init_db() - reticulum = RNS.Reticulum() + reticulum = RNS.Reticulum(configdir=os.environ.get("RNS_CONFIG_DIR")) identity = load_or_create_identity() destination = RNS.Destination( diff --git a/docker-compose.yml b/docker-compose.yml index 99191f2..151a79c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,6 +6,12 @@ services: volumes: - tinyweb-data:/data restart: unless-stopped + # Connect to another Reticulum instance over TCP. + # Required on macOS (Docker can't do LAN auto-discovery). + # On Linux, auto-discovery works with network_mode: host. + # environment: + # - RNS_TCP_HOST=10.0.0.100 + # - RNS_TCP_PORT=4242 volumes: tinyweb-data: diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100755 index 0000000..4131973 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Generate Reticulum config with optional TCP peer +# Set RNS_TCP_HOST and RNS_TCP_PORT env vars to connect to a remote instance + +CONFIG_DIR="/data/.reticulum" +CONFIG_FILE="$CONFIG_DIR/config" + +mkdir -p "$CONFIG_DIR" + +if [ ! -f "$CONFIG_FILE" ]; then + cat > "$CONFIG_FILE" <> "$CONFIG_FILE" < Date: Thu, 26 Mar 2026 20:13:35 -0700 Subject: [PATCH 02/80] added default transport node New TinyWeb instances now auto-connect to rnode.bre.land:4242 so users get internet mesh connectivity out of the box without any manual Reticulum configuration. Env var overrides still supported. --- app.py | 36 +++++++++++++++++++++++++++++++++++- entrypoint.sh | 12 +++--------- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/app.py b/app.py index 2149429..e678dd2 100644 --- a/app.py +++ b/app.py @@ -11,6 +11,8 @@ from gateway import GatewayState, GatewayHandler, GATEWAY_PORT APP_NAME = "tinyweb" ASPECTS = ["server"] IDENTITY_FILE = "tinyweb_identity" +DEFAULT_TRANSPORT_HOST = "rnode.bre.land" +DEFAULT_TRANSPORT_PORT = 4242 def load_or_create_identity(): @@ -40,9 +42,41 @@ def start_gateway(reticulum): thread.start() +def ensure_rns_config(config_dir): + """Generate a default Reticulum config with internet transport if none exists.""" + if config_dir is None: + config_dir = os.path.expanduser("~/.reticulum") + config_file = os.path.join(config_dir, "config") + if os.path.exists(config_file): + return + os.makedirs(config_dir, exist_ok=True) + with open(config_file, "w") as f: + f.write(f"""[reticulum] + enable_transport = False + share_instance = Yes + +[logging] + loglevel = 4 + +[interfaces] + [[Default Interface]] + type = AutoInterface + enabled = Yes + + [[TCP Transport]] + type = TCPClientInterface + enabled = yes + target_host = {DEFAULT_TRANSPORT_HOST} + target_port = {DEFAULT_TRANSPORT_PORT} +""") + print(f"Created Reticulum config at {config_file}") + + def main(): init_db() - reticulum = RNS.Reticulum(configdir=os.environ.get("RNS_CONFIG_DIR")) + config_dir = os.environ.get("RNS_CONFIG_DIR") + ensure_rns_config(config_dir) + reticulum = RNS.Reticulum(configdir=config_dir) identity = load_or_create_identity() destination = RNS.Destination( diff --git a/entrypoint.sh b/entrypoint.sh index 4131973..3ca1bab 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -20,19 +20,13 @@ if [ ! -f "$CONFIG_FILE" ]; then [[Default Interface]] type = AutoInterface enabled = Yes -EOF - if [ -n "$RNS_TCP_HOST" ]; then - RNS_TCP_PORT="${RNS_TCP_PORT:-4242}" - cat >> "$CONFIG_FILE" < Date: Thu, 26 Mar 2026 21:32:11 -0700 Subject: [PATCH 03/80] added delay before announce for TCP readiness The announce was firing before the TCP transport connection was fully established, causing Docker instances to never announce over the mesh. --- app.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app.py b/app.py index e678dd2..174b661 100644 --- a/app.py +++ b/app.py @@ -93,6 +93,8 @@ def main(): allow=RNS.Destination.ALLOW_ALL, ) + # Brief delay to ensure all interfaces (especially TCP) are fully ready + time.sleep(2) destination.announce() set_setting("dest_hash", destination.hash.hex()) start_gateway(reticulum) From f912bab3a56badb2a1368666ffa72b7ecfa7c962 Mon Sep 17 00:00:00 2001 From: blankie Date: Thu, 26 Mar 2026 21:39:37 -0700 Subject: [PATCH 04/80] disabled share_instance for reliable announces With share_instance = Yes, announces weren't being sent over TCP in Docker environments. Setting it to No ensures each TinyWeb instance manages its own Reticulum interfaces directly. --- app.py | 2 +- entrypoint.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app.py b/app.py index 174b661..1099b60 100644 --- a/app.py +++ b/app.py @@ -53,7 +53,7 @@ def ensure_rns_config(config_dir): with open(config_file, "w") as f: f.write(f"""[reticulum] enable_transport = False - share_instance = Yes + share_instance = No [logging] loglevel = 4 diff --git a/entrypoint.sh b/entrypoint.sh index 3ca1bab..ebc54a3 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -11,7 +11,7 @@ if [ ! -f "$CONFIG_FILE" ]; then cat > "$CONFIG_FILE" < Date: Thu, 26 Mar 2026 21:51:58 -0700 Subject: [PATCH 05/80] redesigned subscriptions with card layout Replace cramped table layout with card-based design that works better in narrow viewports and across different themes. --- handlers.py | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/handlers.py b/handlers.py index 27ff3d3..2034d3f 100644 --- a/handlers.py +++ b/handlers.py @@ -685,32 +685,30 @@ def handle_subscriptions(msg=""): subs = db.execute("SELECT * FROM subscriptions ORDER BY id DESC").fetchall() finally: return_db(db) - items = "" + cards = "" for s in subs: auto_label = "on" if s["auto_sync"] else "off" last = s["last_sync"] or "never" - items += ( - f'' - f'{esc(s["name"] or "unknown")}
{esc(s["dest_hash"])}' - f'{esc(last)}' - f'' + cards += ( + f'
' + f'
{esc(s["name"] or "unknown")}
' + f'
{esc(s["dest_hash"])}
' + f'
last sync: {esc(last)}
' + f'
' + f'browse' + f'
' + f'{_csrf_field()}
' f'
' f'{_csrf_field()}
' - f'' - f'' - f'browse ' - f'
' - f'{_csrf_field()}
' f'
' f'{_csrf_field()}
' - f'' - f'' + f'
' + f'
' ) - table = "" + listing = "" if subs: - table = ( - f'' - f'{items}
instancelast syncauto-syncactions
' + listing = ( + f'{cards}' f'
' f'{_csrf_field()}
' ) @@ -722,7 +720,7 @@ def handle_subscriptions(msg=""): f'' f'' f'

{msg}

' - f'
{table}' + f'
{listing}' f'
back' ) From a708b753fa422ae2f88e00022337f611075f08a4 Mon Sep 17 00:00:00 2001 From: blankie Date: Thu, 26 Mar 2026 22:00:27 -0700 Subject: [PATCH 06/80] fixed navbar disappearing on save Browser textarea submissions convert \n to \r\n, causing the template comparison against DEFAULT_TEMPLATE to always fail. This saved the bare skeleton as a custom template, overriding the default navbar. --- handlers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/handlers.py b/handlers.py index 2034d3f..4eaab1e 100644 --- a/handlers.py +++ b/handlers.py @@ -525,7 +525,7 @@ def handle_style_form(msg=""): def handle_style_submit(body): - template = body.get("template", [""])[0] + template = body.get("template", [""])[0].replace("\r\n", "\n").replace("\r", "\n") name = body.get("site_name", ["tinyweb"])[0].strip() sharing = "1" if body.get("sharing_enabled") else "0" set_setting("custom_template", template if template.strip() != DEFAULT_TEMPLATE.strip() else "") From 51e6bf2b72eedbdd33e91c899b5e9e89bbc53d22 Mon Sep 17 00:00:00 2001 From: blankie Date: Fri, 27 Mar 2026 03:24:41 -0700 Subject: [PATCH 07/80] added hybrid semantic search with reranking Implements a three-stage search pipeline: 1. BM25 keyword search via FTS5 with column weights 2. Semantic search via Snowflake arctic-embed-s bi-encoder + HNSW index 3. Optional cross-encoder reranking (on by default, toggleable in settings) Top 20 results are reranked for precision, next 10 appended from RRF for coverage, giving 30 total results across 3 pages. - New embeddings.py with ONNX Runtime inference, text chunking, HNSW index management, RRF fusion, and cross-encoder reranking - Meta description extraction for authentic page snippets with centroid extractive fallback - Stopword filtering in FTS5 queries to avoid overly strict matching - /reindex page for batch embedding of existing pages - Semantic embedding of remote pages during subscription sync - ~125MB dependency footprint (onnxruntime, tokenizers, hnswlib, numpy) - Models: 34MB bi-encoder + 22MB cross-encoder (downloaded on first use) --- .gitignore | 4 + app.py | 17 ++ db.py | 108 ++++++++- embeddings.py | 553 +++++++++++++++++++++++++++++++++++++++++++++++ handlers.py | 169 ++++++++++++++- requirements.txt | 5 + 6 files changed, 839 insertions(+), 17 deletions(-) create mode 100644 embeddings.py diff --git a/.gitignore b/.gitignore index 799f1c1..bfefc77 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ __pycache__/ tinyweb_identity index.db +index.db-shm +index.db-wal +models/ +index.hnsw diff --git a/app.py b/app.py index 1099b60..e3422d9 100644 --- a/app.py +++ b/app.py @@ -72,8 +72,25 @@ def ensure_rns_config(config_dir): print(f"Created Reticulum config at {config_file}") +def _preload_embeddings(): + """Pre-load the embedding model and build the HNSW index in background.""" + try: + from embeddings import _get_session, _get_reranker, build_index + _get_session() # downloads model on first run, loads ONNX session + build_index() # builds HNSW index from existing chunks + # Preload cross-encoder unless user has explicitly disabled it + if get_setting("use_reranker", "1") == "1": + _get_reranker() + print("Semantic search ready (with reranker).") + else: + print("Semantic search ready.") + except Exception as e: + print(f"Semantic search unavailable: {e}") + + def main(): init_db() + threading.Thread(target=_preload_embeddings, daemon=True).start() config_dir = os.environ.get("RNS_CONFIG_DIR") ensure_rns_config(config_dir) reticulum = RNS.Reticulum(configdir=config_dir) diff --git a/db.py b/db.py index 0d32b3a..6b225a2 100644 --- a/db.py +++ b/db.py @@ -226,6 +226,27 @@ def init_db(): db.execute("UPDATE pages SET last_modified = strftime('%Y-%m-%dT%H:%M:%S','now') WHERE last_modified = ''") db.commit() + # Migrate pages: add summary column if missing + if "summary" not in page_cols: + db.execute("ALTER TABLE pages ADD COLUMN summary TEXT DEFAULT ''") + db.commit() + + # Chunks table for semantic search embeddings + db.execute( + "CREATE TABLE IF NOT EXISTS chunks (" + " id INTEGER PRIMARY KEY AUTOINCREMENT," + " page_id INTEGER," + " remote_page_id INTEGER," + " chunk_index INTEGER NOT NULL," + " chunk_text TEXT NOT NULL," + " embedding BLOB NOT NULL," + " FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE," + " FOREIGN KEY (remote_page_id) REFERENCES remote_pages(id) ON DELETE CASCADE" + ")" + ) + db.execute("CREATE INDEX IF NOT EXISTS idx_chunks_page ON chunks(page_id)") + db.execute("CREATE INDEX IF NOT EXISTS idx_chunks_remote ON chunks(remote_page_id)") + db.execute("PRAGMA journal_mode=WAL") db.commit() db.close() @@ -296,24 +317,96 @@ def fetch_page(url): label = a.get_text(strip=True) or href links.append((href, label[:200])) + # Extract meta description before stripping tags + meta_desc = "" + meta_tag = soup.find("meta", attrs={"name": "description"}) + if meta_tag and meta_tag.get("content"): + meta_desc = meta_tag["content"].strip() + if not meta_desc: + # Try og:description as fallback + og_tag = soup.find("meta", attrs={"property": "og:description"}) + if og_tag and og_tag.get("content"): + meta_desc = og_tag["content"].strip() + for tag in soup(["script", "style", "nav", "footer", "header"]): tag.decompose() title = soup.title.string.strip() if soup.title and soup.title.string else url body = soup.get_text(separator=" ", strip=True) - return title, body, links + return title, body, links, meta_desc + + +def _generate_summary(title, body): + """Generate a summary from body text using centroid extractive method. + + Filters out UI debris, embeds remaining sentences, finds the one + closest to the centroid (most representative of the page). + """ + import re + # Split on sentence boundaries + raw = re.split(r'(?<=[.!?])\s+', body) + sentences = [] + noise_patterns = re.compile( + r'arrow-|fedilink|message-square|link-external|' + r'skip to|cookie|subscribe|sign up|log in|' + r'privacy policy|terms of|©|\bads?\b', + re.IGNORECASE + ) + for s in raw: + s = s.strip() + if len(s) < 40: + continue + words = s.split() + if len(words) < 7: + continue + # Skip if mostly non-alpha (icons, arrows, encoded chars) + alpha_chars = sum(1 for c in s if c.isalpha() or c == ' ') + if alpha_chars < len(s) * 0.6: + continue + # Skip nav/menu patterns + if s.count('|') > 2 or s.count('·') > 2 or s.count('►') > 0: + continue + # Skip UI debris + if noise_patterns.search(s): + continue + sentences.append(s) + + if not sentences: + # Last resort: take the first chunk of body that looks like prose + clean = re.sub(r'\s+', ' ', body).strip() + return clean[:160] + "..." if len(clean) > 160 else clean + if len(sentences) == 1: + s = sentences[0] + return s[:200] if len(s) > 200 else s + try: + from embeddings import embed + import numpy as np + embs = embed(sentences[:50]) # cap to avoid embedding too many + centroid = embs.mean(axis=0, keepdims=True) + centroid = centroid / max(np.linalg.norm(centroid), 1e-12) + scores = (embs @ centroid.T).flatten() + best_idx = int(np.argmax(scores)) + result = sentences[best_idx] + # Try to add a second sentence if it fits + if best_idx + 1 < len(sentences) and len(result) + len(sentences[best_idx + 1]) + 1 <= 200: + result += " " + sentences[best_idx + 1] + return result[:200] if len(result) > 200 else result + except Exception: + return sentences[0][:200] def index_url(url, note=""): url = clean_url(url) - title, body, links = fetch_page(url) + title, body, links, meta_desc = fetch_page(url) + # Use meta description if available, otherwise generate from body + summary = meta_desc if meta_desc else _generate_summary(title, body) db = get_db() try: now = __import__("datetime").datetime.now().strftime("%Y-%m-%dT%H:%M:%S") db.execute( - "INSERT INTO pages (url, title, body, note, last_modified) VALUES (?, ?, ?, ?, ?) " + "INSERT INTO pages (url, title, body, note, last_modified, summary) VALUES (?, ?, ?, ?, ?, ?) " "ON CONFLICT(url) DO UPDATE SET title=excluded.title, body=excluded.body, " - "note=excluded.note, last_modified=excluded.last_modified", - (url, title, body, note, now), + "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary", + (url, title, body, note, now, summary), ) page_id = db.execute("SELECT id FROM pages WHERE url = ?", (url,)).fetchone()[0] db.execute("DELETE FROM links WHERE page_id = ?", (page_id,)) @@ -323,6 +416,11 @@ def index_url(url, note=""): (page_id, href, label), ) db.commit() + try: + from embeddings import store_embeddings + store_embeddings(page_id, title, body, db) + except Exception: + pass # embedding generation is best-effort finally: return_db(db) return title diff --git a/embeddings.py b/embeddings.py new file mode 100644 index 0000000..5575c29 --- /dev/null +++ b/embeddings.py @@ -0,0 +1,553 @@ +"""Semantic search using Snowflake arctic-embed-s via ONNX Runtime + hnswlib.""" + +import os +import re +import threading +import numpy as np + +MODEL_ID = "Snowflake/snowflake-arctic-embed-s" +MODEL_DIR = os.path.join(os.path.dirname(__file__), "models", "snowflake-arctic-embed-s") +RERANKER_DIR = os.path.join(os.path.dirname(__file__), "models", "cross-encoder") +HNSW_PATH = os.path.join(os.path.dirname(__file__), "index.hnsw") +DIMS = 384 +MAX_TOKENS = 512 +QUERY_PREFIX = "Represent this sentence for searching relevant passages: " + +_session = None +_tokenizer = None +_lock = threading.Lock() + +_reranker_session = None +_reranker_tokenizer = None +_reranker_lock = threading.Lock() + +# Live HNSW index and chunk-id mapping +_hnsw_index = None +_hnsw_ids = [] # maps internal HNSW label -> chunks.id +_hnsw_lock = threading.Lock() + + +# --------------------------------------------------------------------------- +# Model download & loading +# --------------------------------------------------------------------------- + +def _ensure_model(): + """Download the ONNX model and tokenizer from HuggingFace if not present.""" + model_path = os.path.join(MODEL_DIR, "model.onnx") + tokenizer_path = os.path.join(MODEL_DIR, "tokenizer.json") + if os.path.exists(model_path) and os.path.exists(tokenizer_path): + return + from huggingface_hub import hf_hub_download + os.makedirs(MODEL_DIR, exist_ok=True) + files = { + "onnx/model_quantized.onnx": "model.onnx", + "tokenizer.json": "tokenizer.json", + "tokenizer_config.json": "tokenizer_config.json", + } + for remote, local in files.items(): + target = os.path.join(MODEL_DIR, local) + if os.path.exists(target): + continue + cached = hf_hub_download(repo_id=MODEL_ID, filename=remote) + # hf_hub_download returns the cached file path; copy to our model dir + import shutil + shutil.copy2(cached, target) + + +def _get_session(): + """Return (onnxruntime.InferenceSession, tokenizers.Tokenizer) singleton.""" + global _session, _tokenizer + if _session is not None: + return _session, _tokenizer + with _lock: + if _session is not None: + return _session, _tokenizer + _ensure_model() + import onnxruntime as ort + from tokenizers import Tokenizer + _session = ort.InferenceSession( + os.path.join(MODEL_DIR, "model.onnx"), + providers=["CPUExecutionProvider"], + ) + _tokenizer = Tokenizer.from_file(os.path.join(MODEL_DIR, "tokenizer.json")) + _tokenizer.enable_truncation(max_length=MAX_TOKENS) + _tokenizer.enable_padding(pad_id=0, pad_token="[PAD]", length=None) + return _session, _tokenizer + + +def _get_reranker(): + """Return (onnxruntime.InferenceSession, tokenizers.Tokenizer) for the cross-encoder reranker.""" + global _reranker_session, _reranker_tokenizer + if _reranker_session is not None: + return _reranker_session, _reranker_tokenizer + with _reranker_lock: + if _reranker_session is not None: + return _reranker_session, _reranker_tokenizer + model_path = os.path.join(RERANKER_DIR, "model.onnx") + tok_path = os.path.join(RERANKER_DIR, "tokenizer.json") + if not os.path.exists(model_path) or not os.path.exists(tok_path): + return None, None + import onnxruntime as ort + from tokenizers import Tokenizer + _reranker_session = ort.InferenceSession( + model_path, providers=["CPUExecutionProvider"], + ) + _reranker_tokenizer = Tokenizer.from_file(tok_path) + _reranker_tokenizer.enable_truncation(max_length=512) + _reranker_tokenizer.enable_padding(pad_id=0, pad_token="[PAD]", length=None) + return _reranker_session, _reranker_tokenizer + + +def rerank(query, documents, limit=10): + """Score query-document pairs with the cross-encoder and return reranked indices. + + Args: + query: search query string + documents: list of document texts to score against the query + limit: max results to return + + Returns: list of (original_index, score) sorted by score descending. + """ + session, tokenizer = _get_reranker() + if session is None: + return [(i, 0.0) for i in range(min(limit, len(documents)))] + + # Cross-encoder takes (query, document) pairs — encode as pair sequences + pairs = [[query, doc] for doc in documents] + encodings = tokenizer.encode_batch(pairs) + + input_ids = np.array([e.ids for e in encodings], dtype=np.int64) + attention_mask = np.array([e.attention_mask for e in encodings], dtype=np.int64) + token_type_ids = np.array([e.type_ids for e in encodings], dtype=np.int64) + + outputs = session.run( + None, + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "token_type_ids": token_type_ids, + }, + ) + # Output is logits — higher = more relevant + scores = outputs[0].flatten() + ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True) + return [(i, float(scores[i])) for i in ranked[:limit]] + + +# --------------------------------------------------------------------------- +# Text chunking +# --------------------------------------------------------------------------- + +_SENTENCE_RE = re.compile(r'(?<=[.!?])\s+') + + +def chunk_text(title, body): + """Split body into chunks, each prefixed with title for context. + + Strategy: split on double newlines (paragraphs). If a paragraph exceeds + MAX_TOKENS words, split at sentence boundaries. Each chunk is prefixed + with the page title. + """ + if not body or not body.strip(): + return [f"{title}"] if title else [] + + prefix = f"{title}: " if title else "" + # Rough word budget for chunk body (leave room for prefix) + prefix_words = len(prefix.split()) + max_words = MAX_TOKENS - prefix_words # approximate; tokenizer may differ + + paragraphs = re.split(r'\n\s*\n', body.strip()) + chunks = [] + + for para in paragraphs: + para = para.strip() + if len(para) < 20: + continue + words = para.split() + if len(words) <= max_words: + chunks.append(prefix + para) + else: + # Split paragraph into sentences + sentences = _SENTENCE_RE.split(para) + current = [] + current_len = 0 + for sent in sentences: + sent_words = len(sent.split()) + if current_len + sent_words > max_words and current: + chunks.append(prefix + " ".join(current)) + current = [] + current_len = 0 + if sent_words > max_words: + # Sentence too long — use sliding window + s_words = sent.split() + for i in range(0, len(s_words), max_words - 50): + window = s_words[i:i + max_words] + chunks.append(prefix + " ".join(window)) + else: + current.append(sent) + current_len += sent_words + if current: + chunks.append(prefix + " ".join(current)) + + if not chunks and title: + chunks = [title] + + return chunks + + +# --------------------------------------------------------------------------- +# Embedding +# --------------------------------------------------------------------------- + +def embed(texts, is_query=False): + """Encode texts into L2-normalized float32 embeddings (N, 384). + + For queries, prepend the model's query prefix. + Processes in batches of 32 to limit memory usage. + """ + if not texts: + return np.empty((0, DIMS), dtype=np.float32) + + session, tokenizer = _get_session() + + if is_query: + texts = [QUERY_PREFIX + t for t in texts] + + batch_size = 32 + all_embeddings = [] + + for start in range(0, len(texts), batch_size): + batch = texts[start:start + batch_size] + encodings = tokenizer.encode_batch(batch) + input_ids = np.array([e.ids for e in encodings], dtype=np.int64) + attention_mask = np.array([e.attention_mask for e in encodings], dtype=np.int64) + token_type_ids = np.zeros_like(input_ids) + + outputs = session.run( + None, + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "token_type_ids": token_type_ids, + }, + ) + # CLS token pooling — take the first token's hidden state + emb = outputs[0][:, 0, :] + all_embeddings.append(emb) + + embeddings = np.concatenate(all_embeddings, axis=0) + # L2 normalize + norms = np.linalg.norm(embeddings, axis=1, keepdims=True) + norms = np.maximum(norms, 1e-12) + embeddings = embeddings / norms + return embeddings.astype(np.float32) + + +# --------------------------------------------------------------------------- +# HNSW index management +# --------------------------------------------------------------------------- + +def build_index(db=None): + """Load all embeddings from chunks table and build HNSW index.""" + import hnswlib + global _hnsw_index, _hnsw_ids + + from db import get_db, return_db + own_db = db is None + if own_db: + db = get_db() + try: + rows = db.execute("SELECT id, embedding FROM chunks ORDER BY id").fetchall() + finally: + if own_db: + return_db(db) + + with _hnsw_lock: + if not rows: + _hnsw_index = None + _hnsw_ids = [] + return + + n = len(rows) + ids = [r["id"] for r in rows] + matrix = np.frombuffer(b"".join(r["embedding"] for r in rows), dtype=np.float32).reshape(n, DIMS) + + index = hnswlib.Index(space="cosine", dim=DIMS) + # ef_construction and M balance build speed vs recall; + # these defaults give >99% recall at reasonable build time + index.init_index(max_elements=max(n, 1024), ef_construction=200, M=16) + index.add_items(matrix, list(range(n))) + index.set_ef(50) # query-time accuracy parameter + + _hnsw_index = index + _hnsw_ids = ids + + +def _add_to_index(chunk_ids, embeddings_matrix): + """Add new embeddings to the live HNSW index.""" + import hnswlib + global _hnsw_index, _hnsw_ids + + with _hnsw_lock: + if _hnsw_index is None: + index = hnswlib.Index(space="cosine", dim=DIMS) + index.init_index(max_elements=1024, ef_construction=200, M=16) + index.set_ef(50) + _hnsw_index = index + _hnsw_ids = [] + + current_max = _hnsw_index.get_max_elements() + needed = len(_hnsw_ids) + len(chunk_ids) + if needed > current_max: + _hnsw_index.resize_index(max(needed * 2, current_max * 2)) + + labels = list(range(len(_hnsw_ids), len(_hnsw_ids) + len(chunk_ids))) + _hnsw_index.add_items(embeddings_matrix, labels) + _hnsw_ids.extend(chunk_ids) + + +# --------------------------------------------------------------------------- +# Store embeddings for pages +# --------------------------------------------------------------------------- + +def store_embeddings(page_id, title, body, db): + """Chunk, embed, and store embeddings for a page. Adds to HNSW index.""" + chunks = chunk_text(title, body) + if not chunks: + return + + embeddings_matrix = embed(chunks) + + # Delete old chunks for this page + db.execute("DELETE FROM chunks WHERE page_id = ?", (page_id,)) + + new_ids = [] + for i, (text, emb) in enumerate(zip(chunks, embeddings_matrix)): + cursor = db.execute( + "INSERT INTO chunks (page_id, remote_page_id, chunk_index, chunk_text, embedding) " + "VALUES (?, NULL, ?, ?, ?)", + (page_id, i, text, emb.tobytes()), + ) + new_ids.append(cursor.lastrowid) + db.commit() + + _add_to_index(new_ids, embeddings_matrix) + + +def store_remote_embeddings(remote_page_id, title, note, db): + """Store a single embedding for a remote page (title + note).""" + text = f"{title}: {note}" if note else (title or "") + if not text.strip(): + return + + embeddings_matrix = embed([text]) + + db.execute("DELETE FROM chunks WHERE remote_page_id = ?", (remote_page_id,)) + cursor = db.execute( + "INSERT INTO chunks (page_id, remote_page_id, chunk_index, chunk_text, embedding) " + "VALUES (NULL, ?, 0, ?, ?)", + (remote_page_id, text, embeddings_matrix[0].tobytes()), + ) + db.commit() + + _add_to_index([cursor.lastrowid], embeddings_matrix) + + +# --------------------------------------------------------------------------- +# Search +# --------------------------------------------------------------------------- + +def semantic_search(query_text, limit=100, db=None): + """Search for pages by semantic similarity. + + Returns: [(page_id, score, best_chunk_text), ...] sorted by score desc. + Groups by page_id, taking the max chunk score per page. + """ + if _hnsw_index is None or not _hnsw_ids: + return [] + + query_emb = embed([query_text], is_query=True) + + with _hnsw_lock: + if _hnsw_index is None or not _hnsw_ids: + return [] + k = min(limit * 3, len(_hnsw_ids)) # oversample to account for grouping + if k == 0: + return [] + labels, distances = _hnsw_index.knn_query(query_emb, k=k) + + # Map HNSW labels back to chunk IDs + chunk_ids = [_hnsw_ids[int(lbl)] for lbl in labels[0]] + # cosine distance -> similarity: hnswlib returns 1-cosine for "cosine" space + scores = [1.0 - float(d) for d in distances[0]] + + # Fetch chunk details from DB + from db import get_db, return_db + own_db = db is None + if own_db: + db = get_db() + try: + placeholders = ",".join("?" * len(chunk_ids)) + rows = db.execute( + f"SELECT id, page_id, chunk_text FROM chunks WHERE id IN ({placeholders})", + chunk_ids, + ).fetchall() + finally: + if own_db: + return_db(db) + + chunk_map = {r["id"]: r for r in rows} + + # Group by page_id, keep best score and chunk text per page + page_best = {} # page_id -> (score, chunk_text) + for cid, score in zip(chunk_ids, scores): + chunk = chunk_map.get(cid) + if not chunk or chunk["page_id"] is None: + continue + pid = chunk["page_id"] + if pid not in page_best or score > page_best[pid][0]: + page_best[pid] = (score, chunk["chunk_text"]) + + results = [(pid, score, text) for pid, (score, text) in page_best.items()] + results.sort(key=lambda x: x[1], reverse=True) + return results[:limit] + + +def hybrid_search(query_text, bm25_ranked_ids, limit=10, db=None, use_reranker=False): + """Merge BM25 and semantic results via RRF, optionally rerank with cross-encoder. + + Default (two-stage): BM25 + semantic fused via RRF. + With use_reranker=True (three-stage): rerank top 20 with cross-encoder. + + Returns: [(page_id, best_chunk_text), ...] in ranked order. + """ + k = 60 # RRF constant + + sem_results = semantic_search(query_text, limit=100, db=db) + + best_chunks = {} # page_id -> chunk_text + for _rank, (pid, _score, chunk_text) in enumerate(sem_results): + if pid not in best_chunks: + best_chunks[pid] = chunk_text + + # When BM25 has no hits, use raw semantic similarity scores directly + # (RRF rank positions distort nearly-equal scores) + if not bm25_ranked_ids: + fused_ids = [(pid, score) for pid, score, _ in sem_results] + else: + rrf_scores = {} + for rank, pid in enumerate(bm25_ranked_ids): + rrf_scores[pid] = rrf_scores.get(pid, 0) + 1.0 / (k + rank + 1) + for rank, (pid, _score, chunk_text) in enumerate(sem_results): + rrf_scores[pid] = rrf_scores.get(pid, 0) + 1.0 / (k + rank + 1) + fused_ids = sorted(rrf_scores.items(), key=lambda x: x[1], reverse=True) + + fused = fused_ids + all_ids = [pid for pid, _ in fused] + + if not all_ids: + return [] + + if not use_reranker: + return [(pid, best_chunks.get(pid, "")) for pid in all_ids[:limit]] + + # --- Rerank top 20, append next 10 from RRF order --- + rerank_ids = all_ids[:20] + tail_ids = all_ids[20:30] + + from db import get_db, return_db + own_db = db is None + if own_db: + db = get_db() + try: + placeholders = ",".join("?" * len(rerank_ids)) + rows = db.execute( + f"SELECT id, title, body FROM pages WHERE id IN ({placeholders})", + rerank_ids, + ).fetchall() + finally: + if own_db: + return_db(db) + + page_map = {r["id"]: r for r in rows} + + doc_texts = [] + ordered_ids = [] + for pid in rerank_ids: + page = page_map.get(pid) + if not page: + continue + chunk = best_chunks.get(pid, "") + body_preview = chunk[:200] if chunk else page["body"][:200] + doc = f"{page['title']}. {body_preview}" + doc_texts.append(doc) + ordered_ids.append(pid) + + if not doc_texts: + return [] + + try: + reranked = rerank(query_text, doc_texts, limit=20) + results = [(ordered_ids[idx], best_chunks.get(ordered_ids[idx], "")) for idx, _score in reranked] + except Exception: + results = [(pid, best_chunks.get(pid, "")) for pid in ordered_ids[:20]] + + # Append next 10 from RRF order (no reranking) + reranked_set = {pid for pid, _ in results} + for pid in tail_ids: + if pid not in reranked_set: + results.append((pid, best_chunks.get(pid, ""))) + + return results[:30] + + +# --------------------------------------------------------------------------- +# Reindex +# --------------------------------------------------------------------------- + +def reindex_all(db=None, progress_callback=None): + """Embed all pages that don't yet have chunks. Also generates missing summaries. Rebuilds HNSW index.""" + from db import get_db, return_db, _generate_summary + own_db = db is None + if own_db: + db = get_db() + try: + rows = db.execute( + "SELECT p.id, p.title, p.body, p.summary FROM pages p " + "WHERE p.id NOT IN (SELECT DISTINCT page_id FROM chunks WHERE page_id IS NOT NULL)" + ).fetchall() + + total = len(rows) + for i, row in enumerate(rows): + store_embeddings(row["id"], row["title"], row["body"], db) + # Generate summary if missing + if not row["summary"]: + summary = _generate_summary(row["title"], row["body"]) + db.execute("UPDATE pages SET summary = ? WHERE id = ?", (summary, row["id"])) + db.commit() + if progress_callback: + progress_callback(i + 1, total) + + # Generate summaries for pages that already have chunks but no summary + no_summary = db.execute( + "SELECT id, title, body FROM pages WHERE summary = '' OR summary IS NULL" + ).fetchall() + for row in no_summary: + summary = _generate_summary(row["title"], row["body"]) + db.execute("UPDATE pages SET summary = ? WHERE id = ?", (summary, row["id"])) + if no_summary: + db.commit() + + # Also handle remote pages + remote_rows = db.execute( + "SELECT rp.id, rp.title, rp.note FROM remote_pages rp " + "WHERE rp.id NOT IN (SELECT DISTINCT remote_page_id FROM chunks WHERE remote_page_id IS NOT NULL)" + ).fetchall() + + for rp in remote_rows: + store_remote_embeddings(rp["id"], rp["title"], rp["note"], db) + finally: + if own_db: + return_db(db) + + build_index(db) diff --git a/handlers.py b/handlers.py index 4eaab1e..abd0d13 100644 --- a/handlers.py +++ b/handlers.py @@ -1,4 +1,5 @@ import json +import re import secrets import threading from datetime import datetime @@ -27,10 +28,41 @@ def _check_csrf(body): return secrets.compare_digest(token, expected) +_STOPWORDS = frozenset({ + "a", "an", "the", "and", "or", "but", "is", "are", "was", "were", + "in", "on", "at", "to", "for", "of", "with", "by", "from", "as", + "into", "about", "how", "what", "which", "who", "where", "when", + "do", "does", "did", "be", "been", "being", "have", "has", "had", + "it", "its", "this", "that", "not", "no", "so", "if", "can", "will", + "my", "your", "i", "me", "we", "you", "he", "she", "they", +}) + + def _sanitize_fts_query(query): - """Escape user input for safe use in FTS5 MATCH.""" - escaped = query.replace('"', '""') - return f'"{escaped}"' + """Escape user input for safe use in FTS5 MATCH. + + Splits into individual quoted tokens joined by implicit AND, + so all words must appear but in any order. Appends * to the + last token for prefix matching. Stopwords are dropped to avoid + overly strict matching. + """ + words = query.split() + if not words: + return '""' + tokens = [] + for i, w in enumerate(words): + # Strip FTS5 special characters to prevent injection + cleaned = re.sub(r'["\'\(\)\*\+\-\^~]', '', w).strip() + if not cleaned: + continue + if cleaned.lower() in _STOPWORDS: + continue + if i == len(words) - 1: + # Prefix match on the last token for partial word matching + tokens.append(f"{cleaned}*") + else: + tokens.append(f'"{cleaned}"') + return " ".join(tokens) if tokens else '""' def _get_bookmark_token(): @@ -155,20 +187,46 @@ def handle_search(query): result_html = "" trusted_html = "" if q: + # BM25 keyword search with column weights: title=10, body=1, url=5, note=3 try: - total_results = db.execute( - "SELECT count(*) FROM pages_fts WHERE pages_fts MATCH ?", - (_sanitize_fts_query(q),), - ).fetchone()[0] - rows = db.execute( + fts_q = _sanitize_fts_query(q) + bm25_rows = db.execute( "SELECT p.id, p.url, p.title, p.body, p.note " "FROM pages_fts f JOIN pages p ON f.rowid = p.id " - "WHERE pages_fts MATCH ? ORDER BY rank LIMIT ? OFFSET ?", - (_sanitize_fts_query(q), PER_PAGE, offset), + "WHERE pages_fts MATCH ? " + "ORDER BY bm25(pages_fts, 10.0, 1.0, 5.0, 3.0) LIMIT 100", + (fts_q,), ).fetchall() except Exception: + bm25_rows = [] + + # Hybrid search: merge BM25 + semantic via RRF + bm25_ids = [r["id"] for r in bm25_rows] + chunk_snippets = {} # page_id -> best chunk text + try: + from embeddings import hybrid_search + use_reranker = get_setting("use_reranker", "1") == "1" + fused = hybrid_search(q, bm25_ids, limit=100, db=db, use_reranker=use_reranker) + fused_ids = [pid for pid, _ in fused] + chunk_snippets = {pid: text for pid, text in fused if text} + except Exception: + fused_ids = bm25_ids + + total_results = len(fused_ids) + page_ids = fused_ids[offset:offset + PER_PAGE] + + if page_ids: + # Fetch rows in fused order + placeholders = ",".join("?" * len(page_ids)) + all_rows = db.execute( + f"SELECT id, url, title, body, note, summary FROM pages WHERE id IN ({placeholders})", + page_ids, + ).fetchall() + row_map = {r["id"]: r for r in all_rows} + rows = [row_map[pid] for pid in page_ids if pid in row_map] + else: rows = [] - total_results = 0 + if rows: for r in rows: note_html = "" @@ -179,11 +237,13 @@ def handle_search(query): if tags: tag_links = " ".join(f'[{esc(t)}]' for t in tags) tags_html = f'
{tag_links}
' + # Use page summary as snippet (meta description or centroid sentence) + snip = r["summary"] if r["summary"] else snippet(r["body"], q) result_html += ( f'
' f'{esc(r["title"])}
' f'{esc(r["url"])}
' - f'{esc(snippet(r["body"], q))}' + f'{esc(snip)}' f'{note_html}{tags_html}' f'
' ) @@ -495,6 +555,8 @@ def handle_style_form(msg=""): name = get_site_name() sharing = get_setting("sharing_enabled", "0") checked = " checked" if sharing == "1" else "" + reranker = get_setting("use_reranker", "1") + reranker_checked = " checked" if reranker == "1" else "" return _respond( f"

customize

" f"

name your search engine

" @@ -504,6 +566,10 @@ def handle_style_form(msg=""): f"

sharing

" f'

" + f"

search

" + f'
" + f"Uses a 22MB model. Adds ~50ms per search. Disable for faster results.

" f"

custom html

" f"

Edit the full page template. Use {esc('{{content}}')} " f"where page content should appear.

" @@ -528,9 +594,11 @@ def handle_style_submit(body): template = body.get("template", [""])[0].replace("\r\n", "\n").replace("\r", "\n") name = body.get("site_name", ["tinyweb"])[0].strip() sharing = "1" if body.get("sharing_enabled") else "0" + reranker = "1" if body.get("use_reranker") else "0" set_setting("custom_template", template if template.strip() != DEFAULT_TEMPLATE.strip() else "") set_setting("site_name", name or "tinyweb") set_setting("sharing_enabled", sharing) + set_setting("use_reranker", reranker) return handle_style_form("Saved.") @@ -904,6 +972,16 @@ def handle_subscription_sync(sub_id): "ON CONFLICT(subscription_id, url) DO UPDATE SET title=excluded.title, note=excluded.note, tags=excluded.tags", (sub_id, s["url"], s["title"], s.get("note", ""), tags_str), ) + # Embed remote page for semantic search + try: + from embeddings import store_remote_embeddings + rp_id = db.execute( + "SELECT id FROM remote_pages WHERE subscription_id = ? AND url = ?", + (sub_id, s["url"]), + ).fetchone()["id"] + store_remote_embeddings(rp_id, s["title"], s.get("note", ""), db) + except Exception: + pass synced += 1 except Exception: pass @@ -970,6 +1048,15 @@ def handle_subscription_syncall(): "ON CONFLICT(subscription_id, url) DO UPDATE SET title=excluded.title, note=excluded.note, tags=excluded.tags", (sub["id"], s["url"], s["title"], s.get("note", ""), tags_str), ) + try: + from embeddings import store_remote_embeddings + rp_id = db.execute( + "SELECT id FROM remote_pages WHERE subscription_id = ? AND url = ?", + (sub["id"], s["url"]), + ).fetchone()["id"] + store_remote_embeddings(rp_id, s["title"], s.get("note", ""), db) + except Exception: + pass except Exception: pass now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") @@ -983,6 +1070,60 @@ def handle_subscription_syncall(): return handle_subscriptions(f"Synced {total} subscription(s).") +# --- Reindex (semantic search) --- + + +_reindex_thread = None + + +def handle_reindex_form(): + db = get_db() + try: + total_pages = db.execute("SELECT count(*) FROM pages").fetchone()[0] + pages_with_chunks = db.execute( + "SELECT count(DISTINCT page_id) FROM chunks WHERE page_id IS NOT NULL" + ).fetchone()[0] + finally: + return_db(db) + progress = get_setting("reindex_progress", "") + status_html = "" + if progress: + status_html = f'

Reindex in progress: {esc(progress)}

' + elif _reindex_thread and _reindex_thread.is_alive(): + status_html = '

Reindex running...

' + return _respond( + f"

semantic search index

" + f"

{pages_with_chunks} of {total_pages} pages have embeddings.

" + f'{status_html}' + f'
' + f'{_csrf_field()}' + f'' + f'
' + f'

back to search

' + ) + + +def handle_reindex_submit(body): + global _reindex_thread + if _reindex_thread and _reindex_thread.is_alive(): + return handle_reindex_form() + + def _run(): + try: + from embeddings import reindex_all + def progress(current, total): + set_setting("reindex_progress", f"{current}/{total}") + reindex_all(progress_callback=progress) + except Exception: + pass + finally: + set_setting("reindex_progress", "") + + _reindex_thread = threading.Thread(target=_run, daemon=True) + _reindex_thread.start() + return _redirect("/reindex") + + # --- Dispatcher --- @@ -1027,6 +1168,8 @@ def _dispatch_inner(data): elif path.startswith("/tags/"): tag_name = unquote(path[len("/tags/"):]) return handle_tag_browse(tag_name, query) if tag_name else _error(400) + elif path == "/reindex": + return handle_reindex_form() elif path == "/api/sites": return handle_api_sites(query) elif path == "/subscriptions": @@ -1052,6 +1195,8 @@ def _dispatch_inner(data): return handle_style_form("Template reset to default.") elif path == "/import": return handle_import_submit(body) + elif path == "/reindex": + return handle_reindex_submit(body) elif path == "/subscriptions/add": return handle_subscription_add(body) elif path == "/subscriptions/pick": diff --git a/requirements.txt b/requirements.txt index f63da5d..121fd1f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,8 @@ requests beautifulsoup4 rns +onnxruntime +tokenizers +hnswlib +numpy +huggingface_hub From fa4a833f904defd06faaea9d6512ae2eb4e7ad4e Mon Sep 17 00:00:00 2001 From: blankie Date: Fri, 27 Mar 2026 10:59:37 -0700 Subject: [PATCH 08/80] added junimo theme, bumped browse to 50 --- app.py | 2 +- handlers.py | 20 +- themes/junimo.html | 1625 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1637 insertions(+), 10 deletions(-) create mode 100644 themes/junimo.html diff --git a/app.py b/app.py index e3422d9..104df32 100644 --- a/app.py +++ b/app.py @@ -4,7 +4,7 @@ import threading import RNS from http.server import HTTPServer -from db import init_db, set_setting +from db import init_db, get_setting, set_setting from handlers import dispatch_request from gateway import GatewayState, GatewayHandler, GATEWAY_PORT diff --git a/handlers.py b/handlers.py index abd0d13..2f6f31f 100644 --- a/handlers.py +++ b/handlers.py @@ -116,6 +116,7 @@ def _error(status): PER_PAGE = 10 +BROWSE_PER_PAGE = 50 def _paginate(query, key="p"): @@ -126,10 +127,11 @@ def _paginate(query, key="p"): return max(1, page) -def _page_nav(page, total, base_url): - if total <= PER_PAGE: +def _page_nav(page, total, base_url, per_page=None): + per_page = per_page or PER_PAGE + if total <= per_page: return "" - total_pages = (total + PER_PAGE - 1) // PER_PAGE + total_pages = (total + per_page - 1) // per_page sep = "&" if "?" in base_url else "?" parts = [] if page > 1: @@ -377,13 +379,13 @@ def handle_add_submit(body): def handle_pages(query=None): page = _paginate(query or {}) - offset = (page - 1) * PER_PAGE + offset = (page - 1) * BROWSE_PER_PAGE db = get_db() try: total = db.execute("SELECT count(*) FROM pages").fetchone()[0] rows = db.execute( "SELECT id, url, title, note FROM pages ORDER BY id DESC LIMIT ? OFFSET ?", - (PER_PAGE, offset), + (BROWSE_PER_PAGE, offset), ).fetchall() items = "" for r in rows: @@ -404,7 +406,7 @@ def handle_pages(query=None): return _respond( f"

indexed pages ({total})

" f"
    {items}
" - f'{_page_nav(page, total, "/pages")}' + f'{_page_nav(page, total, "/pages", BROWSE_PER_PAGE)}' f'

export | import

' f'back' ) @@ -678,7 +680,7 @@ def handle_tags(): def handle_tag_browse(tag_name, query=None): page = _paginate(query or {}) - offset = (page - 1) * PER_PAGE + offset = (page - 1) * BROWSE_PER_PAGE db = get_db() try: total = db.execute( @@ -690,7 +692,7 @@ def handle_tag_browse(tag_name, query=None): "JOIN page_tags pt ON p.id = pt.page_id " "JOIN tags t ON t.id = pt.tag_id " "WHERE t.name = ? ORDER BY p.id DESC LIMIT ? OFFSET ?", - (tag_name, PER_PAGE, offset), + (tag_name, BROWSE_PER_PAGE, offset), ).fetchall() items = "" for r in rows: @@ -707,7 +709,7 @@ def handle_tag_browse(tag_name, query=None): f'

tag: {esc(tag_name)}

' f'

{total} page(s)

' f'
    {items}
' - f'{_page_nav(page, total, f"/tags/{esc(tag_name)}")}' + f'{_page_nav(page, total, f"/tags/{esc(tag_name)}", BROWSE_PER_PAGE)}' f'all tags | back' ) diff --git a/themes/junimo.html b/themes/junimo.html new file mode 100644 index 0000000..25688b7 --- /dev/null +++ b/themes/junimo.html @@ -0,0 +1,1625 @@ + + + + + + + + + + + + +
+
+
+ +
+
+
+
+
+
+ +
+
+
+ G +
+ +
+
+
+
+ E + +
+
+
+
+ +
+
+ {{content}} +
+
+
curated by hand · shared over mesh
+
+
+
+ + + From 36676806d7557f56fae0b470e76fda970cfd353a Mon Sep 17 00:00:00 2001 From: blankie Date: Fri, 27 Mar 2026 14:08:04 -0700 Subject: [PATCH 09/80] fixed reindex, preserved summaries Previously reindex skipped pages that already had chunks, leaving stale embeddings in place. It also overwrote good meta description summaries with auto-generated ones. Now it clears all chunks first so everything is re-embedded, and only generates summaries for pages missing one. --- embeddings.py | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/embeddings.py b/embeddings.py index 5575c29..8ad1362 100644 --- a/embeddings.py +++ b/embeddings.py @@ -506,21 +506,24 @@ def hybrid_search(query_text, bm25_ranked_ids, limit=10, db=None, use_reranker=F # --------------------------------------------------------------------------- def reindex_all(db=None, progress_callback=None): - """Embed all pages that don't yet have chunks. Also generates missing summaries. Rebuilds HNSW index.""" + """Re-embed all pages and regenerate all summaries. Rebuilds HNSW index.""" from db import get_db, return_db, _generate_summary own_db = db is None if own_db: db = get_db() try: + # Clear existing chunks so everything is regenerated + db.execute("DELETE FROM chunks") + db.commit() + rows = db.execute( - "SELECT p.id, p.title, p.body, p.summary FROM pages p " - "WHERE p.id NOT IN (SELECT DISTINCT page_id FROM chunks WHERE page_id IS NOT NULL)" + "SELECT p.id, p.title, p.body, p.summary FROM pages p" ).fetchall() total = len(rows) for i, row in enumerate(rows): store_embeddings(row["id"], row["title"], row["body"], db) - # Generate summary if missing + # Only regenerate summary if missing if not row["summary"]: summary = _generate_summary(row["title"], row["body"]) db.execute("UPDATE pages SET summary = ? WHERE id = ?", (summary, row["id"])) @@ -528,20 +531,9 @@ def reindex_all(db=None, progress_callback=None): if progress_callback: progress_callback(i + 1, total) - # Generate summaries for pages that already have chunks but no summary - no_summary = db.execute( - "SELECT id, title, body FROM pages WHERE summary = '' OR summary IS NULL" - ).fetchall() - for row in no_summary: - summary = _generate_summary(row["title"], row["body"]) - db.execute("UPDATE pages SET summary = ? WHERE id = ?", (summary, row["id"])) - if no_summary: - db.commit() - # Also handle remote pages remote_rows = db.execute( - "SELECT rp.id, rp.title, rp.note FROM remote_pages rp " - "WHERE rp.id NOT IN (SELECT DISTINCT remote_page_id FROM chunks WHERE remote_page_id IS NOT NULL)" + "SELECT rp.id, rp.title, rp.note FROM remote_pages rp" ).fetchall() for rp in remote_rows: From 5d6c75a79a36076e4be6fdee64ed5362a2996183 Mon Sep 17 00:00:00 2001 From: blankie Date: Fri, 27 Mar 2026 14:18:54 -0700 Subject: [PATCH 10/80] stripped noscript tags from pages Lemmy and other JS-heavy sites include noscript fallback text like "Javascript is disabled" that pollutes the stored body text and generated snippets/summaries. --- db.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db.py b/db.py index 6b225a2..a6d8008 100644 --- a/db.py +++ b/db.py @@ -328,7 +328,7 @@ def fetch_page(url): if og_tag and og_tag.get("content"): meta_desc = og_tag["content"].strip() - for tag in soup(["script", "style", "nav", "footer", "header"]): + for tag in soup(["script", "style", "nav", "footer", "header", "noscript"]): tag.decompose() title = soup.title.string.strip() if soup.title and soup.title.string else url body = soup.get_text(separator=" ", strip=True) From 0495f81a84d7429864ba66c4e8713a24d5c3cb3c Mon Sep 17 00:00:00 2001 From: blankie Date: Fri, 27 Mar 2026 15:44:07 -0700 Subject: [PATCH 11/80] improved snippet extraction (heuristic) - Case-insensitive meta description extraction (fixes sites like Lemmy with capitalized "Description" meta name) - Strip aside and noscript tags for cleaner body text - Extract paragraph text separately for better sentence quality - Prefer sentences mentioning the site name, then first quality paragraph, then title as fallback - Skip meta descriptions under 20 chars (e.g. just "Lemmy") - Remove embedding/centroid dependency from summary generation --- db.py | 129 +++++++++++++++++++++++++++++++--------------------------- 1 file changed, 69 insertions(+), 60 deletions(-) diff --git a/db.py b/db.py index a6d8008..f31473f 100644 --- a/db.py +++ b/db.py @@ -317,88 +317,97 @@ def fetch_page(url): label = a.get_text(strip=True) or href links.append((href, label[:200])) - # Extract meta description before stripping tags + # Extract meta description before stripping tags (case-insensitive) meta_desc = "" - meta_tag = soup.find("meta", attrs={"name": "description"}) - if meta_tag and meta_tag.get("content"): - meta_desc = meta_tag["content"].strip() - if not meta_desc: - # Try og:description as fallback - og_tag = soup.find("meta", attrs={"property": "og:description"}) - if og_tag and og_tag.get("content"): - meta_desc = og_tag["content"].strip() + for m in soup.find_all("meta"): + name = (m.get("name") or "").lower() + prop = (m.get("property") or "").lower() + content = (m.get("content") or "").strip() + if not content: + continue + if name == "description" and len(content) > len(meta_desc): + meta_desc = content + elif prop == "og:description" and not meta_desc: + meta_desc = content - for tag in soup(["script", "style", "nav", "footer", "header", "noscript"]): + for tag in soup(["script", "style", "nav", "footer", "header", "noscript", "aside"]): tag.decompose() title = soup.title.string.strip() if soup.title and soup.title.string else url + + # Extract paragraph text for better summary generation + paragraphs = [] + for p in soup.find_all("p"): + text = p.get_text(strip=True) + if len(text) >= 40: + paragraphs.append(text) + body = soup.get_text(separator=" ", strip=True) - return title, body, links, meta_desc + return title, body, links, meta_desc, paragraphs -def _generate_summary(title, body): - """Generate a summary from body text using centroid extractive method. +def _generate_summary(title, body, paragraphs=None): + """Generate a summary by extracting the best sentence from the page. - Filters out UI debris, embeds remaining sentences, finds the one - closest to the centroid (most representative of the page). + Priority: sentence mentioning the site name > first paragraph sentence + > first body sentence > title. """ import re - # Split on sentence boundaries - raw = re.split(r'(?<=[.!?])\s+', body) - sentences = [] noise_patterns = re.compile( r'arrow-|fedilink|message-square|link-external|' r'skip to|cookie|subscribe|sign up|log in|' r'privacy policy|terms of|©|\bads?\b', re.IGNORECASE ) - for s in raw: - s = s.strip() - if len(s) < 40: - continue - words = s.split() - if len(words) < 7: - continue - # Skip if mostly non-alpha (icons, arrows, encoded chars) - alpha_chars = sum(1 for c in s if c.isalpha() or c == ' ') - if alpha_chars < len(s) * 0.6: - continue - # Skip nav/menu patterns - if s.count('|') > 2 or s.count('·') > 2 or s.count('►') > 0: - continue - # Skip UI debris - if noise_patterns.search(s): - continue - sentences.append(s) + + def _filter_sentences(raw): + result = [] + for s in raw: + s = s.strip() + if len(s) < 40 or len(s.split()) < 7: + continue + alpha_chars = sum(1 for c in s if c.isalpha() or c == ' ') + if alpha_chars < len(s) * 0.6: + continue + if s.count('|') > 2 or s.count('·') > 2 or s.count('►') > 0: + continue + if noise_patterns.search(s): + continue + result.append(s) + return result + + # Prefer sentences from

tags (actual content, not UI) + sentences = [] + if paragraphs: + raw = [] + for p in paragraphs: + raw.extend(re.split(r'(?<=[.!?])\s+', p)) + sentences = _filter_sentences(raw) + + # Fall back to full body text + if not sentences: + raw = re.split(r'(?<=[.!?])\s+', body) + sentences = _filter_sentences(raw) if not sentences: - # Last resort: take the first chunk of body that looks like prose - clean = re.sub(r'\s+', ' ', body).strip() - return clean[:160] + "..." if len(clean) > 160 else clean - if len(sentences) == 1: - s = sentences[0] - return s[:200] if len(s) > 200 else s - try: - from embeddings import embed - import numpy as np - embs = embed(sentences[:50]) # cap to avoid embedding too many - centroid = embs.mean(axis=0, keepdims=True) - centroid = centroid / max(np.linalg.norm(centroid), 1e-12) - scores = (embs @ centroid.T).flatten() - best_idx = int(np.argmax(scores)) - result = sentences[best_idx] - # Try to add a second sentence if it fits - if best_idx + 1 < len(sentences) and len(result) + len(sentences[best_idx + 1]) + 1 <= 200: - result += " " + sentences[best_idx + 1] - return result[:200] if len(result) > 200 else result - except Exception: - return sentences[0][:200] + return title[:200] if title else "" + + # Prefer a sentence that mentions the site name + if title: + title_words = [w.lower() for w in re.split(r'\W+', title) if len(w) >= 3] + for s in sentences: + s_lower = s.lower() + if sum(1 for w in title_words if w in s_lower) >= max(1, len(title_words) // 2): + return s[:200] + + # Otherwise use the first quality sentence + return sentences[0][:200] def index_url(url, note=""): url = clean_url(url) - title, body, links, meta_desc = fetch_page(url) - # Use meta description if available, otherwise generate from body - summary = meta_desc if meta_desc else _generate_summary(title, body) + title, body, links, meta_desc, paragraphs = fetch_page(url) + # Use meta description if available and meaningful, otherwise generate from body + summary = meta_desc if meta_desc and len(meta_desc) > 20 else _generate_summary(title, body, paragraphs) db = get_db() try: now = __import__("datetime").datetime.now().strftime("%Y-%m-%dT%H:%M:%S") From 821e45364b73a9f1fb6e31da681bdc75199c908d Mon Sep 17 00:00:00 2001 From: blankie Date: Sat, 28 Mar 2026 20:58:04 -0700 Subject: [PATCH 12/80] made semantic search optional, use meta snippets - Add semantic_search setting to toggle AI-powered search on/off - Skip embedding generation, hybrid search, and model preloading when disabled - Use site owner's meta description as snippet instead of heuristic extraction - Remove _generate_summary() and snippet() - no more generated snippets - Show reranker/reindex controls grayed out when semantic search is off - AI dependencies (onnxruntime, hnswlib, etc.) are now fully optional --- app.py | 3 ++ db.py | 81 ++++++---------------------------------------- embeddings.py | 7 +--- handlers.py | 89 +++++++++++++++++++++++++++++++++------------------ templates.py | 8 ----- 5 files changed, 70 insertions(+), 118 deletions(-) diff --git a/app.py b/app.py index 104df32..dba9695 100644 --- a/app.py +++ b/app.py @@ -74,6 +74,9 @@ def ensure_rns_config(config_dir): def _preload_embeddings(): """Pre-load the embedding model and build the HNSW index in background.""" + if get_setting("semantic_search", "1") != "1": + print("Semantic search disabled.") + return try: from embeddings import _get_session, _get_reranker, build_index _get_session() # downloads model on first run, loads ONNX session diff --git a/db.py b/db.py index f31473f..065d65d 100644 --- a/db.py +++ b/db.py @@ -334,80 +334,16 @@ def fetch_page(url): tag.decompose() title = soup.title.string.strip() if soup.title and soup.title.string else url - # Extract paragraph text for better summary generation - paragraphs = [] - for p in soup.find_all("p"): - text = p.get_text(strip=True) - if len(text) >= 40: - paragraphs.append(text) - body = soup.get_text(separator=" ", strip=True) - return title, body, links, meta_desc, paragraphs + return title, body, links, meta_desc -def _generate_summary(title, body, paragraphs=None): - """Generate a summary by extracting the best sentence from the page. - - Priority: sentence mentioning the site name > first paragraph sentence - > first body sentence > title. - """ - import re - noise_patterns = re.compile( - r'arrow-|fedilink|message-square|link-external|' - r'skip to|cookie|subscribe|sign up|log in|' - r'privacy policy|terms of|©|\bads?\b', - re.IGNORECASE - ) - - def _filter_sentences(raw): - result = [] - for s in raw: - s = s.strip() - if len(s) < 40 or len(s.split()) < 7: - continue - alpha_chars = sum(1 for c in s if c.isalpha() or c == ' ') - if alpha_chars < len(s) * 0.6: - continue - if s.count('|') > 2 or s.count('·') > 2 or s.count('►') > 0: - continue - if noise_patterns.search(s): - continue - result.append(s) - return result - - # Prefer sentences from

tags (actual content, not UI) - sentences = [] - if paragraphs: - raw = [] - for p in paragraphs: - raw.extend(re.split(r'(?<=[.!?])\s+', p)) - sentences = _filter_sentences(raw) - - # Fall back to full body text - if not sentences: - raw = re.split(r'(?<=[.!?])\s+', body) - sentences = _filter_sentences(raw) - - if not sentences: - return title[:200] if title else "" - - # Prefer a sentence that mentions the site name - if title: - title_words = [w.lower() for w in re.split(r'\W+', title) if len(w) >= 3] - for s in sentences: - s_lower = s.lower() - if sum(1 for w in title_words if w in s_lower) >= max(1, len(title_words) // 2): - return s[:200] - - # Otherwise use the first quality sentence - return sentences[0][:200] - def index_url(url, note=""): url = clean_url(url) - title, body, links, meta_desc, paragraphs = fetch_page(url) + title, body, links, meta_desc = fetch_page(url) # Use meta description if available and meaningful, otherwise generate from body - summary = meta_desc if meta_desc and len(meta_desc) > 20 else _generate_summary(title, body, paragraphs) + summary = meta_desc if meta_desc and len(meta_desc) > 20 else "" db = get_db() try: now = __import__("datetime").datetime.now().strftime("%Y-%m-%dT%H:%M:%S") @@ -425,11 +361,12 @@ def index_url(url, note=""): (page_id, href, label), ) db.commit() - try: - from embeddings import store_embeddings - store_embeddings(page_id, title, body, db) - except Exception: - pass # embedding generation is best-effort + if get_setting("semantic_search", "1") == "1": + try: + from embeddings import store_embeddings + store_embeddings(page_id, title, body, db) + except Exception: + pass # embedding generation is best-effort finally: return_db(db) return title diff --git a/embeddings.py b/embeddings.py index 8ad1362..aa6a4ff 100644 --- a/embeddings.py +++ b/embeddings.py @@ -507,7 +507,7 @@ def hybrid_search(query_text, bm25_ranked_ids, limit=10, db=None, use_reranker=F def reindex_all(db=None, progress_callback=None): """Re-embed all pages and regenerate all summaries. Rebuilds HNSW index.""" - from db import get_db, return_db, _generate_summary + from db import get_db, return_db own_db = db is None if own_db: db = get_db() @@ -523,11 +523,6 @@ def reindex_all(db=None, progress_callback=None): total = len(rows) for i, row in enumerate(rows): store_embeddings(row["id"], row["title"], row["body"], db) - # Only regenerate summary if missing - if not row["summary"]: - summary = _generate_summary(row["title"], row["body"]) - db.execute("UPDATE pages SET summary = ? WHERE id = ?", (summary, row["id"])) - db.commit() if progress_callback: progress_callback(i + 1, total) diff --git a/handlers.py b/handlers.py index 2f6f31f..484a5ca 100644 --- a/handlers.py +++ b/handlers.py @@ -6,7 +6,7 @@ from datetime import datetime from urllib.parse import unquote from db import get_db, return_db, get_setting, set_setting, get_site_name, index_url, clean_url -from templates import esc, snippet, wrap_page, DEFAULT_TEMPLATE +from templates import esc, wrap_page, DEFAULT_TEMPLATE from rns_client import fetch_remote_sites _request_local = threading.local() @@ -205,13 +205,16 @@ def handle_search(query): # Hybrid search: merge BM25 + semantic via RRF bm25_ids = [r["id"] for r in bm25_rows] chunk_snippets = {} # page_id -> best chunk text - try: - from embeddings import hybrid_search - use_reranker = get_setting("use_reranker", "1") == "1" - fused = hybrid_search(q, bm25_ids, limit=100, db=db, use_reranker=use_reranker) - fused_ids = [pid for pid, _ in fused] - chunk_snippets = {pid: text for pid, text in fused if text} - except Exception: + if get_setting("semantic_search", "1") == "1": + try: + from embeddings import hybrid_search + use_reranker = get_setting("use_reranker", "1") == "1" + fused = hybrid_search(q, bm25_ids, limit=100, db=db, use_reranker=use_reranker) + fused_ids = [pid for pid, _ in fused] + chunk_snippets = {pid: text for pid, text in fused if text} + except Exception: + fused_ids = bm25_ids + else: fused_ids = bm25_ids total_results = len(fused_ids) @@ -239,13 +242,12 @@ def handle_search(query): if tags: tag_links = " ".join(f'[{esc(t)}]' for t in tags) tags_html = f'

{tag_links}
' - # Use page summary as snippet (meta description or centroid sentence) - snip = r["summary"] if r["summary"] else snippet(r["body"], q) + snip_html = f'
{esc(r["summary"])}' if r["summary"] else "" result_html += ( f'
' f'{esc(r["title"])}
' - f'{esc(r["url"])}
' - f'{esc(snip)}' + f'{esc(r["url"])}' + f'{snip_html}' f'{note_html}{tags_html}' f'
' ) @@ -557,8 +559,12 @@ def handle_style_form(msg=""): name = get_site_name() sharing = get_setting("sharing_enabled", "0") checked = " checked" if sharing == "1" else "" + semantic = get_setting("semantic_search", "1") + semantic_checked = " checked" if semantic == "1" else "" reranker = get_setting("use_reranker", "1") reranker_checked = " checked" if reranker == "1" else "" + disabled = "" if semantic == "1" else " disabled" + dimmed = ' style="opacity:0.4"' if semantic != "1" else "" return _respond( f"

customize

" f"

name your search engine

" @@ -569,9 +575,18 @@ def handle_style_form(msg=""): f'

" f"

search

" - f'
" + f"

ai

" + f'
" + f"Requires onnxruntime, tokenizers, hnswlib. Downloads ~30MB of models on first use.

" + f'
' + f'
" f"Uses a 22MB model. Adds ~50ms per search. Disable for faster results.

" + f'manage semantic index

' + f"
" f"

custom html

" f"

Edit the full page template. Use {esc('{{content}}')} " f"where page content should appear.

" @@ -596,10 +611,12 @@ def handle_style_submit(body): template = body.get("template", [""])[0].replace("\r\n", "\n").replace("\r", "\n") name = body.get("site_name", ["tinyweb"])[0].strip() sharing = "1" if body.get("sharing_enabled") else "0" + semantic = "1" if body.get("semantic_search") else "0" reranker = "1" if body.get("use_reranker") else "0" set_setting("custom_template", template if template.strip() != DEFAULT_TEMPLATE.strip() else "") set_setting("site_name", name or "tinyweb") set_setting("sharing_enabled", sharing) + set_setting("semantic_search", semantic) set_setting("use_reranker", reranker) return handle_style_form("Saved.") @@ -975,15 +992,16 @@ def handle_subscription_sync(sub_id): (sub_id, s["url"], s["title"], s.get("note", ""), tags_str), ) # Embed remote page for semantic search - try: - from embeddings import store_remote_embeddings - rp_id = db.execute( - "SELECT id FROM remote_pages WHERE subscription_id = ? AND url = ?", - (sub_id, s["url"]), - ).fetchone()["id"] - store_remote_embeddings(rp_id, s["title"], s.get("note", ""), db) - except Exception: - pass + if get_setting("semantic_search", "1") == "1": + try: + from embeddings import store_remote_embeddings + rp_id = db.execute( + "SELECT id FROM remote_pages WHERE subscription_id = ? AND url = ?", + (sub_id, s["url"]), + ).fetchone()["id"] + store_remote_embeddings(rp_id, s["title"], s.get("note", ""), db) + except Exception: + pass synced += 1 except Exception: pass @@ -1050,15 +1068,16 @@ def handle_subscription_syncall(): "ON CONFLICT(subscription_id, url) DO UPDATE SET title=excluded.title, note=excluded.note, tags=excluded.tags", (sub["id"], s["url"], s["title"], s.get("note", ""), tags_str), ) - try: - from embeddings import store_remote_embeddings - rp_id = db.execute( - "SELECT id FROM remote_pages WHERE subscription_id = ? AND url = ?", - (sub["id"], s["url"]), - ).fetchone()["id"] - store_remote_embeddings(rp_id, s["title"], s.get("note", ""), db) - except Exception: - pass + if get_setting("semantic_search", "1") == "1": + try: + from embeddings import store_remote_embeddings + rp_id = db.execute( + "SELECT id FROM remote_pages WHERE subscription_id = ? AND url = ?", + (sub["id"], s["url"]), + ).fetchone()["id"] + store_remote_embeddings(rp_id, s["title"], s.get("note", ""), db) + except Exception: + pass except Exception: pass now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") @@ -1079,6 +1098,12 @@ _reindex_thread = None def handle_reindex_form(): + if get_setting("semantic_search", "1") != "1": + return _respond( + f"

semantic search index

" + f"

Semantic search is disabled. Enable it in settings to use embeddings.

" + f'

back to search

' + ) db = get_db() try: total_pages = db.execute("SELECT count(*) FROM pages").fetchone()[0] diff --git a/templates.py b/templates.py index 372e736..48beace 100644 --- a/templates.py +++ b/templates.py @@ -6,14 +6,6 @@ def esc(s): return html.escape(str(s)) -def snippet(text, query, ctx=80): - pos = text.lower().find(query.lower()) - if pos == -1: - return text[:200] - start = max(0, pos - ctx) - end = min(len(text), pos + len(query) + ctx) - return ("..." if start > 0 else "") + text[start:end] + ("..." if end < len(text) else "") - DEFAULT_TEMPLATE = "\n\n\n\n{{content}}\n\n" From 2aa24b812d1235d8075459fee1952c48ec44c8b8 Mon Sep 17 00:00:00 2001 From: blankie Date: Sat, 28 Mar 2026 21:24:10 -0700 Subject: [PATCH 13/80] added manual URL entry --- db.py | 20 +++++++++++++ handlers.py | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 99 insertions(+), 2 deletions(-) diff --git a/db.py b/db.py index 065d65d..a0a3580 100644 --- a/db.py +++ b/db.py @@ -20,6 +20,22 @@ BLOCKED_NETWORKS = [ ] +def _is_blocked_response(html, status_code): + """Check if response is a CDN challenge/block page.""" + if status_code == 403: + return True + html_lower = html.lower() + if "just a moment" in html_lower or "cloudflare" in html_lower: + return True + if "enable javascript and cookies" in html_lower: + return True + if "request rejected" in html_lower: + return True + if "access denied" in html_lower: + return True + return False + + def _validate_url_target(url): """Resolve hostname and block private/internal IPs to prevent SSRF.""" parsed = urlparse(url) @@ -281,6 +297,10 @@ def get_site_name(): def fetch_page(url): _validate_url_target(url) resp = requests.get(url, timeout=10, headers={"User-Agent": "TinyWeb/1.0"}, allow_redirects=False) + + if _is_blocked_response(resp.text, resp.status_code): + raise Exception(f"Site blocks automated access: {resp.status_code}") + # Follow redirects manually, re-validating each target max_redirects = 5 while resp.is_redirect and max_redirects > 0: diff --git a/handlers.py b/handlers.py index 484a5ca..5903d0b 100644 --- a/handlers.py +++ b/handlers.py @@ -357,10 +357,13 @@ def handle_add_submit(body): url = clean_url(body.get("url", [""])[0].strip()) note = body.get("note", [""])[0].strip() tags = body.get("tags", [""])[0].strip() + if not url: return handle_add_form("URL is required.") if not url.startswith(("http://", "https://")): return handle_add_form("URL must start with http:// or https://") + + # Try auto-index first try: title = index_url(url, note) if tags: @@ -373,10 +376,82 @@ def handle_add_submit(body): finally: return_db(db) return handle_add_form(f'Indexed: {esc(title)}') + except ValueError as e: return handle_add_form(f"Error: {esc(str(e))}") - except Exception: - return handle_add_form("Error: could not fetch or index that URL.") + + except Exception as e: + error_msg = str(e).lower() + # Check if it's a block response + if "block" in error_msg or "cloudflare" in error_msg or "403" in error_msg: + # Show manual entry form for blocked sites + return _respond( + f"

add url (manual entry)

" + f"

{esc(url)} blocks automated access. " + f"You can still save it manually:

" + f'
' + f'{_csrf_field()}' + f'' + f'' + f'' + f'
' + f'

' + f'
' + f'

' + f'' + f"
" + f'back' + ) + return handle_add_form(f"Error: could not fetch or index that URL. {esc(str(e)[:100])}") + + +def handle_add_manual_submit(body): + url = clean_url(body.get("url", [""])[0].strip()) + note = body.get("note", [""])[0].strip() + tags = body.get("tags", [""])[0].strip() + manual_title = body.get("manual_title", [""])[0].strip() + manual_desc = body.get("manual_description", [""])[0].strip() + + if not url: + return handle_add_form("URL is required.") + if not manual_title or not manual_desc: + return handle_add_form("Title and description are required for manual entry.") + + db = get_db() + try: + now = __import__("datetime").datetime.now().strftime("%Y-%m-%dT%H:%M:%S") + + # Insert the page + db.execute( + "INSERT INTO pages (url, title, body, note, last_modified, summary) VALUES (?, ?, ?, ?, ?, ?) " + "ON CONFLICT(url) DO UPDATE SET title=excluded.title, body=excluded.body, " + "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary", + (url, manual_title, manual_desc, note, now, manual_desc[:200]), + ) + + # Get the page ID + page_id = db.execute("SELECT id FROM pages WHERE url = ?", (url,)).fetchone()[0] + + # Add tags if provided + if tags: + _set_page_tags(page_id, tags, db) + + db.commit() + + # Generate embeddings for this page (if semantic search is enabled) + if get_setting("semantic_search", "1") == "1": + try: + from embeddings import store_embeddings + # Pass the page_id, title, description, and db connection + store_embeddings(page_id, manual_title, manual_desc, db) + db.commit() + except Exception as e: + # Log error but don't fail the whole operation + print(f"Error generating embeddings: {e}") + + return handle_add_form(f'Added manually: {esc(manual_title)}') + finally: + return_db(db) def handle_pages(query=None): @@ -1209,6 +1284,8 @@ def _dispatch_inner(data): return _respond("

403 Forbidden

Invalid or missing CSRF token.

", status=403) if path == "/add": return handle_add_submit(body) + elif path == "/add/manual": + return handle_add_manual_submit(body) elif path.startswith("/edit/"): pid = extract_id("/edit/") return handle_edit_submit(pid, body) if pid is not None else _error(400) From 63f7d401cd0b32c653d744b781228cd30ed4ccc7 Mon Sep 17 00:00:00 2001 From: blankie Date: Mon, 30 Mar 2026 22:36:58 +0000 Subject: [PATCH 14/80] added reticulum hash option to add page --- db.py | 17 +++++++++++------ handlers.py | 46 +++++++++++++++++++++++++++++++++------------- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/db.py b/db.py index a0a3580..4943855 100644 --- a/db.py +++ b/db.py @@ -131,7 +131,8 @@ def init_db(): " title TEXT," " body TEXT," " note TEXT DEFAULT ''," - " last_modified TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%S','now'))" + " last_modified TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%S','now'))," + " reticulum_dest TEXT DEFAULT ''" ")" ) db.execute( @@ -247,6 +248,11 @@ def init_db(): db.execute("ALTER TABLE pages ADD COLUMN summary TEXT DEFAULT ''") db.commit() + # Migrate pages: add reticulum_dest column if missing + if "reticulum_dest" not in page_cols: + db.execute("ALTER TABLE pages ADD COLUMN reticulum_dest TEXT DEFAULT ''") + db.commit() + # Chunks table for semantic search embeddings db.execute( "CREATE TABLE IF NOT EXISTS chunks (" @@ -359,19 +365,18 @@ def fetch_page(url): -def index_url(url, note=""): +def index_url(url, note="", reticulum_dest=""): url = clean_url(url) title, body, links, meta_desc = fetch_page(url) - # Use meta description if available and meaningful, otherwise generate from body summary = meta_desc if meta_desc and len(meta_desc) > 20 else "" db = get_db() try: now = __import__("datetime").datetime.now().strftime("%Y-%m-%dT%H:%M:%S") db.execute( - "INSERT INTO pages (url, title, body, note, last_modified, summary) VALUES (?, ?, ?, ?, ?, ?) " + "INSERT INTO pages (url, title, body, note, last_modified, summary, reticulum_dest) VALUES (?, ?, ?, ?, ?, ?, ?) " "ON CONFLICT(url) DO UPDATE SET title=excluded.title, body=excluded.body, " - "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary", - (url, title, body, note, now, summary), + "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary, reticulum_dest=excluded.reticulum_dest", + (url, title, body, note, now, summary, reticulum_dest), ) page_id = db.execute("SELECT id FROM pages WHERE url = ?", (url,)).fetchone()[0] db.execute("DELETE FROM links WHERE page_id = ?", (page_id,)) diff --git a/handlers.py b/handlers.py index 5903d0b..a5e66d4 100644 --- a/handlers.py +++ b/handlers.py @@ -341,9 +341,12 @@ def handle_search(query): def handle_add_form(msg=""): return _respond( f"

add url

" + f"

Add a site via URL or Reticulum destination hash

" f'
' f'{_csrf_field()}' - f'

' + f'
' + f'or
' + f'

' f'

' f'

' f'' @@ -357,15 +360,25 @@ def handle_add_submit(body): url = clean_url(body.get("url", [""])[0].strip()) note = body.get("note", [""])[0].strip() tags = body.get("tags", [""])[0].strip() + reticulum_dest = body.get("reticulum_dest", [""])[0].strip().replace("<", "").replace(">", "") - if not url: - return handle_add_form("URL is required.") - if not url.startswith(("http://", "https://")): + if reticulum_dest and url: + return handle_add_form("Please provide either a URL or a Reticulum destination hash, not both.") + + if not url and not reticulum_dest: + return handle_add_form("URL or Reticulum destination hash is required.") + + if reticulum_dest and (len(reticulum_dest) != 32 or not all(c in "0123456789abcdefABCDEF" for c in reticulum_dest)): + return handle_add_form("Invalid reticulum destination hash. Must be 32 hex characters.") + + if url and not url.startswith(("http://", "https://")): return handle_add_form("URL must start with http:// or https://") - # Try auto-index first + if reticulum_dest and not url: + url = f"reticulum:{reticulum_dest}" + try: - title = index_url(url, note) + title = index_url(url, note, reticulum_dest) if tags: db = get_db() try: @@ -375,7 +388,9 @@ def handle_add_submit(body): db.commit() finally: return_db(db) - return handle_add_form(f'Indexed: {esc(title)}') + + display_url = url if url.startswith("http") else reticulum_dest + return handle_add_form(f'Indexed: {esc(display_url)}') except ValueError as e: return handle_add_form(f"Error: {esc(str(e))}") @@ -394,6 +409,7 @@ def handle_add_submit(body): f'' f'' f'' + f'' f'
' f'

' f'
' @@ -409,11 +425,16 @@ def handle_add_manual_submit(body): url = clean_url(body.get("url", [""])[0].strip()) note = body.get("note", [""])[0].strip() tags = body.get("tags", [""])[0].strip() + reticulum_dest = body.get("reticulum_dest", [""])[0].strip() manual_title = body.get("manual_title", [""])[0].strip() manual_desc = body.get("manual_description", [""])[0].strip() - if not url: - return handle_add_form("URL is required.") + if not url and not reticulum_dest: + return handle_add_form("URL or Reticulum destination hash is required.") + + if not url and reticulum_dest: + url = f"reticulum:{reticulum_dest}" + if not manual_title or not manual_desc: return handle_add_form("Title and description are required for manual entry.") @@ -421,12 +442,11 @@ def handle_add_manual_submit(body): try: now = __import__("datetime").datetime.now().strftime("%Y-%m-%dT%H:%M:%S") - # Insert the page db.execute( - "INSERT INTO pages (url, title, body, note, last_modified, summary) VALUES (?, ?, ?, ?, ?, ?) " + "INSERT INTO pages (url, title, body, note, last_modified, summary, reticulum_dest) VALUES (?, ?, ?, ?, ?, ?, ?) " "ON CONFLICT(url) DO UPDATE SET title=excluded.title, body=excluded.body, " - "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary", - (url, manual_title, manual_desc, note, now, manual_desc[:200]), + "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary, reticulum_dest=excluded.reticulum_dest", + (url, manual_title, manual_desc, note, now, manual_desc[:200], reticulum_dest), ) # Get the page ID From c89e63f88db65d8e9c203f69972e631eedef4dda Mon Sep 17 00:00:00 2001 From: blankie Date: Mon, 30 Mar 2026 22:48:45 +0000 Subject: [PATCH 15/80] added dropdown to switch add/subscribe --- handlers.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/handlers.py b/handlers.py index a5e66d4..0d6135b 100644 --- a/handlers.py +++ b/handlers.py @@ -338,12 +338,29 @@ def handle_search(query): ) -def handle_add_form(msg=""): +def handle_add_form(msg="", action_type="index"): + if action_type == "subscribe": + return _respond( + f"

subscribe

" + f"

Subscribe to a friend's TinyWeb instance to sync their index

" + f'' + f'{_csrf_field()}' + f'

' + f'' + f"" + f"

or add a single site

" + f"

{msg}

" + f'back' + ) return _respond( f"

add url

" f"

Add a site via URL or Reticulum destination hash

" f'
' f'{_csrf_field()}' + f'

' f'
' f'or
' f'

' @@ -351,6 +368,7 @@ def handle_add_form(msg=""): f'

' f'' f"
" + f"

or manage subscriptions

" f"

{msg}

" f'back' ) @@ -901,6 +919,7 @@ def handle_subscriptions(msg=""): f' ' f'' f'' + f'

or subscribe to an instance

' f'

{msg}

' f'
{listing}' f'
back' @@ -1266,7 +1285,8 @@ def _dispatch_inner(data): if path == "/": return handle_search(query) elif path == "/add": - return handle_add_form() + action_type = query.get("type", ["index"])[0] + return handle_add_form(action_type=action_type if action_type == "subscribe" else "index") elif path == "/pages": return handle_pages(query) elif path.startswith("/edit/"): From 74c686632de32015f3cb1d1f1ead767c39d0358e Mon Sep 17 00:00:00 2001 From: blankie Date: Mon, 30 Mar 2026 22:54:29 +0000 Subject: [PATCH 16/80] swapped to radio toggle for URL vs hash --- handlers.py | 101 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 60 insertions(+), 41 deletions(-) diff --git a/handlers.py b/handlers.py index 0d6135b..bc39743 100644 --- a/handlers.py +++ b/handlers.py @@ -354,49 +354,54 @@ def handle_add_form(msg="", action_type="index"): ) return _respond( f"

add url

" - f"

Add a site via URL or Reticulum destination hash

" + f"

Add a site to your index

" f'
' f'{_csrf_field()}' - f'

' - f'
' - f'or
' - f'

' + f'' + f'' + f'' + f'' + f'

' + f'
' + f'

' f'

' f'

' f'' f"
" - f"

or manage subscriptions

" f"

{msg}

" f'back' + f'' ) def handle_add_submit(body): - url = clean_url(body.get("url", [""])[0].strip()) + input_type = body.get("input_type", ["url"])[0] + url = body.get("url", [""])[0].strip() + reticulum_dest = body.get("reticulum_dest", [""])[0].strip().replace("<", "").replace(">", "") note = body.get("note", [""])[0].strip() tags = body.get("tags", [""])[0].strip() - reticulum_dest = body.get("reticulum_dest", [""])[0].strip().replace("<", "").replace(">", "") - if reticulum_dest and url: - return handle_add_form("Please provide either a URL or a Reticulum destination hash, not both.") - - if not url and not reticulum_dest: - return handle_add_form("URL or Reticulum destination hash is required.") - - if reticulum_dest and (len(reticulum_dest) != 32 or not all(c in "0123456789abcdefABCDEF" for c in reticulum_dest)): - return handle_add_form("Invalid reticulum destination hash. Must be 32 hex characters.") - - if url and not url.startswith(("http://", "https://")): - return handle_add_form("URL must start with http:// or https://") - - if reticulum_dest and not url: + if input_type == "url": + if not url: + return handle_add_form("URL is required.") + url = clean_url(url) + if not url.startswith(("http://", "https://")): + return handle_add_form("URL must start with http:// or https://") + else: + if not reticulum_dest: + return handle_add_form("Reticulum destination hash is required.") + if len(reticulum_dest) != 32 or not all(c in "0123456789abcdefABCDEF" for c in reticulum_dest): + return handle_add_form("Invalid reticulum destination hash. Must be 32 hex characters.") url = f"reticulum:{reticulum_dest}" try: - title = index_url(url, note, reticulum_dest) + title = index_url(url, note, reticulum_dest if reticulum_dest else "") if tags: db = get_db() try: @@ -407,8 +412,7 @@ def handle_add_submit(body): finally: return_db(db) - display_url = url if url.startswith("http") else reticulum_dest - return handle_add_form(f'Indexed: {esc(display_url)}') + return handle_add_form(f'Indexed: {esc(url)}') except ValueError as e: return handle_add_form(f"Error: {esc(str(e))}") @@ -427,7 +431,6 @@ def handle_add_submit(body): f'' f'' f'' - f'' f'
' f'

' f'
' @@ -443,15 +446,11 @@ def handle_add_manual_submit(body): url = clean_url(body.get("url", [""])[0].strip()) note = body.get("note", [""])[0].strip() tags = body.get("tags", [""])[0].strip() - reticulum_dest = body.get("reticulum_dest", [""])[0].strip() manual_title = body.get("manual_title", [""])[0].strip() manual_desc = body.get("manual_description", [""])[0].strip() - if not url and not reticulum_dest: - return handle_add_form("URL or Reticulum destination hash is required.") - - if not url and reticulum_dest: - url = f"reticulum:{reticulum_dest}" + if not url: + return handle_add_form("URL is required.") if not manual_title or not manual_desc: return handle_add_form("Title and description are required for manual entry.") @@ -461,10 +460,10 @@ def handle_add_manual_submit(body): now = __import__("datetime").datetime.now().strftime("%Y-%m-%dT%H:%M:%S") db.execute( - "INSERT INTO pages (url, title, body, note, last_modified, summary, reticulum_dest) VALUES (?, ?, ?, ?, ?, ?, ?) " + "INSERT INTO pages (url, title, body, note, last_modified, summary) VALUES (?, ?, ?, ?, ?, ?) " "ON CONFLICT(url) DO UPDATE SET title=excluded.title, body=excluded.body, " - "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary, reticulum_dest=excluded.reticulum_dest", - (url, manual_title, manual_desc, note, now, manual_desc[:200], reticulum_dest), + "note=excluded.note, last_modified=excluded.last_modified, summary=excluded.summary", + (url, manual_title, manual_desc, note, now, manual_desc[:200]), ) # Get the page ID @@ -493,6 +492,8 @@ def handle_add_manual_submit(body): def handle_pages(query=None): + msg = query.get("msg", [""])[0] if query else "" + msg_html = f'

{esc(msg)}

' if msg else "" page = _paginate(query or {}) offset = (page - 1) * BROWSE_PER_PAGE db = get_db() @@ -520,6 +521,7 @@ def handle_pages(query=None): return_db(db) return _respond( f"

indexed pages ({total})

" + f"{msg_html}" f"
    {items}
" f'{_page_nav(page, total, "/pages", BROWSE_PER_PAGE)}' f'

export | import

' @@ -530,20 +532,27 @@ def handle_pages(query=None): def handle_edit_form(page_id, msg=""): db = get_db() try: - row = db.execute("SELECT id, url, title, note FROM pages WHERE id = ?", (page_id,)).fetchone() + row = db.execute("SELECT id, url, title, body, note, summary FROM pages WHERE id = ?", (page_id,)).fetchone() if not row: return _error(404) tags = ", ".join(_get_page_tags(page_id, db)) finally: return_db(db) + return _respond( f"

edit page

" f"

{esc(row['title'])}
" f"{esc(row['url'])}

" f'
' f'{_csrf_field()}' - f'

' - f'

' + f'
' + f'

' + f'
' + f'

' + f'
' + f'

' + f'
' + f'

' f'' f"
" f"

{msg}

" @@ -552,15 +561,25 @@ def handle_edit_form(page_id, msg=""): def handle_edit_submit(page_id, body): + title = body.get("title", [""])[0].strip() + summary = body.get("summary", [""])[0].strip() note = body.get("note", [""])[0].strip() tags = body.get("tags", [""])[0].strip() + db = get_db() try: - db.execute("UPDATE pages SET note = ? WHERE id = ?", (note, page_id)) + db.execute( + "UPDATE pages SET title = ?, summary = ?, note = ? WHERE id = ?", + (title, summary, note, page_id) + ) + _set_page_tags(page_id, tags, db) + db.commit() + finally: return_db(db) + return _redirect("/pages") From 6c1a04ad79a99b7163afebe143b66a744dc8e7fb Mon Sep 17 00:00:00 2001 From: blankie Date: Mon, 30 Mar 2026 23:01:23 +0000 Subject: [PATCH 17/80] tightened up the add form spacing --- handlers.py | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/handlers.py b/handlers.py index bc39743..1665cae 100644 --- a/handlers.py +++ b/handlers.py @@ -357,26 +357,13 @@ def handle_add_form(msg="", action_type="index"): f"

Add a site to your index

" f'
' f'{_csrf_field()}' - f'' - f'' - f'' - f'' - f'

' - f'
' - f'

' + f'

' f'

' f'

' f'' f"
" f"

{msg}

" f'back' - f'' ) From f59a68a02d5287d1f93d12a0b31b47c9d07d1a9a Mon Sep 17 00:00:00 2001 From: blankie Date: Wed, 8 Apr 2026 04:36:28 +0000 Subject: [PATCH 18/80] added PyInstaller builds, AGPLv3, transport config - Add pyinstaller.spec and GitHub/Forgejo CI workflows for cross-platform builds - Add AGPLv3 license - Move data storage to ~/.tinyweb/ - Add --version and --port CLI flags - Add transport node selection in /style (smart regeneration preserves Reticulum config) - Add discover more nodes link to rmap.world --- .forgejo/workflows/build.yml | 57 ++++ .github/workflows/build.yml | 75 +++++ LICENSE | 574 +++++++++++++++++++++++++++++++++++ README.md | 19 ++ app.py | 109 ++++++- db.py | 5 +- embeddings.py | 8 +- handlers.py | 16 +- pyinstaller.spec | 81 +++++ 9 files changed, 924 insertions(+), 20 deletions(-) create mode 100644 .forgejo/workflows/build.yml create mode 100644 .github/workflows/build.yml create mode 100644 LICENSE create mode 100644 pyinstaller.spec diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml new file mode 100644 index 0000000..c7c6fa3 --- /dev/null +++ b/.forgejo/workflows/build.yml @@ -0,0 +1,57 @@ +on: + push: + tags: + - 'v*.*.*' + workflow_dispatch: + +jobs: + build: + runs-on: docker + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + pip install -r requirements.txt + pip install pyinstaller + + - name: Build with PyInstaller + run: | + pyinstaller --onefile --console --name TinyWeb app.py + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: TinyWeb-linux-x64 + path: dist/TinyWeb + if-no-files-found: error + + release: + needs: build + runs-on: docker + if: startsWith(github.ref, 'refs/tags/v') + + steps: + - name: Download artifact + uses: actions/download-artifact@v4 + with: + name: TinyWeb-linux-x64 + + - name: Make executable + run: chmod +x TinyWeb-linux-x64 + + - name: Create Release + uses: actions/forgejo-release@v2 + with: + direction: upload + release-dir: . + override: true + prerelease: ${{ contains(github.ref_name, 'alpha') || contains(github.ref_name, 'beta') }} + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..d79edb3 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,75 @@ +name: Build + +on: + push: + tags: + - 'v*.*.*' + workflow_dispatch: + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - os: windows-latest + artifact: TinyWeb-windows-x64.exe + - os: macos-latest + artifact: TinyWeb-macos-arm64 + - os: ubuntu-latest + artifact: TinyWeb-linux-x64 + + runs-on: ${{ matrix.os }} + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + pip install -r requirements.txt + pip install pyinstaller + + - name: Build with PyInstaller + run: | + pyinstaller --onefile --console --name TinyWeb app.py + + - name: Get artifact path + id: artifact + run: | + if [[ "${{ matrix.os }}" == "windows-latest" ]]; then + echo "path=dist/TinyWeb.exe" >> $GITHUB_OUTPUT + else + echo "path=dist/TinyWeb" >> $GITHUB_OUTPUT + fi + + - name: Create ZIP + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.artifact }} + path: ${{ steps.artifact.outputs.path }} + if-no-files-found: error + + release: + needs: build + runs-on: ubuntu-latest + if: startsWith(github.ref, 'refs/tags/v') + + steps: + - name: Download all artifacts + uses: actions/download-artifact@v4 + with: + path: artifacts + + - name: Create Release + uses: softprops/action-gh-release@v1 + with: + files: artifacts/** + generate_release_notes: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5445774 --- /dev/null +++ b/LICENSE @@ -0,0 +1,574 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License giving you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +are made publicly available of their being a derivative work, need not +be distributed to others. + + For example, if you modify a part of a free program, you are +not required to distribute the object code for the modified version +itself; however, the GNU Affero General Public License requires you +to provide source code for any version of the program that you use +or modify. This requirement is similar to the requirement that +the user can receive the source code if they distribute a copy. + + Also, if you link or combine the program with any other software +that contains code covered by this License (or any work based on the +program), you must provide the source code for that combined work +as well. The GNU Affero General Public License normally requires +that any work that you distribute or publish that in whole or in +part contains or is derived from the program or any part thereof, +to be licensed as a whole at no charge to all third parties under +the terms of this License. This is known as "providing source code" +or "making available" the work. + + An "aggregated" or "combined" work is not covered by this License +if you do not meet these conditions, and you must provide the source +code as above. Additionally, aggregating works does not exempt you +from the requirements of this License. + + Specifically, if you make an "aggregate" or "combined" work by +combining this program with other software (or any work based on this +program) on a volume of a storage or distribution medium, you must +provide the source code for the combined work as above. This +requirement is intended to ensure that any user of the combined work +gets the source code that you made available, and can exercise the +right to modify and re-distribute the combined work. + + This License is specifically intended to limit any attempt to +place your modifications under a license that would restrict re-use +or further modification by others. This is to ensure that any +derivative work you create will be available under the same license +as the original, so that any derivative work can be re-distributed +under the same conditions as the original. + + Finally, this License is not intended to limit your rights under +fair use or other limitations on exclusive rights, such as patents +or trademarks. This License does not grant you any rights to the +names of the authors or copyright holders, nor to trade names, +trademarks, or service marks, except as needed for the normal and +customary use in describing the origin of the work and reproducing +the content of the notice file. + + The source code for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided in copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must contain prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must contain prominent notices stating that it is + released under this License and any conditions added under section 7. + This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the legal rights of the compilation's users beyond +what the individual works permit. Inclusion of a covered work in an +aggregate does not cause this License to apply to the other parts of +the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in + accord with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A +product is a consumer product regardless of whether the product has +substantial commercial, industrial or non-consumer uses, unless such +uses represent the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions applicable to the entire Program shall be treated +as though they were included in this License, to the extent that they +are valid under applicable law. If additional permissions apply only to +part of the Program, then that part may be used separately under those +permissions, but the entire Program remains governed by this License +without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as +you received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, or selling the work, +or by making, using, or selling the work. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available to anyone +in the United States, you may not convey the work under this License. +This is done by providing access to copy the corresponding source code +from a network server at no charge. + + If, during the execution of the Program, the Program is transmitted +to a user or a computer, either the source code or object code, you +must meet the requirements of this License regarding the +Corresponding Source of the work. You must make sure that the source +code or object code (as applicable) is available for such users to +copy and modify, and to run, for their own use, the corresponding +source in accordance with this License. This requirement applies +both to the work as stand-alone and to the work as part of an +aggregate. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 12. No Warranty + + THE PROGRAM IS PROVIDED WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK +AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD +THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY +SERVICING, REPAIR OR CORRECTION. + + 13. Disclaimer of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR +THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + 14. Interpretation of Sections 12 and 13. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + + The hypothetical commands `show w' and `show c' should show the appropriate + parts of the General Public License. Of course, your program's commands + might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, + if any, to sign a "copyright disclaimer" for the program, if necessary. + For more information on this, and how to apply and follow the GNU AGPL, + see . diff --git a/README.md b/README.md index ec66704..deb1d1e 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,25 @@ A personal, decentralized search engine built on the [Reticulum](https://reticul - **Import/export** — JSON-based backup and restore - **Mesh-native** — Works over Reticulum without the internet; encrypted and decentralized by default +## Download (pre-built binaries) + +Download the latest release for your platform from the [GitHub Releases](https://github.com/anomalyco/tinyweb/releases) page: + +| Platform | File | +|----------|------| +| Windows | `TinyWeb-windows-x64.exe` | +| macOS | `TinyWeb-macos-arm64` | +| Linux | `TinyWeb-linux-x64` | + +Run the downloaded file — no installation required. Your data is stored in `~/.tinyweb/`. + +### Command line options + +```bash +./TinyWeb --version # Show version +./TinyWeb -p 9000 # Use port 9000 instead of default 8080 +``` + ## Getting started ```bash diff --git a/app.py b/app.py index dba9695..c13c229 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,8 @@ import os +import sys import time import threading +import argparse import RNS from http.server import HTTPServer @@ -13,18 +15,59 @@ ASPECTS = ["server"] IDENTITY_FILE = "tinyweb_identity" DEFAULT_TRANSPORT_HOST = "rnode.bre.land" DEFAULT_TRANSPORT_PORT = 4242 +DATA_DIR = os.path.expanduser("~/.tinyweb") + + +def get_transport_config(): + host = get_setting("transport_host", DEFAULT_TRANSPORT_HOST) + port = get_setting("transport_port", str(DEFAULT_TRANSPORT_PORT)) + return host, int(port) + + +def find_available_port(start=8080, max_attempts=20): + """Find an available port starting from start.""" + import socket + for port in range(start, start + max_attempts): + try: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("0.0.0.0", port)) + return port + except OSError: + continue + return start + + +def get_version(): + """Get version from git tag or VERSION file.""" + try: + import subprocess + tag = subprocess.check_output( + ["git", "describe", "--tags", "--abbrev=0"], + stderr=subprocess.DEVNULL, + text=True + ).strip() + if tag.startswith("v"): + return tag[1:] + return tag + except Exception: + version_file = os.path.join(os.path.dirname(__file__), "VERSION") + if os.path.exists(version_file): + with open(version_file) as f: + return f.read().strip() + return "0.0.0" def load_or_create_identity(): - if os.path.isfile(IDENTITY_FILE): - # Ensure identity file is only readable by owner - current = os.stat(IDENTITY_FILE).st_mode & 0o777 + os.makedirs(DATA_DIR, exist_ok=True) + identity_path = os.path.join(DATA_DIR, IDENTITY_FILE) + if os.path.isfile(identity_path): + current = os.stat(identity_path).st_mode & 0o777 if current != 0o600: - os.chmod(IDENTITY_FILE, 0o600) - return RNS.Identity.from_file(IDENTITY_FILE) + os.chmod(identity_path, 0o600) + return RNS.Identity.from_file(identity_path) identity = RNS.Identity() - identity.to_file(IDENTITY_FILE) - os.chmod(IDENTITY_FILE, 0o600) + identity.to_file(identity_path) + os.chmod(identity_path, 0o600) return identity @@ -42,13 +85,35 @@ def start_gateway(reticulum): thread.start() -def ensure_rns_config(config_dir): +def _transport_settings_match(config_file, desired_host, desired_port): + """Check if existing config transport settings match desired values.""" + import configparser + try: + config = configparser.ConfigParser() + config.read(config_file) + if config.has_section("TCP Transport"): + existing_host = config.get("TCP Transport", "target_host") + existing_port = config.get("TCP Transport", "target_port") + return existing_host == desired_host and existing_port == str(desired_port) + except Exception: + pass + return False + + +def ensure_rns_config(config_dir, transport_host=None, transport_port=None): """Generate a default Reticulum config with internet transport if none exists.""" if config_dir is None: config_dir = os.path.expanduser("~/.reticulum") config_file = os.path.join(config_dir, "config") + if transport_host is None: + transport_host = get_setting("transport_host", DEFAULT_TRANSPORT_HOST) + if transport_port is None: + transport_port = int(get_setting("transport_port", str(DEFAULT_TRANSPORT_PORT))) + if os.path.exists(config_file): - return + if _transport_settings_match(config_file, transport_host, transport_port): + return + os.makedirs(config_dir, exist_ok=True) with open(config_file, "w") as f: f.write(f"""[reticulum] @@ -66,8 +131,8 @@ def ensure_rns_config(config_dir): [[TCP Transport]] type = TCPClientInterface enabled = yes - target_host = {DEFAULT_TRANSPORT_HOST} - target_port = {DEFAULT_TRANSPORT_PORT} + target_host = {transport_host} + target_port = {transport_port} """) print(f"Created Reticulum config at {config_file}") @@ -79,9 +144,8 @@ def _preload_embeddings(): return try: from embeddings import _get_session, _get_reranker, build_index - _get_session() # downloads model on first run, loads ONNX session - build_index() # builds HNSW index from existing chunks - # Preload cross-encoder unless user has explicitly disabled it + _get_session() + build_index() if get_setting("use_reranker", "1") == "1": _get_reranker() print("Semantic search ready (with reranker).") @@ -92,10 +156,25 @@ def _preload_embeddings(): def main(): + parser = argparse.ArgumentParser(prog="tinyweb", description="Personal decentralized search engine") + parser.add_argument("--version", "-v", action="store_true", help="Show version") + parser.add_argument("--port", "-p", type=int, default=None, help="HTTP gateway port (default: 8080)") + args = parser.parse_args() + + if args.version: + print(f"TinyWeb {get_version()}") + return + + port = args.port or 8080 + import gateway + gateway.GATEWAY_PORT = find_available_port(port) + init_db() + transport_host = get_setting("transport_host", DEFAULT_TRANSPORT_HOST) + transport_port = int(get_setting("transport_port", str(DEFAULT_TRANSPORT_PORT))) threading.Thread(target=_preload_embeddings, daemon=True).start() config_dir = os.environ.get("RNS_CONFIG_DIR") - ensure_rns_config(config_dir) + ensure_rns_config(config_dir, transport_host, transport_port) reticulum = RNS.Reticulum(configdir=config_dir) identity = load_or_create_identity() diff --git a/db.py b/db.py index 4943855..295da86 100644 --- a/db.py +++ b/db.py @@ -2,10 +2,12 @@ import socket import ipaddress import sqlite3 import requests +import os from urllib.parse import urlparse, urljoin, parse_qs, urlencode, urlunparse, quote from bs4 import BeautifulSoup -DATABASE = "index.db" +DATA_DIR = os.path.expanduser("~/.tinyweb") +DATABASE = os.path.join(DATA_DIR, "index.db") BLOCKED_NETWORKS = [ ipaddress.ip_network("127.0.0.0/8"), @@ -123,6 +125,7 @@ def return_db(db): def init_db(): + os.makedirs(DATA_DIR, exist_ok=True) db = sqlite3.connect(DATABASE) db.execute( "CREATE TABLE IF NOT EXISTS pages (" diff --git a/embeddings.py b/embeddings.py index aa6a4ff..302a31f 100644 --- a/embeddings.py +++ b/embeddings.py @@ -5,10 +5,11 @@ import re import threading import numpy as np +DATA_DIR = os.path.expanduser("~/.tinyweb") MODEL_ID = "Snowflake/snowflake-arctic-embed-s" -MODEL_DIR = os.path.join(os.path.dirname(__file__), "models", "snowflake-arctic-embed-s") -RERANKER_DIR = os.path.join(os.path.dirname(__file__), "models", "cross-encoder") -HNSW_PATH = os.path.join(os.path.dirname(__file__), "index.hnsw") +MODEL_DIR = os.path.join(DATA_DIR, "models", "snowflake-arctic-embed-s") +RERANKER_DIR = os.path.join(DATA_DIR, "models", "cross-encoder") +HNSW_PATH = os.path.join(DATA_DIR, "index.hnsw") DIMS = 384 MAX_TOKENS = 512 QUERY_PREFIX = "Represent this sentence for searching relevant passages: " @@ -33,6 +34,7 @@ _hnsw_lock = threading.Lock() def _ensure_model(): """Download the ONNX model and tokenizer from HuggingFace if not present.""" + os.makedirs(MODEL_DIR, exist_ok=True) model_path = os.path.join(MODEL_DIR, "model.onnx") tokenizer_path = os.path.join(MODEL_DIR, "tokenizer.json") if os.path.exists(model_path) and os.path.exists(tokenizer_path): diff --git a/handlers.py b/handlers.py index 1665cae..a19a62d 100644 --- a/handlers.py +++ b/handlers.py @@ -684,6 +684,8 @@ def handle_style_form(msg=""): reranker_checked = " checked" if reranker == "1" else "" disabled = "" if semantic == "1" else " disabled" dimmed = ' style="opacity:0.4"' if semantic != "1" else "" + transport_host = get_setting("transport_host", "rnode.bre.land") + transport_port = get_setting("transport_port", "4242") return _respond( f"

customize

" f"

name your search engine

" @@ -693,6 +695,12 @@ def handle_style_form(msg=""): f"

sharing

" f'

" + f"

mesh network

" + f"

Connect to a Reticulum transport node to reach other peers.

" + f"Default: rnode.bre.land:4242
" + f'' + f'
' + f'

discover more nodes


' f"

search

" f"

ai

" f'