@fffangchenghao/dsh-web-search 0.17.0 → 0.18.0
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.
- package/CHANGELOG.md +29 -0
- package/README.md +6 -6
- package/README.zh-CN.md +6 -6
- package/client.js +1 -1
- package/docs/rrf-ranking.md +18 -0
- package/lib/engines.js +7 -2
- package/lib/rank.js +15 -2
- package/lib/relevance.d.ts +57 -0
- package/lib/relevance.js +77 -0
- package/lib/types.d.ts +8 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.18.0
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
- **Chinese queries no longer drag dictionary pages into the answer.** A long or
|
|
7
|
+
mixed query (`东数西算 八个国家枢纽节点 定位`, `如何配置 postgres 逻辑复制`)
|
|
8
|
+
made `cn.bing` answer with rows about a single character — `东(汉语文字)`,
|
|
9
|
+
`如何(汉语词语)`, a company named 李在东 — and those rows collected votes in
|
|
10
|
+
the fusion. A CJK relevance gate now splits the query into character bigrams
|
|
11
|
+
and keeps a row only when its title, snippet or URL accumulates two units of
|
|
12
|
+
overlap; an ASCII word counts double, so a PostgreSQL page survives a mixed
|
|
13
|
+
query on `postgres` alone. An engine whose entire list is filtered is reported
|
|
14
|
+
as `<id>: no relevant results`, which lets the fallback tier run instead of
|
|
15
|
+
returning the junk.
|
|
16
|
+
- **Chinese official domains earn the authority boost.** `gov.cn`, `edu.cn`,
|
|
17
|
+
`news.cn`, `people.com.cn`, `xinhuanet.com`, `ncsti.gov.cn` and `cas.cn` join
|
|
18
|
+
the default authority list, so a ministry page outranks an SEO repost or a
|
|
19
|
+
Baidu Baike entry at the same fused position.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
- `RankOptions.query` carries the query into fusion; `scripts/bench.mjs` passes
|
|
23
|
+
the fixture's query, so offline replay applies the same gate production uses.
|
|
24
|
+
- The 20-query benchmark is byte-for-byte unchanged (`0.4375 / 0.7917 / 0.8071`):
|
|
25
|
+
the recorded fixtures do not contain the dictionary-page failure mode.
|
|
26
|
+
|
|
27
|
+
### Tests
|
|
28
|
+
- 493 cases (492 pass, one environment skip), including the new
|
|
29
|
+
`test/relevance.test.ts` coverage for dropped dictionary/company rows, URL-slug
|
|
30
|
+
matches, English passthrough and the mixed-query ASCII weight.
|
|
31
|
+
|
|
3
32
|
## 0.17.0
|
|
4
33
|
|
|
5
34
|
### Fixed
|
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
<p align="center">
|
|
11
11
|
<a href="https://www.npmjs.com/package/@fffangchenghao/dsh-web-search"><img src="https://img.shields.io/npm/v/@fffangchenghao/dsh-web-search.svg" alt="npm version"></a>
|
|
12
|
-
<img src="https://img.shields.io/badge/tests-
|
|
12
|
+
<img src="https://img.shields.io/badge/tests-492%20passing-brightgreen" alt="tests">
|
|
13
13
|
<img src="https://img.shields.io/badge/engines-8%2C%20zero%20API%20key-brightgreen" alt="engines">
|
|
14
14
|
<img src="https://img.shields.io/badge/node-%3E%3D22.18-blue" alt="node">
|
|
15
15
|
<img src="https://img.shields.io/badge/dsh-%3E%3D0.2.1--rc.2%20%3C0.3.0-blueviolet" alt="dsh">
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
- **No API key, eight engines.** AnySearch, CN Bing, DuckDuckGo HTML, www Bing, DuckDuckGo Lite and 360 Search are scraped directly; Exa joins the primary tier through its keyless MCP endpoint, and Firecrawl's search API is the measured fallback. The plugin works out of the box.
|
|
22
22
|
- **The ranking is measured, not asserted.** Cross-engine reciprocal-rank fusion with authority and freshness boosts, a 20-query offline benchmark, and an 81-configuration parameter sweep — the only search plugin here that publishes both its metric and its confidence intervals. See [How the ranking works](docs/rrf-ranking.md).
|
|
23
23
|
- **Fetching admits failure.** Binary documents and empty 200 responses are rejected by name (`SEARCH_UNSUPPORTED`, `SEARCH_EMPTY`) instead of being returned as noise; the direct → tunnel → render → extract ladder shares one 25 s budget and stops when there is no time left. The budget is per request — there is a regression test for exactly that.
|
|
24
|
-
- **
|
|
24
|
+
- **493 tests across 32 files**, a committed `lib/`, declared `engines.dsh` / `engines.node`, and a [SECURITY.md](SECURITY.md) that lists every process, host and file the plugin touches.
|
|
25
25
|
- **Bilingual documentation.** This README and [中文说明](README.zh-CN.md) are maintained side by side.
|
|
26
26
|
|
|
27
27
|

|
|
@@ -37,7 +37,7 @@ The web-search corner of the DSH plugin ecosystem is crowded, and most rivals ar
|
|
|
37
37
|
| Key-free engines | 8 | ~30 | 7 channels (+X) | 1 official API |
|
|
38
38
|
| Dedicated vertical sources | 34 (8 on by default) | 41 | — | — |
|
|
39
39
|
| Model-facing tools | 6 | ~10 | 3 | 5 |
|
|
40
|
-
| Test suite |
|
|
40
|
+
| Test suite | 32 files / 493 cases | none | 29 files | 6 files |
|
|
41
41
|
| Ranking benchmark | 20 queries + 81-config sweep | — | — | — |
|
|
42
42
|
| Store status | source contract satisfied, awaiting review | unlisted | no entry | blocked (review-required) |
|
|
43
43
|
|
|
@@ -240,9 +240,9 @@ Each line is the plain version first, the technical note second. The technical n
|
|
|
240
240
|
Domains such as `kubernetes.io`, `developer.mozilla.org` and `rfc-editor.org` get a boost, as does anything published within 30 days.
|
|
241
241
|
*Technical: `score = votes / (rrfConstant + position)`, then `× (1 + authorityBoost)` and a freshness factor; defaults `rrfConstant: 60`, `authorityBoost: 0.25`, `freshnessBoost: 0.2`, `freshnessDays: 30`. Publication dates are now parsed from each engine's results, so the freshness term scores a real date instead of sitting idle.*
|
|
242
242
|
|
|
243
|
-
5. **Chinese and English are handled separately.**
|
|
244
|
-
English queries lead with global sources, Chinese queries with Chinese sources, so "how to …" is not answered with a dictionary page for the word `how`.
|
|
245
|
-
*Technical: `lead = cn` when the query contains CJK characters, `lead = global` for plain ASCII; the other region only appends when the leading one comes up short.*
|
|
243
|
+
5. **Chinese and English are handled separately, and Chinese rows must talk about the question.**
|
|
244
|
+
English queries lead with global sources, Chinese queries with Chinese sources, so "how to …" is not answered with a dictionary page for the word `how`. A scraped Chinese engine can still fall back to single-character dictionary and company pages for a long query; those rows are dropped before fusion unless they share at least two words with the question, and `.gov.cn` / `.edu.cn` official pages get the authority boost.
|
|
245
|
+
*Technical: `lead = cn` when the query contains CJK characters, `lead = global` for plain ASCII; the other region only appends when the leading one comes up short. `src/relevance.ts` splits a CJK query into character bigrams (an ASCII word counts double), requires two weight units of overlap with title, snippet or URL, and returns English queries untouched. Measured on `东数西算 八个国家枢纽节点 定位`, `cn.bing` answered with ten dictionary/company rows; the gate now reports `cn.bing: no relevant results` and the fused list keeps the NDRC/百科/news rows.*
|
|
246
246
|
|
|
247
247
|
6. **You choose speed or completeness.**
|
|
248
248
|
`auto` waits up to 6 s for English and 3.5 s for Chinese; `fast` takes whoever answers first; `all` waits for everyone, up to 10 s.
|
package/README.zh-CN.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
<p align="center">
|
|
11
11
|
<a href="https://www.npmjs.com/package/@fffangchenghao/dsh-web-search"><img src="https://img.shields.io/npm/v/@fffangchenghao/dsh-web-search.svg" alt="npm 版本"></a>
|
|
12
|
-
<img src="https://img.shields.io/badge/tests-
|
|
12
|
+
<img src="https://img.shields.io/badge/tests-492%20passing-brightgreen" alt="测试">
|
|
13
13
|
<img src="https://img.shields.io/badge/engines-8%2C%20zero%20API%20key-brightgreen" alt="引擎">
|
|
14
14
|
<img src="https://img.shields.io/badge/node-%3E%3D22.18-blue" alt="node">
|
|
15
15
|
<img src="https://img.shields.io/badge/dsh-%3E%3D0.2.1--rc.2%20%3C0.3.0-blueviolet" alt="dsh">
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
- **不要 API key,八个引擎。** AnySearch、必应中国、DuckDuckGo HTML、必应国际、DuckDuckGo Lite、360 搜索直接抓取;Exa 走它的免密钥 MCP 通道加入主引擎,Firecrawl 的搜索 API 作为实测后的兜底。装好就能用。
|
|
22
22
|
- **排序是量出来的,不是写出来的。** 跨引擎 RRF 融合,叠加权威度与时效加权;20 条离线基准 + 81 组参数扫描,是这类插件里唯一同时公开指标和置信区间的。方法见 [排序是怎么做的](docs/rrf-ranking.md)。
|
|
23
23
|
- **抓取会承认失败。** 二进制文档和「200 但正文为空」会被明确拒绝(`SEARCH_UNSUPPORTED`、`SEARCH_EMPTY`),而不是当噪音返回;direct → tunnel → render → extract 四级阶梯共享 25 秒预算,预算不足就不再起新的一级。预算是「每次请求」而不是「插件启动时」,这点有回归测试守着。
|
|
24
|
-
- **
|
|
24
|
+
- **32 个测试文件、493 个用例**,`lib/` 产物入库,声明了 `engines.dsh` / `engines.node`,[SECURITY.md](SECURITY.md) 逐项列出插件会碰的进程、主机和文件。
|
|
25
25
|
- **双语文档。** 本文件和 [English README](README.md) 同步维护。
|
|
26
26
|
|
|
27
27
|

|
|
@@ -37,7 +37,7 @@ DSH 插件生态里的「联网搜索」这一块已经很挤,大多数竞品
|
|
|
37
37
|
| 免 key 引擎 | 8 | ~30 | 7 条通道(含 X) | 1 个官方 API |
|
|
38
38
|
| 专门数据源 | 34(默认开 8 个)| 41 | — | — |
|
|
39
39
|
| 面向模型的工具 | 6 | ~10 | 3 | 5 |
|
|
40
|
-
| 测试 |
|
|
40
|
+
| 测试 | 32 文件 / 493 用例 | 无 | 29 文件 | 6 文件 |
|
|
41
41
|
| 排序基准 | 20 查询 + 81 组扫描 | — | — | — |
|
|
42
42
|
| 商店状态 | 源码契约已满足,待复核 | unlisted | 无条目 | blocked(review-required) |
|
|
43
43
|
|
|
@@ -240,9 +240,9 @@ Harness 里有个叫 `web` 的**服务**,它自己不会搜索,只负责「
|
|
|
240
240
|
`kubernetes.io`、`developer.mozilla.org`、`rfc-editor.org` 这类域名会被加权;30 天内发布的内容也会被加权。
|
|
241
241
|
*技术补充:`score = votes / (rrfConstant + position)`,再乘 `1 + authorityBoost` 和新鲜度系数;默认 `rrfConstant: 60`、`authorityBoost: 0.25`、`freshnessBoost: 0.2`、`freshnessDays: 30`。发布日期由各引擎的结果解析而来,所以新鲜度这一项现在按真实日期计算,不再空转。*
|
|
242
242
|
|
|
243
|
-
5.
|
|
244
|
-
英文问题先看国外来源,中文问题先看中文来源,避免「how to …」被某个中文引擎按单词 `how`
|
|
245
|
-
*技术补充:查询含 CJK 字符时 `lead = cn`,纯 ASCII 时 `lead = global
|
|
243
|
+
5. **中英文分开处理,而且中文结果必须真的在讲这个问题。**
|
|
244
|
+
英文问题先看国外来源,中文问题先看中文来源,避免「how to …」被某个中文引擎按单词 `how` 匹配成词典页。中文长查询仍可能被引擎退化成单字词典页、公司页;这些行在融合前会被丢掉,除非标题/摘要/URL 与问题至少重合两个词;`.gov.cn` / `.edu.cn` 官方页面另有权威度加权。
|
|
245
|
+
*技术补充:查询含 CJK 字符时 `lead = cn`,纯 ASCII 时 `lead = global`;非主导区只在主导区凑不够条数时才追加。`src/relevance.ts` 把中文查询切成二字 bigram(ASCII 单词权重翻倍),要求与标题、摘要或 URL 至少两个权重单位的重合;英文查询原样放行。用「东数西算 八个国家枢纽节点 定位」实测:`cn.bing` 返回十条词典/公司页,现在会报 `cn.bing: no relevant results`,融合结果保留发改委/百科/新闻页。*
|
|
246
246
|
|
|
247
247
|
6. **快慢可以选。**
|
|
248
248
|
默认 `auto`:英文最多等 6 秒、中文最多等 3.5 秒;`fast` 谁先回就用谁;`all` 等所有引擎,最多 10 秒。
|
package/client.js
CHANGED
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
var ENTRY = 'web-search-bing';
|
|
48
48
|
var PACKAGE_NAME = 'dsh-web-search-bing';
|
|
49
49
|
/** Keep in step with package.json; compared with the npm registry. */
|
|
50
|
-
var VERSION = '0.
|
|
50
|
+
var VERSION = '0.18.0';
|
|
51
51
|
/** Snapshot used while no configuration service is reachable. */
|
|
52
52
|
var EMPTY_STATE = { status: 'unavailable', value: undefined, base: undefined, user: undefined, revision: undefined, writable: false };
|
|
53
53
|
|
package/docs/rrf-ranking.md
CHANGED
|
@@ -131,6 +131,24 @@ Exa therefore leads; Firecrawl is parsed and tested but ships as the fallback,
|
|
|
131
131
|
available through `hostIds: ['firecrawl']` and used whenever every primary
|
|
132
132
|
returns nothing.
|
|
133
133
|
|
|
134
|
+
|
|
135
|
+
## CJK relevance gate
|
|
136
|
+
|
|
137
|
+
Fusion assumes each engine's list is about the query. A scraped Chinese engine
|
|
138
|
+
sometimes is not: `cn.bing` answered `东数西算 八个国家枢纽节点 定位` with ten
|
|
139
|
+
rows for the character `东` (dictionary entries, a company named 李在东), and
|
|
140
|
+
those rows would otherwise collect votes like any other engine's. Before fusion,
|
|
141
|
+
`src/relevance.ts` builds overlapping two-character tokens from the query and
|
|
142
|
+
keeps a row only when its title, snippet or URL accumulates two units of
|
|
143
|
+
overlap. An ASCII word is worth two units, so a PostgreSQL page in a mixed
|
|
144
|
+
query (`如何配置 postgres 逻辑复制`) survives on `postgres` alone, while
|
|
145
|
+
`如何(汉语词语)_百度百科` does not. English queries are returned unchanged.
|
|
146
|
+
|
|
147
|
+
The gate lives in both the engine tier (so an engine whose whole list is junk is
|
|
148
|
+
reported as `no relevant results` and the fallback tier can run) and the ranker
|
|
149
|
+
(so offline replay applies the same rule). On the 20-query bench it changes no
|
|
150
|
+
metric: the recorded fixtures do not contain that failure mode.
|
|
151
|
+
|
|
134
152
|
## Known limits
|
|
135
153
|
|
|
136
154
|
- **Relative Chinese time words.** A query like "上周发布的那版" carries its time
|
package/lib/engines.js
CHANGED
|
@@ -3,6 +3,7 @@ import { filterByTimeRange, preferWindow } from "./freshness.js";
|
|
|
3
3
|
import { resolveProxy } from "./proxy.js";
|
|
4
4
|
import { parseAnySearch, parseBing, parseDdgHtml, parseDdgLite, parseExaMcp, parseFirecrawl, parseSo } from "./parsers.js";
|
|
5
5
|
import { mergeRegions } from "./rank.js";
|
|
6
|
+
import { filterRelevant } from "./relevance.js";
|
|
6
7
|
import { cacheKey } from "./cache.js";
|
|
7
8
|
import { searchHost } from "./transport.js";
|
|
8
9
|
import { keyFailureKind, keyPoolFor } from "./keys.js";
|
|
@@ -243,6 +244,8 @@ async function runTier(hosts, query, signal, timeoutMs, failures, proxy, limits,
|
|
|
243
244
|
const relayAbort = () => controller.abort();
|
|
244
245
|
signal?.addEventListener('abort', relayAbort, { once: true });
|
|
245
246
|
const outcomes = new Array(hosts.length).fill(undefined);
|
|
247
|
+
/** Rows each engine returned before the CJK relevance gate, for the failure text. */
|
|
248
|
+
const rawCounts = new Array(hosts.length).fill(0);
|
|
246
249
|
const answered = () => outcomes.filter((outcome) => outcome instanceof SearchError || outcome !== undefined);
|
|
247
250
|
const available = () => outcomes.reduce((total, outcome) => total + (outcome instanceof SearchError || outcome === undefined ? 0 : outcome.sources.length), 0);
|
|
248
251
|
const contributors = () => outcomes.filter((outcome, index) => counters(hosts[index]) && !(outcome instanceof SearchError) && outcome !== undefined && outcome.sources.length > 0).length;
|
|
@@ -268,7 +271,8 @@ async function runTier(hosts, query, signal, timeoutMs, failures, proxy, limits,
|
|
|
268
271
|
};
|
|
269
272
|
const running = hosts.map((host, index) => searchHostWithKeys(host, query, controller.signal, timeoutMs, proxy, limits.timeRange, pool, anysearchDomain).then((outcome) => {
|
|
270
273
|
if (outcome.ok) {
|
|
271
|
-
|
|
274
|
+
rawCounts[index] = outcome.sources.length;
|
|
275
|
+
outcomes[index] = { host, sources: filterRelevant(outcome.sources, query) };
|
|
272
276
|
health?.noteSuccess(host.id);
|
|
273
277
|
}
|
|
274
278
|
else {
|
|
@@ -307,7 +311,7 @@ async function runTier(hosts, query, signal, timeoutMs, failures, proxy, limits,
|
|
|
307
311
|
failures.push(outcome.message);
|
|
308
312
|
}
|
|
309
313
|
else if (outcome.sources.length === 0) {
|
|
310
|
-
failures.push(`${host.id}: no results`);
|
|
314
|
+
failures.push(`${host.id}: ${(rawCounts[index] ?? 0) > 0 ? 'no relevant results' : 'no results'}`);
|
|
311
315
|
}
|
|
312
316
|
else {
|
|
313
317
|
answers.push(outcome);
|
|
@@ -400,6 +404,7 @@ export async function search(query, signal, options) {
|
|
|
400
404
|
// documented shape of `ResolvedConfig.rank`.
|
|
401
405
|
const rank = {
|
|
402
406
|
...(options.rank ?? {}),
|
|
407
|
+
query,
|
|
403
408
|
...(timeRange === 'off' ? {} : { timeRange }),
|
|
404
409
|
};
|
|
405
410
|
/**
|
package/lib/rank.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { publishedTimestamp } from "./freshness.js";
|
|
2
|
+
import { filterRelevant } from "./relevance.js";
|
|
2
3
|
/**
|
|
3
4
|
* Reciprocal-rank-fusion constant over the interleaved slot order; a larger
|
|
4
5
|
* value flattens the curve so authority and freshness reorder more freely.
|
|
@@ -27,6 +28,17 @@ export const DEFAULT_AUTHORITY_DOMAINS = [
|
|
|
27
28
|
'dev.mysql.com',
|
|
28
29
|
'redis.io',
|
|
29
30
|
'nginx.org',
|
|
31
|
+
// Chinese official domains: policy and standards pages from a ministry or a
|
|
32
|
+
// university outrank the SEO reposts and dictionary pages that a scraped
|
|
33
|
+
// Chinese engine returns at the same rank. The suffix match in
|
|
34
|
+
// `isAuthoritative` makes `gov.cn` cover every ministry subdomain.
|
|
35
|
+
'gov.cn',
|
|
36
|
+
'edu.cn',
|
|
37
|
+
'news.cn',
|
|
38
|
+
'people.com.cn',
|
|
39
|
+
'xinhuanet.com',
|
|
40
|
+
'ncsti.gov.cn',
|
|
41
|
+
'cas.cn',
|
|
30
42
|
];
|
|
31
43
|
/** Multiplier added for an authoritative domain by default. */
|
|
32
44
|
export const DEFAULT_AUTHORITY_BOOST = 0.25;
|
|
@@ -331,8 +343,9 @@ function fuseEntries(entries, limit, options) {
|
|
|
331
343
|
for (const entry of entries) {
|
|
332
344
|
const seen = new Set();
|
|
333
345
|
const rows = [];
|
|
334
|
-
|
|
335
|
-
|
|
346
|
+
const sources = options.query === undefined ? entry.sources : filterRelevant(entry.sources, options.query);
|
|
347
|
+
for (let index = 0; index < sources.length; index += 1) {
|
|
348
|
+
const source = sources[index];
|
|
336
349
|
if (source === undefined)
|
|
337
350
|
continue;
|
|
338
351
|
if (typeof source.url !== 'string' || source.url.trim() === '')
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lexical relevance for CJK queries.
|
|
3
|
+
*
|
|
4
|
+
* A Chinese query sent to a scraped engine can come back as a dictionary entry
|
|
5
|
+
* for one character of it: `东数西算 八个国家枢纽节点 定位` against `cn.bing`
|
|
6
|
+
* returned `东(汉语文字)`, `东的意思…`, and a company named 李在东, none of
|
|
7
|
+
* which share a word with the question. The engines' own rank order cannot be
|
|
8
|
+
* trusted for those rows, and letting them into the fusion is worse than
|
|
9
|
+
* dropping them: one engine's ten junk rows can outweigh the three good rows
|
|
10
|
+
* another engine found.
|
|
11
|
+
*
|
|
12
|
+
* The check is deliberately lexical and conservative: a CJK query is split into
|
|
13
|
+
* overlapping two-character tokens (its bigrams), and a row must share at least
|
|
14
|
+
* two of them with its title, snippet or URL. Two matches is enough for a page
|
|
15
|
+
* that mentions the entity and the aspect, and it is exactly what a
|
|
16
|
+
* single-character dictionary page cannot produce. English queries are left
|
|
17
|
+
* alone; their engines did not show this failure mode, and an ASCII word
|
|
18
|
+
* overlap would start rejecting legitimate paraphrases.
|
|
19
|
+
*
|
|
20
|
+
* @module @fangchenghao/dsh-web-search/relevance
|
|
21
|
+
*/
|
|
22
|
+
import type { Source } from './types.ts';
|
|
23
|
+
/** One overlap token and how much evidence a match is worth. */
|
|
24
|
+
export interface QueryToken {
|
|
25
|
+
text: string;
|
|
26
|
+
/** ASCII words are specific (`postgres`), so a match is worth two bigrams. */
|
|
27
|
+
weight: number;
|
|
28
|
+
}
|
|
29
|
+
/** A CJK query prepared for overlap checks. */
|
|
30
|
+
export interface QueryProfile {
|
|
31
|
+
/** True when the query contains at least one CJK character. */
|
|
32
|
+
cjk: boolean;
|
|
33
|
+
/** Distinct two-character tokens (CJK bigrams) plus ASCII words. */
|
|
34
|
+
tokens: QueryToken[];
|
|
35
|
+
/** How many weight units a row must accumulate. */
|
|
36
|
+
required: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Build the overlap profile for a query.
|
|
40
|
+
* @param query - the user's question.
|
|
41
|
+
* @returns the profile; `cjk` is false for an English-only query.
|
|
42
|
+
*/
|
|
43
|
+
export declare function queryProfile(query: string): QueryProfile;
|
|
44
|
+
/**
|
|
45
|
+
* Whether one row talks about the query at all.
|
|
46
|
+
* @param source - engine row with title, snippet and URL.
|
|
47
|
+
* @param profile - prepared query tokens.
|
|
48
|
+
* @returns true when at least `profile.required` distinct tokens appear.
|
|
49
|
+
*/
|
|
50
|
+
export declare function isRelevant(source: Source, profile: QueryProfile): boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Drop rows that do not share enough words with a CJK query.
|
|
53
|
+
* @param sources - one engine's rows.
|
|
54
|
+
* @param query - the user's question.
|
|
55
|
+
* @returns the rows that survive; English queries are returned unchanged.
|
|
56
|
+
*/
|
|
57
|
+
export declare function filterRelevant(sources: readonly Source[], query: string): Source[];
|
package/lib/relevance.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** Runs of CJK characters (Han, kana, Hangul). */
|
|
2
|
+
const CJK_RUN = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff]+/gu;
|
|
3
|
+
/** Common CJK function-word bigrams that match almost any page. */
|
|
4
|
+
const CJK_STOPWORDS = new Set([
|
|
5
|
+
'的是', '了吗', '什么', '怎么', '如何', '哪些', '多少', '一下', '请问',
|
|
6
|
+
'帮我', '告诉', '介绍', '以及', '或者', '还是', '就是', '可以', '需要',
|
|
7
|
+
]);
|
|
8
|
+
/**
|
|
9
|
+
* Build the overlap profile for a query.
|
|
10
|
+
* @param query - the user's question.
|
|
11
|
+
* @returns the profile; `cjk` is false for an English-only query.
|
|
12
|
+
*/
|
|
13
|
+
export function queryProfile(query) {
|
|
14
|
+
const text = query.toLowerCase();
|
|
15
|
+
const tokens = new Map();
|
|
16
|
+
let cjk = false;
|
|
17
|
+
for (const run of text.match(CJK_RUN) ?? []) {
|
|
18
|
+
cjk = true;
|
|
19
|
+
if (run.length === 1) {
|
|
20
|
+
// A one-character query has no bigram; keep the character itself so the
|
|
21
|
+
// check still has something to match.
|
|
22
|
+
tokens.set(run, { text: run, weight: 1 });
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
for (let index = 0; index < run.length - 1; index += 1) {
|
|
26
|
+
const bigram = run.slice(index, index + 2);
|
|
27
|
+
if (!CJK_STOPWORDS.has(bigram))
|
|
28
|
+
tokens.set(bigram, { text: bigram, weight: 1 });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
// A specific ASCII word is stronger evidence than a two-character slice of a
|
|
32
|
+
// Chinese phrase: a PostgreSQL page can match `postgres` without containing
|
|
33
|
+
// any of the Chinese words around it, and dropping it would be worse than
|
|
34
|
+
// keeping a dictionary page.
|
|
35
|
+
for (const word of text.match(/[a-z][a-z0-9.+#_-]{2,}/gu) ?? [])
|
|
36
|
+
tokens.set(word, { text: word, weight: 2 });
|
|
37
|
+
const required = !cjk || tokens.size <= 1 ? 1 : Math.min(3, Math.max(2, Math.ceil(tokens.size * 0.2)));
|
|
38
|
+
return { cjk, tokens: [...tokens.values()], required };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Whether one row talks about the query at all.
|
|
42
|
+
* @param source - engine row with title, snippet and URL.
|
|
43
|
+
* @param profile - prepared query tokens.
|
|
44
|
+
* @returns true when at least `profile.required` distinct tokens appear.
|
|
45
|
+
*/
|
|
46
|
+
export function isRelevant(source, profile) {
|
|
47
|
+
if (!profile.cjk)
|
|
48
|
+
return true;
|
|
49
|
+
let haystack = `${source.title ?? ''} ${source.snippet ?? ''}`.toLowerCase();
|
|
50
|
+
try {
|
|
51
|
+
haystack += ` ${decodeURIComponent(source.url)}`.toLowerCase();
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
haystack += ` ${source.url}`.toLowerCase();
|
|
55
|
+
}
|
|
56
|
+
let matched = 0;
|
|
57
|
+
for (const token of profile.tokens) {
|
|
58
|
+
if (haystack.includes(token.text)) {
|
|
59
|
+
matched += token.weight;
|
|
60
|
+
if (matched >= profile.required)
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return profile.required === 0;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Drop rows that do not share enough words with a CJK query.
|
|
68
|
+
* @param sources - one engine's rows.
|
|
69
|
+
* @param query - the user's question.
|
|
70
|
+
* @returns the rows that survive; English queries are returned unchanged.
|
|
71
|
+
*/
|
|
72
|
+
export function filterRelevant(sources, query) {
|
|
73
|
+
const profile = queryProfile(query);
|
|
74
|
+
if (!profile.cjk)
|
|
75
|
+
return [...sources];
|
|
76
|
+
return sources.filter((source) => isRelevant(source, profile));
|
|
77
|
+
}
|
package/lib/types.d.ts
CHANGED
|
@@ -125,6 +125,14 @@ export interface RankOptions {
|
|
|
125
125
|
timeRange?: TimeRange;
|
|
126
126
|
/** Per-engine weight in the pre-fusion interleave. */
|
|
127
127
|
weights?: number[];
|
|
128
|
+
/**
|
|
129
|
+
* The query the engine rows answer.
|
|
130
|
+
*
|
|
131
|
+
* When present, CJK rows that share too few words with it are discarded
|
|
132
|
+
* before fusion (see `relevance.ts`). Bench replay passes the fixture's query
|
|
133
|
+
* so an offline run measures the same gate production applies.
|
|
134
|
+
*/
|
|
135
|
+
query?: string;
|
|
128
136
|
/**
|
|
129
137
|
* Evaluation instant in milliseconds for the freshness boost, defaulting to
|
|
130
138
|
* `Date.now()`. Benchmarks pin this to the fixture's recording time so a
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fffangchenghao/dsh-web-search",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "DSH bundle: a key-free web search provider. Leads with the anonymous AnySearch API and falls back to public result pages (DuckDuckGo, Bing, 360), merged by reciprocal-rank fusion with a bilingual region policy, an engine cooldown and a TTL cache.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|