awcrowd 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.
- awcrowd/__init__.py +9 -0
- awcrowd/__main__.py +3 -0
- awcrowd/cli.py +241 -0
- awcrowd/consent.py +102 -0
- awcrowd/export.py +106 -0
- awcrowd/federation.py +122 -0
- awcrowd/model.py +72 -0
- awcrowd/query.py +203 -0
- awcrowd/sources/__init__.py +34 -0
- awcrowd/sources/discord_store.py +167 -0
- awcrowd/sources/files.py +116 -0
- awcrowd/weighting.py +105 -0
- awcrowd-0.1.0.dist-info/METADATA +277 -0
- awcrowd-0.1.0.dist-info/RECORD +17 -0
- awcrowd-0.1.0.dist-info/WHEEL +4 -0
- awcrowd-0.1.0.dist-info/entry_points.txt +2 -0
- awcrowd-0.1.0.dist-info/licenses/LICENSE +202 -0
awcrowd/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""awcrowd -- Aither World Crowd: one model for votes, answers, posts and ratings,
|
|
2
|
+
read from the stores that already hold them, asked questions with citations."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
from .model import Response # noqa: E402
|
|
8
|
+
|
|
9
|
+
__all__ = ["Response", "__version__"]
|
awcrowd/__main__.py
ADDED
awcrowd/cli.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""awcrowd -- ask your crowd, keep every answer, and ask the answers a question.
|
|
2
|
+
|
|
3
|
+
awcrowd sources --source discord:guilds.db what each source holds
|
|
4
|
+
awcrowd query "<question>" --source ... [--scope guild=<id>] [--role <id>] [--since 7d]
|
|
5
|
+
awcrowd export --anonymized --out <dir> --source ...
|
|
6
|
+
awcrowd consent grant|withdraw --world <id> [--person <id>]
|
|
7
|
+
awcrowd aggregate --source ... [--k 10] the cross-world shape
|
|
8
|
+
awcrowd decide --yes 7 --no 2 --eligible 10 the community vote rule
|
|
9
|
+
awcrowd --self-test
|
|
10
|
+
|
|
11
|
+
Sources can also come from ``AWCROWD_SOURCES`` (comma separated). State (the consent
|
|
12
|
+
ledger) lives in ``AWCROWD_HOME`` (default ``~/.awcrowd``).
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from . import __version__, sources
|
|
24
|
+
from .consent import ConsentLedger
|
|
25
|
+
from .export import export
|
|
26
|
+
from .federation import WorldPolicy, aggregate
|
|
27
|
+
from .query import Scope, parse_since, query
|
|
28
|
+
from .weighting import decide
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def home() -> Path:
|
|
32
|
+
return Path(os.environ.get("AWCROWD_HOME") or Path.home() / ".awcrowd")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _ledger() -> ConsentLedger:
|
|
36
|
+
return ConsentLedger(home() / "consent.jsonl",
|
|
37
|
+
policy=os.environ.get("AWCROWD_CONSENT_POLICY", "source_default"))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _specs(a) -> list[str]:
|
|
41
|
+
specs = list(a.source or [])
|
|
42
|
+
if not specs and os.environ.get("AWCROWD_SOURCES"):
|
|
43
|
+
specs = [s.strip() for s in os.environ["AWCROWD_SOURCES"].split(",") if s.strip()]
|
|
44
|
+
if not specs:
|
|
45
|
+
raise SystemExit("awcrowd: no source; pass --source <kind>:<path> or set "
|
|
46
|
+
"AWCROWD_SOURCES")
|
|
47
|
+
return specs
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _visibility(a) -> dict[str, str]:
|
|
51
|
+
out = {}
|
|
52
|
+
for item in a.visibility or []:
|
|
53
|
+
world, _, vis = item.partition("=")
|
|
54
|
+
out[world] = vis or "private"
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _load(a):
|
|
59
|
+
return _ledger().filter(sources.load_all(_specs(a), _visibility(a)))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _scope(a) -> Scope:
|
|
63
|
+
world = ""
|
|
64
|
+
for item in a.scope or []:
|
|
65
|
+
k, _, v = item.partition("=")
|
|
66
|
+
if k in ("guild", "world", "workspace"):
|
|
67
|
+
world = v
|
|
68
|
+
elif k == "role":
|
|
69
|
+
a.role = v
|
|
70
|
+
elif k == "since":
|
|
71
|
+
a.since = v
|
|
72
|
+
return Scope(world=world, role=a.role or "", since=parse_since(a.since or ""))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def cmd_sources(a) -> int:
|
|
76
|
+
rs = _load(a)
|
|
77
|
+
by: dict[str, dict[str, int]] = {}
|
|
78
|
+
for r in rs:
|
|
79
|
+
by.setdefault(r.source, {}).setdefault(r.kind, 0)
|
|
80
|
+
by[r.source][r.kind] += 1
|
|
81
|
+
print(json.dumps({"responses": len(rs), "by_source": by}, indent=1))
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cmd_query(a) -> int:
|
|
86
|
+
ans = query(a.question, _load(a), _scope(a), use_llm=not a.no_llm)
|
|
87
|
+
if a.json:
|
|
88
|
+
print(json.dumps(ans.to_dict(), indent=1))
|
|
89
|
+
return 0
|
|
90
|
+
print(ans.answer)
|
|
91
|
+
print(f"\n(mode {ans.mode}; {len(ans.citations)} cited of {ans.considered} in scope)")
|
|
92
|
+
for c in ans.citations[: a.show]:
|
|
93
|
+
what = c["choice"] or c["text"][:80]
|
|
94
|
+
print(f" [{c['id']}] {c['kind']:<6} {c['topic'][:60]!r} -> {what!r} {c['ref']}")
|
|
95
|
+
return 0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cmd_export(a) -> int:
|
|
99
|
+
if not a.anonymized:
|
|
100
|
+
print("awcrowd: export is --anonymized only; a raw export would carry people's "
|
|
101
|
+
"ids out of their world", file=sys.stderr)
|
|
102
|
+
return 2
|
|
103
|
+
m = export(_load(a), a.out)
|
|
104
|
+
print(json.dumps(m, indent=1))
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def cmd_consent(a) -> int:
|
|
109
|
+
led = _ledger()
|
|
110
|
+
if a.verb == "list":
|
|
111
|
+
for e in led.entries():
|
|
112
|
+
print(json.dumps(e, sort_keys=True))
|
|
113
|
+
return 0
|
|
114
|
+
fn = led.grant if a.verb == "grant" else led.withdraw
|
|
115
|
+
print(json.dumps(fn(a.world, a.person or "", by=a.by or ""), sort_keys=True))
|
|
116
|
+
return 0
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def cmd_aggregate(a) -> int:
|
|
120
|
+
print(json.dumps(aggregate(_load(a), WorldPolicy(_ledger(), k=a.k)), indent=1))
|
|
121
|
+
return 0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cmd_decide(a) -> int:
|
|
125
|
+
d = decide(a.yes, a.no, a.eligible, a.abstain)
|
|
126
|
+
print(json.dumps(d, indent=1))
|
|
127
|
+
return 0 if d["passed"] else 1
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def self_test() -> int:
|
|
131
|
+
"""Prove the slice end to end on a throwaway store: read, consent, query, export,
|
|
132
|
+
aggregate, decide. Exit 0 only when every check held."""
|
|
133
|
+
import sqlite3
|
|
134
|
+
|
|
135
|
+
from .model import Response
|
|
136
|
+
|
|
137
|
+
fails: list[str] = []
|
|
138
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
139
|
+
db = sqlite3.connect(Path(tmp) / "guilds.db")
|
|
140
|
+
db.executescript("CREATE TABLE kv (guild TEXT, plugin TEXT, key TEXT, value TEXT);")
|
|
141
|
+
poll = {"id": "p1", "question": "Rename the product?", "choices": ["Keep", "Change"],
|
|
142
|
+
"votes": {"u1": 0, "u2": 0, "u3": 1}, "by": "u1", "at": 1_700_000_000}
|
|
143
|
+
sugg = {"id": "s1", "board": "suggest", "title": "Dark mode", "status": "New",
|
|
144
|
+
"author": "u9", "votes": {"u1": {"sign": 1, "w": 2.0, "at": 1_700_000_000}}}
|
|
145
|
+
db.executemany("INSERT INTO kv VALUES (?,?,?,?)", [
|
|
146
|
+
("g1", "community", "poll:p1", json.dumps(poll)),
|
|
147
|
+
("g1", "aitherium_feedback", "board:sugg:s1", json.dumps(sugg))])
|
|
148
|
+
db.commit()
|
|
149
|
+
db.close()
|
|
150
|
+
spec = f"discord:{Path(tmp) / 'guilds.db'}"
|
|
151
|
+
rs = sources.load_all([spec])
|
|
152
|
+
if len([r for r in rs if r.source == "discord.community_poll"]) != 3:
|
|
153
|
+
fails.append("community poll votes not read")
|
|
154
|
+
if not any(r.weight == 2.0 for r in rs if r.source == "feedback.board"):
|
|
155
|
+
fails.append("board weight not taken from the source")
|
|
156
|
+
led = ConsentLedger(Path(tmp) / "consent.jsonl")
|
|
157
|
+
led.withdraw("g1", "u3")
|
|
158
|
+
kept = led.filter(rs)
|
|
159
|
+
if any(r.respondent == "u3" for r in kept):
|
|
160
|
+
fails.append("withdrawal did not remove the person")
|
|
161
|
+
ans = query("rename the product", kept, use_llm=False)
|
|
162
|
+
if ans.tallies.get("poll:p1") != {"Keep": 2.0}:
|
|
163
|
+
fails.append(f"tally wrong: {ans.tallies}")
|
|
164
|
+
if not ans.citations or not all(c["ref"] for c in ans.citations):
|
|
165
|
+
fails.append("answer not cited")
|
|
166
|
+
m = export(kept, Path(tmp) / "out", salt=b"s")
|
|
167
|
+
blob = "".join((Path(tmp) / "out" / f"crowd-{s}.jsonl").read_text("utf-8")
|
|
168
|
+
for s in ("train", "val", "test"))
|
|
169
|
+
if m["rows"] != len(kept) or "u1" in blob or "g1" in blob:
|
|
170
|
+
fails.append("export leaked an id or lost rows")
|
|
171
|
+
many = [Response(kind="vote", source="t", world="g1", topic_id="x", topic="q",
|
|
172
|
+
respondent=f"m{i}", at=0, choice="a") for i in range(9)]
|
|
173
|
+
led.grant("g1")
|
|
174
|
+
if aggregate(many, WorldPolicy(led))["topics"]:
|
|
175
|
+
fails.append("a group under k was not suppressed")
|
|
176
|
+
if not decide(7.0, 2.0, 10.0)["passed"] or decide(6.0, 0.0, 10.0)["passed"]:
|
|
177
|
+
fails.append("decision rule wrong")
|
|
178
|
+
for f in fails:
|
|
179
|
+
print(f"FAIL {f}")
|
|
180
|
+
print("awcrowd self-test:", "OK" if not fails else f"{len(fails)} failure(s)")
|
|
181
|
+
return 0 if not fails else 1
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
185
|
+
p = argparse.ArgumentParser(prog="awcrowd", description=__doc__.split("\n")[0])
|
|
186
|
+
p.add_argument("--version", action="version", version=f"awcrowd {__version__}")
|
|
187
|
+
p.add_argument("--self-test", action="store_true", help="prove the slice works")
|
|
188
|
+
sub = p.add_subparsers(dest="cmd")
|
|
189
|
+
|
|
190
|
+
def src(sp):
|
|
191
|
+
sp.add_argument("--source", action="append", help="<kind>:<path> (repeatable)")
|
|
192
|
+
sp.add_argument("--visibility", action="append",
|
|
193
|
+
help="<world>=public|private|business (default public)")
|
|
194
|
+
return sp
|
|
195
|
+
|
|
196
|
+
src(sub.add_parser("sources", help="count what each source holds")).set_defaults(
|
|
197
|
+
fn=cmd_sources)
|
|
198
|
+
q = src(sub.add_parser("query", help="ask the responses a question"))
|
|
199
|
+
q.add_argument("question")
|
|
200
|
+
q.add_argument("--scope", action="append", help="guild=<id> | role=<id> | since=7d")
|
|
201
|
+
q.add_argument("--role", default="")
|
|
202
|
+
q.add_argument("--since", default="")
|
|
203
|
+
q.add_argument("--no-llm", action="store_true", help="tally only, no model call")
|
|
204
|
+
q.add_argument("--json", action="store_true")
|
|
205
|
+
q.add_argument("--show", type=int, default=12, help="citations to print")
|
|
206
|
+
q.set_defaults(fn=cmd_query)
|
|
207
|
+
e = src(sub.add_parser("export", help="anonymised labelled corpus"))
|
|
208
|
+
e.add_argument("--anonymized", "--anonymised", action="store_true")
|
|
209
|
+
e.add_argument("--out", required=True)
|
|
210
|
+
e.set_defaults(fn=cmd_export)
|
|
211
|
+
c = sub.add_parser("consent", help="grant or withdraw, per world or per person")
|
|
212
|
+
c.add_argument("verb", choices=("grant", "withdraw", "list"))
|
|
213
|
+
c.add_argument("--world", default="")
|
|
214
|
+
c.add_argument("--person", default="")
|
|
215
|
+
c.add_argument("--by", default="")
|
|
216
|
+
c.set_defaults(fn=cmd_consent)
|
|
217
|
+
g = src(sub.add_parser("aggregate", help="the cross-world aggregate (k-suppressed)"))
|
|
218
|
+
g.add_argument("--k", type=int, default=10)
|
|
219
|
+
g.set_defaults(fn=cmd_aggregate)
|
|
220
|
+
d = sub.add_parser("decide", help="70%% turnout + 65%% yes")
|
|
221
|
+
for name in ("yes", "no", "eligible", "abstain"):
|
|
222
|
+
d.add_argument(f"--{name}", type=float, default=0.0)
|
|
223
|
+
d.set_defaults(fn=cmd_decide)
|
|
224
|
+
return p
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def main(argv: list[str] | None = None) -> int:
|
|
228
|
+
a = build_parser().parse_args(argv)
|
|
229
|
+
if a.self_test:
|
|
230
|
+
return self_test()
|
|
231
|
+
if not getattr(a, "fn", None):
|
|
232
|
+
build_parser().print_help()
|
|
233
|
+
return 2
|
|
234
|
+
if a.cmd == "consent" and a.verb != "list" and not a.world:
|
|
235
|
+
print("awcrowd: consent needs --world", file=sys.stderr)
|
|
236
|
+
return 2
|
|
237
|
+
return int(a.fn(a))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
if __name__ == "__main__":
|
|
241
|
+
raise SystemExit(main())
|
awcrowd/consent.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Consent and withdrawal, per person and per world.
|
|
2
|
+
|
|
3
|
+
An append-only JSONL ledger. The LATEST entry for a key wins, so a withdrawal is one
|
|
4
|
+
line and a renewed consent is another; nothing is ever edited in place, which keeps
|
|
5
|
+
the history auditable.
|
|
6
|
+
|
|
7
|
+
Two levels:
|
|
8
|
+
|
|
9
|
+
* ``person`` -- one member in one world. ``withdraw`` removes every response that
|
|
10
|
+
person gave in that world from query, aggregate and export, retroactively.
|
|
11
|
+
* ``world`` -- a world's admins. ``opt_in`` allows that world's AGGREGATES to be
|
|
12
|
+
federated; ``withdraw`` takes the world out again (and is retroactive the same way:
|
|
13
|
+
the next aggregate simply no longer contains it). A world that never opted in is
|
|
14
|
+
OUT -- the default is no.
|
|
15
|
+
|
|
16
|
+
The default for a PERSON inside their own world follows the source: a member who voted
|
|
17
|
+
in a poll in that world consented to that world seeing the vote. Leaving that default
|
|
18
|
+
is what ``withdraw`` is for, and ``policy=opt_in`` makes the default no for a world
|
|
19
|
+
that wants it stricter.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import time
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Iterable, Iterator
|
|
28
|
+
|
|
29
|
+
from .model import Response
|
|
30
|
+
|
|
31
|
+
GRANT, WITHDRAW = "grant", "withdraw"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ConsentLedger:
|
|
35
|
+
def __init__(self, path: str | os.PathLike, policy: str = "source_default"):
|
|
36
|
+
if policy not in ("source_default", "opt_in"):
|
|
37
|
+
raise ValueError("policy must be source_default or opt_in")
|
|
38
|
+
self.path = Path(path)
|
|
39
|
+
self.policy = policy
|
|
40
|
+
|
|
41
|
+
# -- writing ---------------------------------------------------------------
|
|
42
|
+
def _append(self, entry: dict) -> dict:
|
|
43
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
entry = {**entry, "at": entry.get("at") or time.time()}
|
|
45
|
+
with open(self.path, "a", encoding="utf-8", newline="\n") as f:
|
|
46
|
+
f.write(json.dumps(entry, sort_keys=True) + "\n")
|
|
47
|
+
return entry
|
|
48
|
+
|
|
49
|
+
def grant(self, world: str, person: str = "", by: str = "", scope: str = "crowd") -> dict:
|
|
50
|
+
return self._append({"level": "person" if person else "world", "world": str(world),
|
|
51
|
+
"person": str(person), "verb": GRANT, "scope": scope, "by": by})
|
|
52
|
+
|
|
53
|
+
def withdraw(self, world: str, person: str = "", by: str = "",
|
|
54
|
+
scope: str = "crowd") -> dict:
|
|
55
|
+
return self._append({"level": "person" if person else "world", "world": str(world),
|
|
56
|
+
"person": str(person), "verb": WITHDRAW, "scope": scope,
|
|
57
|
+
"by": by})
|
|
58
|
+
|
|
59
|
+
# -- reading ---------------------------------------------------------------
|
|
60
|
+
def entries(self) -> Iterator[dict]:
|
|
61
|
+
if not self.path.is_file():
|
|
62
|
+
return
|
|
63
|
+
with open(self.path, encoding="utf-8") as f:
|
|
64
|
+
for line in f:
|
|
65
|
+
line = line.strip()
|
|
66
|
+
if not line:
|
|
67
|
+
continue
|
|
68
|
+
try:
|
|
69
|
+
yield json.loads(line)
|
|
70
|
+
except json.JSONDecodeError:
|
|
71
|
+
continue # a torn last line; the rest of the ledger stands
|
|
72
|
+
|
|
73
|
+
def _latest(self) -> dict[tuple[str, str, str], str]:
|
|
74
|
+
state: dict[tuple[str, str, str], str] = {}
|
|
75
|
+
for e in self.entries():
|
|
76
|
+
state[(e.get("level", ""), str(e.get("world", "")), str(e.get("person", "")))] = \
|
|
77
|
+
e.get("verb", "")
|
|
78
|
+
return state
|
|
79
|
+
|
|
80
|
+
def person_allowed(self, world: str, person: str,
|
|
81
|
+
state: dict | None = None) -> bool:
|
|
82
|
+
state = self._latest() if state is None else state
|
|
83
|
+
verb = state.get(("person", str(world), str(person)))
|
|
84
|
+
if verb == WITHDRAW:
|
|
85
|
+
return False
|
|
86
|
+
if verb == GRANT:
|
|
87
|
+
return True
|
|
88
|
+
return self.policy == "source_default"
|
|
89
|
+
|
|
90
|
+
def world_federates(self, world: str, state: dict | None = None) -> bool:
|
|
91
|
+
"""True only for a world whose admins opted in and have not withdrawn."""
|
|
92
|
+
state = self._latest() if state is None else state
|
|
93
|
+
return state.get(("world", str(world), "")) == GRANT
|
|
94
|
+
|
|
95
|
+
def filter(self, responses: Iterable[Response]) -> list[Response]:
|
|
96
|
+
"""The responses a query or export may use: withdrawn people are gone."""
|
|
97
|
+
state = self._latest()
|
|
98
|
+
return [r for r in responses if self.person_allowed(r.world, r.respondent, state)]
|
|
99
|
+
|
|
100
|
+
def withdrawn_people(self) -> set[tuple[str, str]]:
|
|
101
|
+
return {(w, p) for (lvl, w, p), v in self._latest().items()
|
|
102
|
+
if lvl == "person" and v == WITHDRAW}
|
awcrowd/export.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""``awcrowd export --anonymized``: a labelled corpus another tool can train or score on.
|
|
2
|
+
|
|
3
|
+
Layout (the awdata convention: identifiers plus our own labels, a manifest with label
|
|
4
|
+
prevalences, and a deterministic held-out split):
|
|
5
|
+
|
|
6
|
+
<out>/crowd-train.jsonl crowd-val.jsonl crowd-test.jsonl
|
|
7
|
+
<out>/manifest.json {schema, counts, label_prevalence, sources, salted, built_at}
|
|
8
|
+
|
|
9
|
+
Anonymised means, per row:
|
|
10
|
+
|
|
11
|
+
* the respondent becomes ``p-<hmac>`` under a salt that is NOT written anywhere in the
|
|
12
|
+
output, so the same person links across rows but not back to an account;
|
|
13
|
+
* Discord mentions, user ids (17-20 digit snowflakes), emails and URLs in text are
|
|
14
|
+
replaced with placeholders;
|
|
15
|
+
* the world id becomes ``w-<hmac>`` too; roles are dropped;
|
|
16
|
+
* withdrawn people are absent (the caller passes responses through the consent
|
|
17
|
+
ledger first -- ``cli.py`` always does), and aggregate rows carry no person at all;
|
|
18
|
+
* anonymous board posts are exported like every other row: no author.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import hmac
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import secrets
|
|
28
|
+
import time
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from .model import Response
|
|
32
|
+
|
|
33
|
+
SCHEMA = "aither.crowd.dataset.v1"
|
|
34
|
+
SPLITS = (("train", 80), ("val", 10), ("test", 10))
|
|
35
|
+
_MENTION = re.compile(r"<[@#][!&]?\d+>")
|
|
36
|
+
_SNOWFLAKE = re.compile(r"\b\d{17,20}\b")
|
|
37
|
+
_EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
|
|
38
|
+
_URL = re.compile(r"https?://\S+")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def scrub(text: str) -> str:
|
|
42
|
+
text = _MENTION.sub("<mention>", text or "")
|
|
43
|
+
text = _EMAIL.sub("<email>", text)
|
|
44
|
+
text = _URL.sub("<url>", text)
|
|
45
|
+
return _SNOWFLAKE.sub("<id>", text)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _pseudo(salt: bytes, prefix: str, value: str) -> str:
|
|
49
|
+
return prefix + hmac.new(salt, value.encode(), hashlib.sha256).hexdigest()[:12]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def split_of(key: str) -> str:
|
|
53
|
+
b = int(hashlib.sha256(key.encode()).hexdigest()[:8], 16) % 100
|
|
54
|
+
acc = 0
|
|
55
|
+
for name, pct in SPLITS:
|
|
56
|
+
acc += pct
|
|
57
|
+
if b < acc:
|
|
58
|
+
return name
|
|
59
|
+
return SPLITS[-1][0]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def row(r: Response, salt: bytes) -> dict:
|
|
63
|
+
label = r.choice or r.kind
|
|
64
|
+
return {
|
|
65
|
+
"id": _pseudo(salt, "x-", r.id), "kind": r.kind, "source": r.source,
|
|
66
|
+
"world": _pseudo(salt, "w-", r.world),
|
|
67
|
+
"topic_id": _pseudo(salt, "t-", f"{r.world}/{r.topic_id}"),
|
|
68
|
+
"topic": scrub(r.topic), "text": scrub(r.text), "reason": scrub(r.reason),
|
|
69
|
+
"label": label, "value": r.value,
|
|
70
|
+
"respondent": None if r.meta.get("aggregate") else _pseudo(salt, "p-", r.respondent),
|
|
71
|
+
"aggregate": bool(r.meta.get("aggregate")),
|
|
72
|
+
"weight": r.weight, "day": time.strftime("%Y-%m-%d", time.gmtime(r.at or 0)),
|
|
73
|
+
# the split is by TOPIC, so one poll never sits on both sides of the eval
|
|
74
|
+
"split": split_of(f"{r.world}/{r.topic_id}"),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def export(responses: list[Response], out_dir: str | os.PathLike,
|
|
79
|
+
salt: bytes | None = None) -> dict:
|
|
80
|
+
"""Write the corpus; private and business worlds are refused, not exported."""
|
|
81
|
+
salt = salt or secrets.token_bytes(32)
|
|
82
|
+
out = Path(out_dir)
|
|
83
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
rows = [row(r, salt) for r in responses if r.visibility == "public"]
|
|
85
|
+
refused = sum(1 for r in responses if r.visibility != "public")
|
|
86
|
+
counts: dict[str, int] = {}
|
|
87
|
+
labels: dict[str, int] = {}
|
|
88
|
+
for name, _ in SPLITS:
|
|
89
|
+
part = [x for x in rows if x["split"] == name]
|
|
90
|
+
counts[name] = len(part)
|
|
91
|
+
tmp = out / f"crowd-{name}.jsonl.tmp"
|
|
92
|
+
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
|
|
93
|
+
for x in part:
|
|
94
|
+
f.write(json.dumps(x, sort_keys=True) + "\n")
|
|
95
|
+
os.replace(tmp, out / f"crowd-{name}.jsonl")
|
|
96
|
+
for x in rows:
|
|
97
|
+
labels[x["label"]] = labels.get(x["label"], 0) + 1
|
|
98
|
+
n = max(1, len(rows))
|
|
99
|
+
manifest = {"schema": SCHEMA, "counts": counts, "rows": len(rows),
|
|
100
|
+
"refused_non_public": refused,
|
|
101
|
+
"label_prevalence": {k: round(v / n, 4) for k, v in sorted(labels.items())},
|
|
102
|
+
"sources": sorted({x["source"] for x in rows}), "salted": True,
|
|
103
|
+
"built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
|
|
104
|
+
(out / "manifest.json").write_text(json.dumps(manifest, indent=1, sort_keys=True),
|
|
105
|
+
encoding="utf-8")
|
|
106
|
+
return manifest
|
awcrowd/federation.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""The federation CONTRACT: what one world may tell another. Phase 1 = the contract
|
|
2
|
+
and its tests; the live transport (Flux in, Strata at rest, the gateway out) is
|
|
3
|
+
phase 2 -- see the plan doc.
|
|
4
|
+
|
|
5
|
+
Three pieces:
|
|
6
|
+
|
|
7
|
+
1. ``event(r)`` -- the ``aither.crowd.event.v1`` envelope a world emits for one
|
|
8
|
+
response onto its OWN live stream. It still names the person (pseudonymously,
|
|
9
|
+
per world) because it never leaves that world.
|
|
10
|
+
2. ``WorldPolicy`` -- a world's admins opted in (consent ledger, world level), its
|
|
11
|
+
visibility is public, and the minimum group size ``k``.
|
|
12
|
+
3. ``aggregate(responses, ...)`` -- the ONLY shape that crosses a world boundary:
|
|
13
|
+
counts, weighted shares, sentiment and themes per topic, with any group smaller
|
|
14
|
+
than ``k`` distinct people SUPPRESSED. No text, no ids, no people. A private or
|
|
15
|
+
business world contributes nothing, ever, whatever its consent says.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
from .consent import ConsentLedger
|
|
24
|
+
from .model import Response
|
|
25
|
+
from .weighting import effective_weight
|
|
26
|
+
|
|
27
|
+
EVENT_SCHEMA = "aither.crowd.event.v1"
|
|
28
|
+
AGGREGATE_SCHEMA = "aither.crowd.aggregate.v1"
|
|
29
|
+
K_MIN = 10
|
|
30
|
+
|
|
31
|
+
_POS = frozenset("yes love great good like keep agree helpful works useful +1 up "
|
|
32
|
+
"thanks awesome nice".split())
|
|
33
|
+
_NEG = frozenset("no hate bad broken dislike change disagree useless confusing slow "
|
|
34
|
+
"worse bug down -1 annoying".split())
|
|
35
|
+
_WORD = re.compile(r"[a-z0-9'+-]+")
|
|
36
|
+
_THEME_STOP = frozenset(
|
|
37
|
+
"the a an and or of to in is it for on that this with be are was we i you my our "
|
|
38
|
+
"they them but not so as at by from have has had do does can will would should".split())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def event(r: Response, world_salt: bytes) -> dict:
|
|
42
|
+
"""The live event for one response. ``world_salt`` is the world's own secret
|
|
43
|
+
(Lockbox / workspace secrets in phase 2); the person id is HMAC'd under it."""
|
|
44
|
+
who = hashlib.sha256(world_salt + r.respondent.encode()).hexdigest()[:16]
|
|
45
|
+
return {"schema": EVENT_SCHEMA, "world": r.world, "visibility": r.visibility,
|
|
46
|
+
"kind": r.kind, "source": r.source, "topic_id": r.topic_id, "topic": r.topic,
|
|
47
|
+
"choice": r.choice, "value": r.value, "weight": r.weight, "at": r.at,
|
|
48
|
+
"person": None if r.meta.get("aggregate") else who, "response_id": r.id}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class WorldPolicy:
|
|
53
|
+
ledger: ConsentLedger
|
|
54
|
+
k: int = K_MIN
|
|
55
|
+
|
|
56
|
+
def federates(self, world: str, visibility: str) -> bool:
|
|
57
|
+
return visibility == "public" and self.ledger.world_federates(world)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def sentiment(r: Response) -> float | None:
|
|
61
|
+
"""-1..1 from the response itself: an up/down vote, a good/bad rating, or the
|
|
62
|
+
words of a reason. ``None`` when it says nothing either way."""
|
|
63
|
+
if r.value is not None and r.kind == "vote":
|
|
64
|
+
return max(-1.0, min(1.0, float(r.value)))
|
|
65
|
+
if r.kind == "rating" and r.choice:
|
|
66
|
+
c = r.choice.lower()
|
|
67
|
+
if c in ("good", "up", "helpful", "+"):
|
|
68
|
+
return 1.0
|
|
69
|
+
if c in ("bad", "down", "wrong", "-"):
|
|
70
|
+
return -1.0
|
|
71
|
+
words = set(_WORD.findall(f"{r.text} {r.reason}".lower()))
|
|
72
|
+
pos, neg = len(words & _POS), len(words & _NEG)
|
|
73
|
+
return None if pos == neg else (1.0 if pos > neg else -1.0)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def themes(texts: list[str], top: int = 5, min_count: int = K_MIN) -> list[str]:
|
|
77
|
+
counts: dict[str, int] = {}
|
|
78
|
+
for t in texts:
|
|
79
|
+
for w in set(_WORD.findall(t.lower())):
|
|
80
|
+
if len(w) > 3 and w not in _THEME_STOP and not w.isdigit():
|
|
81
|
+
counts[w] = counts.get(w, 0) + 1
|
|
82
|
+
# a theme must come from at least k responses, so a rare word (a name, a handle)
|
|
83
|
+
# said by a few people never crosses the boundary inside an otherwise-large group
|
|
84
|
+
return [w for w, n in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
|
|
85
|
+
if n >= min_count][:top]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def aggregate(responses: list[Response], policy: WorldPolicy, topic_key=None) -> dict:
|
|
89
|
+
"""The cross-world answer. ``topic_key(r)`` groups responses (default: the topic
|
|
90
|
+
text, case-folded, so the same question asked in two worlds pools)."""
|
|
91
|
+
key = topic_key or (lambda r: r.topic.strip().lower())
|
|
92
|
+
allowed_people = policy.ledger.filter(responses)
|
|
93
|
+
worlds_in = sorted({r.world for r in allowed_people
|
|
94
|
+
if policy.federates(r.world, r.visibility)})
|
|
95
|
+
pool = [r for r in allowed_people if r.world in worlds_in]
|
|
96
|
+
groups: dict[str, list[Response]] = {}
|
|
97
|
+
for r in pool:
|
|
98
|
+
groups.setdefault(key(r), []).append(r)
|
|
99
|
+
topics, suppressed = [], 0
|
|
100
|
+
for name, rs in sorted(groups.items()):
|
|
101
|
+
people = {(r.world, r.respondent) for r in rs if not r.meta.get("aggregate")}
|
|
102
|
+
agg_n = sum(int(r.weight or 0) for r in rs if r.meta.get("aggregate"))
|
|
103
|
+
n_people = len(people) + agg_n
|
|
104
|
+
if n_people < policy.k:
|
|
105
|
+
suppressed += 1
|
|
106
|
+
continue
|
|
107
|
+
shares: dict[str, float] = {}
|
|
108
|
+
for r in rs:
|
|
109
|
+
if r.choice:
|
|
110
|
+
shares[r.choice] = shares.get(r.choice, 0.0) + effective_weight(r)
|
|
111
|
+
total = sum(shares.values()) or 1.0
|
|
112
|
+
sents = [s for s in (sentiment(r) for r in rs) if s is not None]
|
|
113
|
+
topics.append({
|
|
114
|
+
"topic": name[:160], "people": n_people,
|
|
115
|
+
"worlds": len({r.world for r in rs}),
|
|
116
|
+
"shares": {c: round(w / total, 4) for c, w in
|
|
117
|
+
sorted(shares.items(), key=lambda kv: -kv[1])},
|
|
118
|
+
"sentiment": round(sum(sents) / len(sents), 4) if sents else None,
|
|
119
|
+
"themes": themes([f"{r.text} {r.reason}" for r in rs], min_count=policy.k),
|
|
120
|
+
})
|
|
121
|
+
return {"schema": AGGREGATE_SCHEMA, "k": policy.k, "worlds": len(worlds_in),
|
|
122
|
+
"topics": topics, "suppressed_groups": suppressed}
|
awcrowd/model.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""One response model for everything a crowd says.
|
|
2
|
+
|
|
3
|
+
A poll vote, a survey/form answer, a feedback post and a rating-with-reason are the
|
|
4
|
+
same thing seen from four surfaces: SOMEONE, in SOME WORLD, said SOMETHING about
|
|
5
|
+
SOME TOPIC, at SOME TIME, and here is where to look it up. ``Response`` is that
|
|
6
|
+
shape and nothing more. It carries no counter: a tally is always recomputed from
|
|
7
|
+
the responses, so there is never a second number that can drift from the source.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import asdict, dataclass, field
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
SCHEMA = "aither.crowd.response.v1"
|
|
18
|
+
KINDS = ("vote", "answer", "post", "rating")
|
|
19
|
+
#: what a world is: public communities may federate aggregates; private and
|
|
20
|
+
#: business worlds never leave their own world (owner rule: hard isolation).
|
|
21
|
+
VISIBILITIES = ("public", "private", "business")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Response:
|
|
26
|
+
kind: str # vote | answer | post | rating
|
|
27
|
+
source: str # adapter name: discord.community_poll, feedback.board, ...
|
|
28
|
+
world: str # guild id / workspace id: the isolation boundary
|
|
29
|
+
topic_id: str # poll id, form id, board item id, turn id
|
|
30
|
+
topic: str # the question / title the response is about
|
|
31
|
+
respondent: str # the person, as the SOURCE names them (never exported raw)
|
|
32
|
+
at: float # unix seconds
|
|
33
|
+
choice: str = "" # the option picked (vote), or the rating label
|
|
34
|
+
value: float | None = None # +1/-1 for an up/down vote, a numeric rating, ...
|
|
35
|
+
text: str = "" # the free text: an answer, a post body, a reason
|
|
36
|
+
reason: str = "" # why, when the surface asks for one
|
|
37
|
+
weight: float | None = None # the weight the SOURCE fixed at cast time; None = unweighted
|
|
38
|
+
roles: list[str] = field(default_factory=list)
|
|
39
|
+
ref: str = "" # where to look it up (store key, URL): the citation
|
|
40
|
+
visibility: str = "public"
|
|
41
|
+
meta: dict[str, Any] = field(default_factory=dict)
|
|
42
|
+
id: str = ""
|
|
43
|
+
|
|
44
|
+
def __post_init__(self) -> None:
|
|
45
|
+
if self.kind not in KINDS:
|
|
46
|
+
raise ValueError(f"kind must be one of {KINDS}, got {self.kind!r}")
|
|
47
|
+
if self.visibility not in VISIBILITIES:
|
|
48
|
+
raise ValueError(f"visibility must be one of {VISIBILITIES}")
|
|
49
|
+
if not self.id:
|
|
50
|
+
self.id = response_id(self.source, self.world, self.topic_id, self.respondent,
|
|
51
|
+
self.kind)
|
|
52
|
+
|
|
53
|
+
def to_dict(self) -> dict[str, Any]:
|
|
54
|
+
d = asdict(self)
|
|
55
|
+
d["schema"] = SCHEMA
|
|
56
|
+
return d
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_dict(cls, d: dict[str, Any]) -> Response:
|
|
60
|
+
keep = {k: v for k, v in d.items() if k in cls.__dataclass_fields__}
|
|
61
|
+
return cls(**keep)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def response_id(source: str, world: str, topic_id: str, respondent: str, kind: str) -> str:
|
|
65
|
+
"""Stable id: one person's response to one topic on one source. A changed vote
|
|
66
|
+
replaces the earlier one (latest wins), exactly as every source already does."""
|
|
67
|
+
raw = json.dumps([source, world, topic_id, respondent, kind])
|
|
68
|
+
return "r-" + hashlib.sha256(raw.encode()).hexdigest()[:12]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def now() -> float:
|
|
72
|
+
return time.time()
|