embed-ab 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
embed_ab/compare.py ADDED
@@ -0,0 +1,212 @@
1
+ """The comparison pipeline: index, search, metrics, statistics, overlap, warnings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ import re
7
+ import time
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, field
10
+ from importlib import metadata
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+
15
+ from embed_ab import metrics as M
16
+ from embed_ab.bm25 import BM25, TOKENIZERS
17
+ from embed_ab.cache import EmbeddingCache
18
+ from embed_ab.checks import COPY_THRESHOLD, run_checks
19
+ from embed_ab.evalset import EvalSet, EvalSetError
20
+ from embed_ab.overlap import jaccard_at_k, rbo_ext
21
+ from embed_ab.paths import cache_subdir
22
+ from embed_ab.providers import Embedder, make_embedder
23
+ from embed_ab.search import dense_search, top_k
24
+ from embed_ab.stats import paired_bootstrap_ci
25
+ from embed_ab.synth import copy_ratio
26
+
27
+ PRIMARY = "ndcg"
28
+ RBO_P = 0.9
29
+
30
+
31
+ @dataclass
32
+ class CompareResult:
33
+ """Everything a report needs; ``data`` is plain JSON-serialisable data."""
34
+
35
+ data: dict[str, Any] = field(default_factory=dict)
36
+
37
+ def to_dict(self) -> dict[str, Any]:
38
+ return self.data
39
+
40
+ def diff(self, metric: str) -> dict[str, Any]:
41
+ """Candidate-minus-baseline summary for ``metric`` such as ``ndcg@10``."""
42
+ return self.data["comparison"]["metrics"][metric]
43
+
44
+
45
+ def parse_metric_name(name: str, k: int) -> str:
46
+ """Validate ``ndcg@10``-style names against the run's ``k``."""
47
+ m = re.fullmatch(r"(recall|ndcg|mrr|hit)@(\d+)", name.strip().lower())
48
+ if not m:
49
+ raise EvalSetError(
50
+ f"Unknown metric {name!r}. Use one of recall@K, ndcg@K, mrr@K, hit@K (for example ndcg@{k})."
51
+ )
52
+ if int(m.group(2)) != k:
53
+ raise EvalSetError(f"Metric {name!r} does not match -k {k}. Run with -k {m.group(2)} or gate on {m.group(1)}@{k}.")
54
+ return f"{m.group(1)}@{k}"
55
+
56
+
57
+ def _version(pkg: str) -> str | None:
58
+ try:
59
+ return metadata.version(pkg)
60
+ except metadata.PackageNotFoundError:
61
+ return None
62
+
63
+
64
+ def _index_embedder(
65
+ emb: Embedder, evalset: EvalSet, k: int, use_cache: bool, log: Callable[[str], None]
66
+ ) -> dict[str, Any]:
67
+ doc_ids = list(evalset.corpus)
68
+ q_ids = list(evalset.queries)
69
+ prompts = f"q={emb.info().get('query_prompt', '')}|d={emb.info().get('doc_prompt', '')}"
70
+ cache = EmbeddingCache(cache_subdir("embeddings"), f"{emb.spec}|{prompts}") if use_cache else None
71
+
72
+ def run(kind: str, texts: list[str], fn: Callable[..., np.ndarray]) -> tuple[np.ndarray, int, int]:
73
+ if cache is None:
74
+ return fn(texts), 0, len(texts)
75
+ return cache.embed(kind, texts, fn)
76
+
77
+ log(f" indexing {len(doc_ids)} chunks with {emb.spec} ...")
78
+ t0 = time.perf_counter()
79
+ doc_vecs, h1, m1 = run("d", [evalset.corpus[d] for d in doc_ids], emb.embed_documents)
80
+ index_s = time.perf_counter() - t0
81
+ q_vecs, h2, m2 = run("q", [evalset.queries[q] for q in q_ids], emb.embed_queries)
82
+ t1 = time.perf_counter()
83
+ ranked = dense_search(q_vecs, doc_vecs, doc_ids, k)
84
+ search_s = time.perf_counter() - t1
85
+ info = emb.info()
86
+ return {
87
+ "spec": emb.spec, "kind": "embedding", "ranked": ranked, "info": info,
88
+ "index_seconds": round(index_s, 4), "search_seconds": round(search_s, 4),
89
+ "cache_hits": h1 + h2, "cache_misses": m1 + m2,
90
+ "vector_bytes": int(doc_vecs.nbytes),
91
+ }
92
+
93
+
94
+ def compare(
95
+ evalset: EvalSet,
96
+ a: str,
97
+ b: str,
98
+ *,
99
+ k: int = 10,
100
+ bm25: str | None = "word",
101
+ seed: int = 0,
102
+ n_boot: int = 2000,
103
+ use_cache: bool = True,
104
+ a_prompts: tuple[str, str] = ("", ""),
105
+ b_prompts: tuple[str, str] = ("", ""),
106
+ embedders: tuple[Embedder, Embedder] | None = None,
107
+ log: Callable[[str], None] = lambda _msg: None,
108
+ ) -> CompareResult:
109
+ """Compare embedding model ``a`` (baseline) with ``b`` (candidate) on ``evalset``.
110
+
111
+ ``bm25`` is ``"word"``, ``"char2"`` or ``None``. ``embedders`` injects ready-made embedders (tests).
112
+ """
113
+ if k < 1:
114
+ raise EvalSetError("-k must be at least 1.")
115
+ if bm25 is not None and bm25 not in TOKENIZERS:
116
+ raise EvalSetError(f"Unknown BM25 tokenizer {bm25!r}; choose one of {', '.join(TOKENIZERS)}.")
117
+ if a == b and embedders is None:
118
+ raise EvalSetError("-a and -b are the same model; pick two different models to compare.")
119
+ ea, eb = embedders or (
120
+ make_embedder(a, query_prompt=a_prompts[0], doc_prompt=a_prompts[1]),
121
+ make_embedder(b, query_prompt=b_prompts[0], doc_prompt=b_prompts[1]),
122
+ )
123
+
124
+ q_ids = list(evalset.queries)
125
+ doc_ids = list(evalset.corpus)
126
+ qrels = [evalset.qrels[q] for q in q_ids]
127
+ systems: dict[str, dict[str, Any]] = {"A": _index_embedder(ea, evalset, k, use_cache, log),
128
+ "B": _index_embedder(eb, evalset, k, use_cache, log)}
129
+ if bm25:
130
+ log(f" indexing BM25 ({bm25}) ...")
131
+ t0 = time.perf_counter()
132
+ index = BM25([evalset.corpus[d] for d in doc_ids], bm25)
133
+ index_s = time.perf_counter() - t0
134
+ t1 = time.perf_counter()
135
+ scores = np.stack([index.scores(evalset.queries[q]) for q in q_ids])
136
+ systems["BM25"] = {
137
+ "spec": f"bm25:{bm25}", "kind": "lexical", "ranked": top_k(scores, doc_ids, k), "info": {},
138
+ "index_seconds": round(index_s, 4), "search_seconds": round(time.perf_counter() - t1, 4),
139
+ "cache_hits": 0, "cache_misses": 0, "vector_bytes": 0,
140
+ }
141
+
142
+ per_query: dict[str, dict[str, np.ndarray]] = {
143
+ name: M.all_metrics(s["ranked"], qrels, k) for name, s in systems.items()
144
+ }
145
+ primary = f"{PRIMARY}@{k}"
146
+ comparison: dict[str, Any] = {"baseline": "A", "candidate": "B", "metrics": {}}
147
+ for metric in per_query["A"]:
148
+ diff = per_query["B"][metric] - per_query["A"][metric]
149
+ mean, lo, hi = paired_bootstrap_ci(diff, n_boot=n_boot, seed=seed)
150
+ comparison["metrics"][metric] = {
151
+ "mean_diff": mean, "ci_lo": lo, "ci_hi": hi,
152
+ "wins": int((diff > 1e-12).sum()), "losses": int((diff < -1e-12).sum()),
153
+ "ties": int((np.abs(diff) <= 1e-12).sum()),
154
+ }
155
+
156
+ jac = np.array([jaccard_at_k(x, y, k) for x, y in zip(systems["A"]["ranked"], systems["B"]["ranked"])])
157
+ rbo = np.array([rbo_ext(x, y, RBO_P) for x, y in zip(systems["A"]["ranked"], systems["B"]["ranked"])])
158
+
159
+ rows = []
160
+ for i, qid in enumerate(q_ids):
161
+ row: dict[str, Any] = {
162
+ "id": qid, "text": evalset.queries[qid],
163
+ "relevant": sorted(d for d, g in qrels[i].items() if g > 0),
164
+ "diff_primary": float(per_query["B"][primary][i] - per_query["A"][primary][i]),
165
+ "jaccard": float(jac[i]), "rbo": float(rbo[i]),
166
+ }
167
+ for name, s in systems.items():
168
+ row[name] = {"top": s["ranked"][i], **{m: float(v[i]) for m, v in per_query[name].items()}}
169
+ rows.append(row)
170
+
171
+ ratios = [
172
+ max(copy_ratio(evalset.queries[q], evalset.corpus[d]) for d, g in evalset.qrels[q].items() if g > 0)
173
+ for q in q_ids
174
+ ]
175
+ copy_share = float(np.mean([r >= COPY_THRESHOLD for r in ratios]))
176
+ pd = comparison["metrics"][primary]
177
+ seq = {systems[s]["spec"]: systems[s]["info"].get("max_seq_length") for s in ("A", "B")}
178
+ warnings = run_checks(
179
+ n_queries=len(q_ids),
180
+ mean_a=float(per_query["A"][primary].mean()), mean_b=float(per_query["B"][primary].mean()),
181
+ tie_share=pd["ties"] / len(q_ids), ci=(pd["ci_lo"], pd["ci_hi"]),
182
+ copy_share=copy_share, max_chunk_chars=max(len(t) for t in evalset.corpus.values()),
183
+ max_seq_lengths=seq, metric=primary,
184
+ )
185
+
186
+ shown = {d for r in rows for s in systems for d in r[s]["top"][:3]} | {d for r in rows for d in r["relevant"]}
187
+ out_systems = {}
188
+ for name, s in systems.items():
189
+ out_systems[name] = {key: s[key] for key in
190
+ ("spec", "kind", "info", "index_seconds", "search_seconds", "cache_hits", "cache_misses", "vector_bytes")}
191
+ out_systems[name]["metrics"] = {m: float(v.mean()) for m, v in per_query[name].items()}
192
+ mock = any(systems[s]["info"].get("mock") for s in ("A", "B"))
193
+ result = {
194
+ "tool": {
195
+ "name": "embed-ab", "version": _version("embed-ab"), "python": platform.python_version(),
196
+ "numpy": _version("numpy"), "sentence_transformers": _version("sentence-transformers"),
197
+ },
198
+ "mock_notice": "Practice mock mode: mock embedders are hashed n-gram vectors, not real models. "
199
+ "The numbers illustrate the method and say nothing about real model quality." if mock else None,
200
+ "params": {"k": k, "seed": seed, "bootstrap": n_boot, "primary_metric": primary, "rbo_p": RBO_P,
201
+ "bm25": bm25, "copy_threshold": COPY_THRESHOLD},
202
+ "evalset": {"documents": len(doc_ids), "queries": len(q_ids),
203
+ "max_chunk_chars": max(len(t) for t in evalset.corpus.values())},
204
+ "systems": out_systems,
205
+ "comparison": comparison,
206
+ "overlap": {"jaccard_mean": float(jac.mean()), "rbo_mean": float(rbo.mean()),
207
+ "jaccard": [float(x) for x in jac], "rbo": [float(x) for x in rbo]},
208
+ "queries": rows,
209
+ "docs": {d: evalset.corpus[d][:160] for d in sorted(shown)},
210
+ "warnings": warnings,
211
+ }
212
+ return CompareResult(result)
@@ -0,0 +1,40 @@
1
+ {"_id": "backup.ko.md#0000", "text": "자동 백업은 매일 새벽 3시에 실행되며 최근 7일치 사본을 보관합니다. 보관 기간은 설정의 저장소 탭에서 바꿀 수 있습니다."}
2
+ {"_id": "backup.ko.md#0001", "text": "수동 백업을 만들려면 파일 메뉴에서 '지금 백업'을 누르세요. 백업 파일은 확장자가 pbk인 단일 압축 파일로 저장됩니다."}
3
+ {"_id": "backup.ko.md#0002", "text": "백업 파일을 복원하면 현재 노트가 모두 덮어써집니다. 복원하기 전에 현재 상태를 한 번 더 내보내 두는 것을 권장합니다."}
4
+ {"_id": "backup.ko.md#0003", "text": "백업 폴더를 외장 디스크나 클라우드 폴더로 지정하면 컴퓨터가 고장 나도 노트를 지킬 수 있습니다. 경로는 저장소 탭의 대상 폴더 항목에서 정합니다."}
5
+ {"_id": "backup.ko.md#0004", "text": "암호화된 노트북은 백업 파일 안에서도 암호화된 채로 보관됩니다. 복원할 때 원래 암호를 입력해야 열 수 있습니다."}
6
+ {"_id": "backup.ko.md#0005", "text": "백업 용량이 커서 느리다면 첨부 이미지를 제외하는 옵션을 켜 보세요. 텍스트만 백업하면 용량이 크게 줄어듭니다."}
7
+ {"_id": "backup.ko.md#0006", "text": "백업이 실패하면 상태 표시줄에 빨간 경고가 나타납니다. 대부분 디스크 공간 부족이 원인이므로 오래된 사본을 정리해 보세요."}
8
+ {"_id": "backup.ko.md#0007", "text": "한 노트만 따로 내보내고 싶다면 노트 메뉴의 '내보내기'를 사용하세요. 마크다운과 PDF 형식을 지원합니다."}
9
+ {"_id": "sync.ko.md#0000", "text": "동기화를 켜려면 계정으로 로그인한 뒤 설정에서 동기화 스위치를 켜세요. 처음 동기화는 노트 양에 따라 몇 분이 걸릴 수 있습니다."}
10
+ {"_id": "sync.ko.md#0001", "text": "두 기기에서 같은 노트를 동시에 고치면 충돌 사본이 만들어집니다. 충돌 사본은 원본 옆에 '(충돌)'이라는 이름으로 표시됩니다."}
11
+ {"_id": "sync.ko.md#0002", "text": "오프라인에서 작성한 내용은 기기에 먼저 저장되고, 네트워크에 다시 연결되면 자동으로 올라갑니다. 비행기 안에서도 안심하고 쓰셔도 됩니다."}
12
+ {"_id": "sync.ko.md#0003", "text": "모바일 데이터 사용량을 아끼려면 '와이파이에서만 동기화' 옵션을 켜세요. 이미지 첨부는 와이파이에 연결될 때까지 대기합니다."}
13
+ {"_id": "sync.ko.md#0004", "text": "동기화 기록은 설정의 기록 탭에서 확인합니다. 어느 기기가 언제 어떤 노트를 바꿨는지 최근 30일치가 남습니다."}
14
+ {"_id": "sync.ko.md#0005", "text": "실수로 지운 노트는 휴지통에서 30일 동안 복구할 수 있습니다. 휴지통을 비우면 모든 기기에서 영구 삭제됩니다."}
15
+ {"_id": "sync.ko.md#0006", "text": "동기화 용량은 무료 플랜에서 계정당 2GB입니다. 용량이 가득 차면 새 첨부 파일은 올라가지 않지만 텍스트는 계속 동기화됩니다."}
16
+ {"_id": "sync.ko.md#0007", "text": "기기를 잃어버렸다면 웹 계정 페이지에서 해당 기기의 로그인을 해제하세요. 해제된 기기는 더 이상 노트를 받아 가지 못합니다."}
17
+ {"_id": "security.ko.md#0000", "text": "앱 잠금을 켜면 실행할 때마다 비밀번호나 지문을 묻습니다. 일정 시간 사용하지 않으면 자동으로 다시 잠깁니다."}
18
+ {"_id": "security.ko.md#0001", "text": "노트북 단위로 암호를 걸 수 있습니다. 암호를 잊어버리면 복구할 방법이 없으니 안전한 곳에 적어 두세요."}
19
+ {"_id": "security.ko.md#0002", "text": "모든 동기화 통신은 TLS로 암호화되며, 서버에는 종단 간 암호화된 데이터만 저장됩니다. 서비스 운영자도 노트 내용을 읽을 수 없습니다."}
20
+ {"_id": "security.ko.md#0003", "text": "이중 인증을 켜면 새 기기에서 로그인할 때 인증 앱의 일회용 코드가 필요합니다. 복구 코드는 계정 생성 직후 한 번만 보여 줍니다."}
21
+ {"_id": "security.ko.md#0004", "text": "화면 캡처 방지 옵션을 켜면 암호화된 노트북이 열려 있는 동안 스크린샷이 검게 나옵니다. 안드로이드와 아이폰에서 지원합니다."}
22
+ {"_id": "security.ko.md#0005", "text": "공유 링크는 만료 날짜와 비밀번호를 지정할 수 있습니다. 링크를 만든 사람은 언제든 공유를 취소할 수 있습니다."}
23
+ {"_id": "security.ko.md#0006", "text": "앱은 노트 내용을 분석하거나 광고에 쓰지 않으며, 사용 통계 전송은 기본값이 꺼짐입니다. 설정의 개인정보 탭에서 확인할 수 있습니다."}
24
+ {"_id": "security.ko.md#0007", "text": "보안 문제를 발견하면 공개 이슈 대신 보안 신고 주소로 알려 주세요. 영업일 기준 3일 안에 답변합니다."}
25
+ {"_id": "search.en.md#0000", "text": "Press Ctrl+K to open quick search. Results appear as you type and match note titles first, then note bodies."}
26
+ {"_id": "search.en.md#0001", "text": "Wrap words in quotes to search for an exact phrase. Without quotes, every word must appear, but not necessarily next to each other."}
27
+ {"_id": "search.en.md#0002", "text": "Use tag:project to limit results to notes carrying that tag. Tags can be combined, so tag:project tag:urgent finds notes with both."}
28
+ {"_id": "search.en.md#0003", "text": "The index is rebuilt in the background after large imports. While it runs, the status bar shows a small spinner and recent notes may be missing from results."}
29
+ {"_id": "search.en.md#0004", "text": "Search covers text inside PDF attachments when the optional OCR component is installed. Scanned images are processed once and cached locally."}
30
+ {"_id": "search.en.md#0005", "text": "Saved searches live in the sidebar. Right-click a query and choose Pin to keep it, or drag it into a folder to organize related searches."}
31
+ {"_id": "search.en.md#0006", "text": "Date filters understand phrases such as before:2026-01-01 and after:last-week. Combine them with tags to build a quick weekly review."}
32
+ {"_id": "search.en.md#0007", "text": "Fuzzy matching tolerates one typo per word and can be turned off in Preferences if you prefer strict results."}
33
+ {"_id": "plugins.en.md#0000", "text": "Plugins are small folders containing a manifest and a script. Drop one into the plugins directory and restart the app to load it."}
34
+ {"_id": "plugins.en.md#0001", "text": "Every plugin declares the permissions it needs in its manifest. The app asks you to approve network or file access the first time it is used."}
35
+ {"_id": "plugins.en.md#0002", "text": "The scripting API exposes notes, tags and the editor. Use app.notes.create(title, body) to add a note from a plugin."}
36
+ {"_id": "plugins.en.md#0003", "text": "Plugins run in a sandbox with a 5 second time limit per call. Long tasks should be split into chunks or scheduled as background jobs."}
37
+ {"_id": "plugins.en.md#0004", "text": "To publish a plugin, add a release on its repository and submit the repository name to the community list. A reviewer checks the manifest before it appears."}
38
+ {"_id": "plugins.en.md#0005", "text": "Crashing plugins are disabled automatically after three failures in a row. Re-enable them from the plugin list once the problem is fixed."}
39
+ {"_id": "plugins.en.md#0006", "text": "Plugin settings are stored per vault in a small JSON file. Delete the file to reset a plugin to its defaults."}
40
+ {"_id": "plugins.en.md#0007", "text": "Themes are plugins that only contain CSS. They load without a script and never need permissions."}
@@ -0,0 +1,15 @@
1
+ 자동 백업은 매일 새벽 3시에 실행되며 최근 7일치 사본을 보관합니다. 보관 기간은 설정의 저장소 탭에서 바꿀 수 있습니다.
2
+
3
+ 수동 백업을 만들려면 파일 메뉴에서 '지금 백업'을 누르세요. 백업 파일은 확장자가 pbk인 단일 압축 파일로 저장됩니다.
4
+
5
+ 백업 파일을 복원하면 현재 노트가 모두 덮어써집니다. 복원하기 전에 현재 상태를 한 번 더 내보내 두는 것을 권장합니다.
6
+
7
+ 백업 폴더를 외장 디스크나 클라우드 폴더로 지정하면 컴퓨터가 고장 나도 노트를 지킬 수 있습니다. 경로는 저장소 탭의 대상 폴더 항목에서 정합니다.
8
+
9
+ 암호화된 노트북은 백업 파일 안에서도 암호화된 채로 보관됩니다. 복원할 때 원래 암호를 입력해야 열 수 있습니다.
10
+
11
+ 백업 용량이 커서 느리다면 첨부 이미지를 제외하는 옵션을 켜 보세요. 텍스트만 백업하면 용량이 크게 줄어듭니다.
12
+
13
+ 백업이 실패하면 상태 표시줄에 빨간 경고가 나타납니다. 대부분 디스크 공간 부족이 원인이므로 오래된 사본을 정리해 보세요.
14
+
15
+ 한 노트만 따로 내보내고 싶다면 노트 메뉴의 '내보내기'를 사용하세요. 마크다운과 PDF 형식을 지원합니다.
@@ -0,0 +1,15 @@
1
+ Plugins are small folders containing a manifest and a script. Drop one into the plugins directory and restart the app to load it.
2
+
3
+ Every plugin declares the permissions it needs in its manifest. The app asks you to approve network or file access the first time it is used.
4
+
5
+ The scripting API exposes notes, tags and the editor. Use app.notes.create(title, body) to add a note from a plugin.
6
+
7
+ Plugins run in a sandbox with a 5 second time limit per call. Long tasks should be split into chunks or scheduled as background jobs.
8
+
9
+ To publish a plugin, add a release on its repository and submit the repository name to the community list. A reviewer checks the manifest before it appears.
10
+
11
+ Crashing plugins are disabled automatically after three failures in a row. Re-enable them from the plugin list once the problem is fixed.
12
+
13
+ Plugin settings are stored per vault in a small JSON file. Delete the file to reset a plugin to its defaults.
14
+
15
+ Themes are plugins that only contain CSS. They load without a script and never need permissions.
@@ -0,0 +1,15 @@
1
+ Press Ctrl+K to open quick search. Results appear as you type and match note titles first, then note bodies.
2
+
3
+ Wrap words in quotes to search for an exact phrase. Without quotes, every word must appear, but not necessarily next to each other.
4
+
5
+ Use tag:project to limit results to notes carrying that tag. Tags can be combined, so tag:project tag:urgent finds notes with both.
6
+
7
+ The index is rebuilt in the background after large imports. While it runs, the status bar shows a small spinner and recent notes may be missing from results.
8
+
9
+ Search covers text inside PDF attachments when the optional OCR component is installed. Scanned images are processed once and cached locally.
10
+
11
+ Saved searches live in the sidebar. Right-click a query and choose Pin to keep it, or drag it into a folder to organize related searches.
12
+
13
+ Date filters understand phrases such as before:2026-01-01 and after:last-week. Combine them with tags to build a quick weekly review.
14
+
15
+ Fuzzy matching tolerates one typo per word and can be turned off in Preferences if you prefer strict results.
@@ -0,0 +1,15 @@
1
+ 앱 잠금을 켜면 실행할 때마다 비밀번호나 지문을 묻습니다. 일정 시간 사용하지 않으면 자동으로 다시 잠깁니다.
2
+
3
+ 노트북 단위로 암호를 걸 수 있습니다. 암호를 잊어버리면 복구할 방법이 없으니 안전한 곳에 적어 두세요.
4
+
5
+ 모든 동기화 통신은 TLS로 암호화되며, 서버에는 종단 간 암호화된 데이터만 저장됩니다. 서비스 운영자도 노트 내용을 읽을 수 없습니다.
6
+
7
+ 이중 인증을 켜면 새 기기에서 로그인할 때 인증 앱의 일회용 코드가 필요합니다. 복구 코드는 계정 생성 직후 한 번만 보여 줍니다.
8
+
9
+ 화면 캡처 방지 옵션을 켜면 암호화된 노트북이 열려 있는 동안 스크린샷이 검게 나옵니다. 안드로이드와 아이폰에서 지원합니다.
10
+
11
+ 공유 링크는 만료 날짜와 비밀번호를 지정할 수 있습니다. 링크를 만든 사람은 언제든 공유를 취소할 수 있습니다.
12
+
13
+ 앱은 노트 내용을 분석하거나 광고에 쓰지 않으며, 사용 통계 전송은 기본값이 꺼짐입니다. 설정의 개인정보 탭에서 확인할 수 있습니다.
14
+
15
+ 보안 문제를 발견하면 공개 이슈 대신 보안 신고 주소로 알려 주세요. 영업일 기준 3일 안에 답변합니다.
@@ -0,0 +1,15 @@
1
+ 동기화를 켜려면 계정으로 로그인한 뒤 설정에서 동기화 스위치를 켜세요. 처음 동기화는 노트 양에 따라 몇 분이 걸릴 수 있습니다.
2
+
3
+ 두 기기에서 같은 노트를 동시에 고치면 충돌 사본이 만들어집니다. 충돌 사본은 원본 옆에 '(충돌)'이라는 이름으로 표시됩니다.
4
+
5
+ 오프라인에서 작성한 내용은 기기에 먼저 저장되고, 네트워크에 다시 연결되면 자동으로 올라갑니다. 비행기 안에서도 안심하고 쓰셔도 됩니다.
6
+
7
+ 모바일 데이터 사용량을 아끼려면 '와이파이에서만 동기화' 옵션을 켜세요. 이미지 첨부는 와이파이에 연결될 때까지 대기합니다.
8
+
9
+ 동기화 기록은 설정의 기록 탭에서 확인합니다. 어느 기기가 언제 어떤 노트를 바꿨는지 최근 30일치가 남습니다.
10
+
11
+ 실수로 지운 노트는 휴지통에서 30일 동안 복구할 수 있습니다. 휴지통을 비우면 모든 기기에서 영구 삭제됩니다.
12
+
13
+ 동기화 용량은 무료 플랜에서 계정당 2GB입니다. 용량이 가득 차면 새 첨부 파일은 올라가지 않지만 텍스트는 계속 동기화됩니다.
14
+
15
+ 기기를 잃어버렸다면 웹 계정 페이지에서 해당 기기의 로그인을 해제하세요. 해제된 기기는 더 이상 노트를 받아 가지 못합니다.
@@ -0,0 +1,41 @@
1
+ query-id corpus-id score
2
+ q01 backup.ko.md#0000 1
3
+ q02 backup.ko.md#0001 1
4
+ q03 backup.ko.md#0002 1
5
+ q04 backup.ko.md#0003 1
6
+ q05 backup.ko.md#0004 1
7
+ q06 backup.ko.md#0005 1
8
+ q07 backup.ko.md#0006 1
9
+ q08 backup.ko.md#0007 1
10
+ q09 sync.ko.md#0000 1
11
+ q10 sync.ko.md#0001 1
12
+ q11 sync.ko.md#0002 1
13
+ q12 sync.ko.md#0003 1
14
+ q13 sync.ko.md#0004 1
15
+ q14 sync.ko.md#0005 1
16
+ q15 sync.ko.md#0006 1
17
+ q16 sync.ko.md#0007 1
18
+ q17 security.ko.md#0000 1
19
+ q18 security.ko.md#0001 1
20
+ q19 security.ko.md#0002 1
21
+ q20 security.ko.md#0003 1
22
+ q21 security.ko.md#0004 1
23
+ q22 security.ko.md#0005 1
24
+ q23 security.ko.md#0006 1
25
+ q24 security.ko.md#0007 1
26
+ q25 search.en.md#0000 1
27
+ q26 search.en.md#0001 1
28
+ q27 search.en.md#0002 1
29
+ q28 search.en.md#0003 1
30
+ q29 search.en.md#0004 1
31
+ q30 search.en.md#0005 1
32
+ q31 search.en.md#0006 1
33
+ q32 search.en.md#0007 1
34
+ q33 plugins.en.md#0000 1
35
+ q34 plugins.en.md#0001 1
36
+ q35 plugins.en.md#0002 1
37
+ q36 plugins.en.md#0003 1
38
+ q37 plugins.en.md#0004 1
39
+ q38 plugins.en.md#0005 1
40
+ q39 plugins.en.md#0006 1
41
+ q40 plugins.en.md#0007 1
@@ -0,0 +1,40 @@
1
+ {"_id": "q01", "text": "자동으로 백업해 주는 사본은 보관기간이 어떻게 되나요?"}
2
+ {"_id": "q02", "text": "수동으로 백업본을 만드는 메뉴가 어디에 있나요?"}
3
+ {"_id": "q03", "text": "복원하는 순간 지금 작성중인 노트들은 덮어써지나요?"}
4
+ {"_id": "q04", "text": "백업을 저장할 폴더를 외장디스크로 바꾸려는데 설정 항목이 어디죠?"}
5
+ {"_id": "q05", "text": "암호를 건 노트북은 백업해도 암호화돼서 저장되나요?"}
6
+ {"_id": "q06", "text": "첨부된 이미지들 때문에 백업이 느린데 용량을 줄이는 옵션이 있나요?"}
7
+ {"_id": "q07", "text": "백업에 실패했을 때 상태표시줄에 경고가 뜨는 이유가 뭐죠?"}
8
+ {"_id": "q08", "text": "노트 한 건만 마크다운이나 PDF 같은 형식으로 내보낼 수 있나요?"}
9
+ {"_id": "q09", "text": "동기화를 시작하려면 먼저 로그인해야 하나요? 처음에는 시간이 오래 걸리나요?"}
10
+ {"_id": "q10", "text": "노트를 두 기기에서 동시에 편집하면 충돌본은 이름이 어떻게 붙나요?"}
11
+ {"_id": "q11", "text": "오프라인으로 작성한 글은 네트워크 연결 후에 자동 업로드되나요?"}
12
+ {"_id": "q12", "text": "모바일 데이터가 아깝지 않게 와이파이로만 동기화되도록 하고 싶어요"}
13
+ {"_id": "q13", "text": "동기화 이력은 어디서 보고, 어떤 기기가 노트를 수정했는지도 나오나요?"}
14
+ {"_id": "q14", "text": "삭제한 노트를 휴지통에서 복구할 수 있는 기간이 궁금해요"}
15
+ {"_id": "q15", "text": "무료 요금제에서 계정마다 동기화 용량이 얼마까지 가능한가요?"}
16
+ {"_id": "q16", "text": "분실한 기기에서 로그아웃시키려면 웹 계정 페이지를 이용하면 되나요?"}
17
+ {"_id": "q17", "text": "앱을 잠그면 실행할 때마다 지문이나 비밀번호를 요구하나요?"}
18
+ {"_id": "q18", "text": "노트북 암호를 잃어버리면 복구할 수 있는 방법이 있나요?"}
19
+ {"_id": "q19", "text": "서버에는 종단간 암호화 데이터만 저장돼서 운영자도 노트를 못 읽는다던데 맞나요?"}
20
+ {"_id": "q20", "text": "이중인증을 쓰면 새 기기에서 로그인할 때 일회용 코드를 입력해야 하나요?"}
21
+ {"_id": "q21", "text": "화면캡처를 방지하면 스크린샷이 까맣게 찍히나요?"}
22
+ {"_id": "q22", "text": "공유링크는 만료일과 비밀번호를 정할 수 있고 공유 취소도 되나요?"}
23
+ {"_id": "q23", "text": "사용통계를 서버로 보내는 설정이 기본으로 꺼져 있나요?"}
24
+ {"_id": "q24", "text": "보안취약점을 발견했을 때는 신고 주소로 보내면 3일 안에 답장을 받나요?"}
25
+ {"_id": "q25", "text": "How do I jump to a note by typing part of its name?"}
26
+ {"_id": "q26", "text": "Can I look for a specific sentence instead of separate keywords?"}
27
+ {"_id": "q27", "text": "Filtering notes by label in the search box"}
28
+ {"_id": "q28", "text": "Why are my freshly imported notes not showing up in search results?"}
29
+ {"_id": "q29", "text": "Is it possible to find words that appear inside scanned documents?"}
30
+ {"_id": "q30", "text": "Where can I keep a frequently used query handy?"}
31
+ {"_id": "q31", "text": "Restrict results to notes edited in the past seven days"}
32
+ {"_id": "q32", "text": "The search finds notes even when I misspell a word, can I disable that?"}
33
+ {"_id": "q33", "text": "How do I install an extension manually?"}
34
+ {"_id": "q34", "text": "Can an add-on read my files without asking me?"}
35
+ {"_id": "q35", "text": "Which function creates a new note from code?"}
36
+ {"_id": "q36", "text": "My script gets killed after a few seconds, what is the limit?"}
37
+ {"_id": "q37", "text": "What are the steps for sharing my own plugin with other users?"}
38
+ {"_id": "q38", "text": "A misbehaving add-on stopped working by itself; how do I turn it back on?"}
39
+ {"_id": "q39", "text": "Where does an extension keep its configuration, and how do I reset it?"}
40
+ {"_id": "q40", "text": "Do visual themes need any special access rights?"}
embed_ab/evalset.py ADDED
@@ -0,0 +1,127 @@
1
+ """BEIR-style evaluation sets: ``corpus.jsonl``, ``queries.jsonl``, ``qrels.tsv``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+
10
+ class EvalSetError(ValueError):
11
+ """The evaluation set is missing, malformed, or inconsistent."""
12
+
13
+
14
+ @dataclass
15
+ class EvalSet:
16
+ """Documents, queries and graded relevance judgements."""
17
+
18
+ corpus: dict[str, str]
19
+ queries: dict[str, str]
20
+ qrels: dict[str, dict[str, int]] = field(default_factory=dict)
21
+
22
+ def subset_queries(self, max_queries: int | None) -> EvalSet:
23
+ """Keep the first ``max_queries`` queries (file order); the corpus is unchanged."""
24
+ if max_queries is None or max_queries >= len(self.queries):
25
+ return self
26
+ if max_queries < 1:
27
+ raise EvalSetError("max_queries must be at least 1.")
28
+ ids = list(self.queries)[:max_queries]
29
+ return EvalSet(
30
+ corpus=self.corpus,
31
+ queries={q: self.queries[q] for q in ids},
32
+ qrels={q: self.qrels[q] for q in ids},
33
+ )
34
+
35
+
36
+ def _read_jsonl(path: Path, what: str) -> list[tuple[int, dict]]:
37
+ if not path.is_file():
38
+ raise EvalSetError(
39
+ f"{what} file not found: {path}. An evaluation set folder needs corpus.jsonl, "
40
+ "queries.jsonl and qrels.tsv; create one with `embed-ab build-set <docs> --out <dir>`."
41
+ )
42
+ rows: list[tuple[int, dict]] = []
43
+ for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
44
+ if not line.strip():
45
+ continue
46
+ try:
47
+ obj = json.loads(line)
48
+ except json.JSONDecodeError as exc:
49
+ raise EvalSetError(f"{path.name} line {lineno}: invalid JSON ({exc.msg}).") from exc
50
+ if not isinstance(obj, dict) or "_id" not in obj or "text" not in obj:
51
+ raise EvalSetError(f'{path.name} line {lineno}: expected an object with "_id" and "text".')
52
+ rows.append((lineno, obj))
53
+ return rows
54
+
55
+
56
+ def _read_id_text(path: Path, what: str) -> dict[str, str]:
57
+ out: dict[str, str] = {}
58
+ for lineno, obj in _read_jsonl(path, what):
59
+ key = str(obj["_id"])
60
+ if key in out:
61
+ raise EvalSetError(f"{path.name} line {lineno}: duplicate _id {key!r}.")
62
+ text = str(obj["text"])
63
+ title = str(obj.get("title") or "").strip()
64
+ out[key] = f"{title}\n{text}" if title else text
65
+ if not out:
66
+ raise EvalSetError(f"{path.name} is empty; add at least one entry.")
67
+ return out
68
+
69
+
70
+ def load_evalset(path: str | Path) -> EvalSet:
71
+ """Load and validate an evaluation set folder."""
72
+ folder = Path(path)
73
+ if not folder.is_dir():
74
+ raise EvalSetError(f"Evaluation set folder not found: {folder}")
75
+ corpus = _read_id_text(folder / "corpus.jsonl", "corpus")
76
+ queries = _read_id_text(folder / "queries.jsonl", "queries")
77
+
78
+ qrels_path = folder / "qrels.tsv"
79
+ if not qrels_path.is_file():
80
+ raise EvalSetError(f"qrels file not found: {qrels_path}. Expected tab-separated query-id, corpus-id, score.")
81
+ qrels: dict[str, dict[str, int]] = {}
82
+ for lineno, line in enumerate(qrels_path.read_text(encoding="utf-8").splitlines(), start=1):
83
+ if not line.strip():
84
+ continue
85
+ parts = line.split("\t")
86
+ if lineno == 1 and parts[0].strip() == "query-id":
87
+ continue
88
+ if len(parts) != 3:
89
+ raise EvalSetError(f"qrels.tsv line {lineno}: expected 3 tab-separated columns, got {len(parts)}.")
90
+ qid, did, raw = (p.strip() for p in parts)
91
+ try:
92
+ score = int(raw)
93
+ except ValueError as exc:
94
+ raise EvalSetError(f"qrels.tsv line {lineno}: score {raw!r} is not an integer.") from exc
95
+ if qid not in queries:
96
+ raise EvalSetError(f"qrels.tsv line {lineno}: query id {qid!r} is not in queries.jsonl.")
97
+ if did not in corpus:
98
+ raise EvalSetError(f"qrels.tsv line {lineno}: corpus id {did!r} is not in corpus.jsonl.")
99
+ qrels.setdefault(qid, {})[did] = score
100
+
101
+ unjudged = [q for q in queries if not any(s > 0 for s in qrels.get(q, {}).values())]
102
+ if unjudged:
103
+ shown = ", ".join(unjudged[:5])
104
+ raise EvalSetError(
105
+ f"{len(unjudged)} query(ies) have no relevant document in qrels.tsv (e.g. {shown}). "
106
+ "Add a row with score >= 1 for each, or remove those queries from queries.jsonl."
107
+ )
108
+ return EvalSet(corpus=corpus, queries=queries, qrels=qrels)
109
+
110
+
111
+ def write_evalset(evalset: EvalSet, folder: str | Path) -> None:
112
+ """Write the three BEIR files deterministically (same input, same bytes)."""
113
+ out = Path(folder)
114
+ out.mkdir(parents=True, exist_ok=True)
115
+
116
+ def dump(mapping: dict[str, str]) -> str:
117
+ return "".join(
118
+ json.dumps({"_id": k, "text": v}, ensure_ascii=False, sort_keys=True) + "\n" for k, v in mapping.items()
119
+ )
120
+
121
+ (out / "corpus.jsonl").write_text(dump(evalset.corpus), encoding="utf-8")
122
+ (out / "queries.jsonl").write_text(dump(evalset.queries), encoding="utf-8")
123
+ lines = ["query-id\tcorpus-id\tscore"]
124
+ for qid in evalset.queries:
125
+ for did, score in sorted(evalset.qrels.get(qid, {}).items()):
126
+ lines.append(f"{qid}\t{did}\t{score}")
127
+ (out / "qrels.tsv").write_text("\n".join(lines) + "\n", encoding="utf-8")
embed_ab/metrics.py ADDED
@@ -0,0 +1,61 @@
1
+ """Ranking metrics. Each function returns one value per query (a numpy array)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Sequence
7
+
8
+ import numpy as np
9
+
10
+ Ranked = Sequence[Sequence[str]]
11
+ Qrels = Sequence[dict[str, int]] # one {doc_id: grade} per query, aligned with Ranked
12
+
13
+ METRIC_NAMES = ("recall", "ndcg", "mrr", "hit")
14
+
15
+
16
+ def _relevant(judged: dict[str, int]) -> set[str]:
17
+ return {d for d, g in judged.items() if g > 0}
18
+
19
+
20
+ def recall_at_k(ranked: Ranked, qrels: Qrels, k: int) -> np.ndarray:
21
+ """Share of relevant documents found in the top k."""
22
+ out = []
23
+ for docs, judged in zip(ranked, qrels, strict=True):
24
+ rel = _relevant(judged)
25
+ out.append(len(rel & set(docs[:k])) / len(rel) if rel else 0.0)
26
+ return np.array(out)
27
+
28
+
29
+ def hit_at_k(ranked: Ranked, qrels: Qrels, k: int) -> np.ndarray:
30
+ """1.0 if any relevant document is in the top k."""
31
+ return np.array(
32
+ [1.0 if _relevant(j) & set(d[:k]) else 0.0 for d, j in zip(ranked, qrels, strict=True)]
33
+ )
34
+
35
+
36
+ def mrr_at_k(ranked: Ranked, qrels: Qrels, k: int) -> np.ndarray:
37
+ """Reciprocal rank of the first relevant document within the top k."""
38
+ out = []
39
+ for docs, judged in zip(ranked, qrels, strict=True):
40
+ rel = _relevant(judged)
41
+ out.append(next((1.0 / (i + 1) for i, d in enumerate(docs[:k]) if d in rel), 0.0))
42
+ return np.array(out)
43
+
44
+
45
+ def ndcg_at_k(ranked: Ranked, qrels: Qrels, k: int) -> np.ndarray:
46
+ """nDCG with linear gain (grade) and log2(rank + 1) discount."""
47
+ out = []
48
+ for docs, judged in zip(ranked, qrels, strict=True):
49
+ dcg = sum(max(judged.get(d, 0), 0) / math.log2(i + 2) for i, d in enumerate(docs[:k]))
50
+ ideal = sorted((g for g in judged.values() if g > 0), reverse=True)[:k]
51
+ idcg = sum(g / math.log2(i + 2) for i, g in enumerate(ideal))
52
+ out.append(dcg / idcg if idcg > 0 else 0.0)
53
+ return np.array(out)
54
+
55
+
56
+ _FUNCS = {"recall": recall_at_k, "ndcg": ndcg_at_k, "mrr": mrr_at_k, "hit": hit_at_k}
57
+
58
+
59
+ def all_metrics(ranked: Ranked, qrels: Qrels, k: int) -> dict[str, np.ndarray]:
60
+ """Per-query arrays keyed ``recall@k``, ``ndcg@k``, ``mrr@k``, ``hit@k``."""
61
+ return {f"{name}@{k}": fn(ranked, qrels, k) for name, fn in _FUNCS.items()}