vakforge 0.0.1__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.
vakforge/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """vakforge: turn the data your company already has into a self-hosted voice assistant."""
2
+
3
+ __version__ = "0.0.1"
vakforge/cli.py ADDED
@@ -0,0 +1,124 @@
1
+ """vakforge CLI. Thin: each subcommand delegates to a module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Annotated
8
+
9
+ import typer
10
+ from rich.console import Console
11
+
12
+ from vakforge import __version__
13
+
14
+ app = typer.Typer(
15
+ help="Turn the data your company already has into a self-hosted voice assistant.",
16
+ no_args_is_help=True,
17
+ rich_markup_mode="rich",
18
+ )
19
+ console = Console()
20
+ err_console = Console(stderr=True)
21
+
22
+ PROJECT_GITIGNORE = """# written by `vakforge init`
23
+ data/raw/
24
+ runs/
25
+ .venv/
26
+ *.wav
27
+ *.mp3
28
+ *.flac
29
+ *.safetensors
30
+ *.bin
31
+ *.pt
32
+ *.gguf
33
+ """
34
+
35
+
36
+ def _version(value: bool) -> None:
37
+ if value:
38
+ console.print(f"vakforge {__version__}")
39
+ raise typer.Exit()
40
+
41
+
42
+ @app.callback()
43
+ def main(
44
+ version: Annotated[
45
+ bool, typer.Option("--version", callback=_version, is_eager=True, help="Show version.")
46
+ ] = False,
47
+ ) -> None:
48
+ """vakforge."""
49
+
50
+
51
+ @app.command()
52
+ def init(
53
+ name: Annotated[str, typer.Argument(help="Project directory to create.")],
54
+ locale: Annotated[
55
+ list[str], typer.Option("--locale", "-l", help="Locale pack id(s), e.g. en-US.")
56
+ ],
57
+ ) -> None:
58
+ """Scaffold a project folder with a locale."""
59
+ from vakforge.config import ProjectConfig
60
+ from vakforge.locales import get_pack, list_packs
61
+
62
+ for pack_id in locale:
63
+ try:
64
+ get_pack(pack_id)
65
+ except KeyError:
66
+ err_console.print(f"[red]unknown locale {pack_id!r}[/]; known: {list_packs()}")
67
+ raise typer.Exit(2) from None
68
+
69
+ project = Path(name)
70
+ if project.exists() and any(project.iterdir()):
71
+ err_console.print(f"[red]{project} exists and is not empty[/]")
72
+ raise typer.Exit(2)
73
+ for sub in ("data/raw", "data/audio", "configs", "runs"):
74
+ (project / sub).mkdir(parents=True, exist_ok=True)
75
+ (project / ".gitignore").write_text(PROJECT_GITIGNORE, encoding="utf-8")
76
+ cfg_path = ProjectConfig(name=project.name, locales=locale).save(project)
77
+ console.print(f"[green]created[/] {project}/ ({cfg_path.name}: locales={locale})")
78
+ console.print(
79
+ "next: drop your documents, tables, chats or audio into data/raw/ and run "
80
+ f"`vakforge inspect {project}/data/raw`"
81
+ )
82
+
83
+
84
+ @app.command()
85
+ def validate(
86
+ manifest: Annotated[Path, typer.Argument(exists=True, dir_okay=False, readable=True)],
87
+ allow_unconsented: Annotated[
88
+ bool, typer.Option(help="Accept rows with meta.consent='none' (never exported).")
89
+ ] = False,
90
+ ) -> None:
91
+ """Validate a canonical `vakforge.jsonl` manifest."""
92
+ from vakforge.validate import validate_manifest
93
+
94
+ convs, issues = validate_manifest(manifest, allow_unconsented=allow_unconsented)
95
+ if allow_unconsented and any(c.meta.consent == "none" for c in convs):
96
+ err_console.print(
97
+ "[yellow]warning:[/] unconsented rows accepted; they will never be exported"
98
+ )
99
+ for issue in issues:
100
+ err_console.print(f"[red]✗[/] {issue}")
101
+ n_ok = len(convs) - len({i.conv_id for i in issues})
102
+ console.print(f"{len(convs)} conversation(s) parsed, {n_ok} clean, {len(issues)} issue(s)")
103
+ raise typer.Exit(1 if issues else 0)
104
+
105
+
106
+ @app.command()
107
+ def schema(
108
+ out: Annotated[
109
+ Path | None, typer.Option("--out", "-o", help="Write JSON Schema here instead of stdout.")
110
+ ] = None,
111
+ ) -> None:
112
+ """Export the canonical JSON Schema."""
113
+ from vakforge.schema import json_schema
114
+
115
+ text = json.dumps(json_schema(), indent=2)
116
+ if out:
117
+ out.write_text(text + "\n", encoding="utf-8")
118
+ console.print(f"[green]wrote[/] {out}")
119
+ else:
120
+ print(text)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ app()
vakforge/config.py ADDED
@@ -0,0 +1,28 @@
1
+ """Project config (`vakforge.yaml`), written by `init` and read by every stage."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import yaml
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+ CONFIG_NAME = "vakforge.yaml"
11
+
12
+
13
+ class ProjectConfig(BaseModel):
14
+ model_config = ConfigDict(extra="forbid")
15
+
16
+ name: str
17
+ locales: list[str] = Field(min_length=1)
18
+ data_dir: str = "data"
19
+
20
+ @classmethod
21
+ def load(cls, project_dir: Path) -> ProjectConfig:
22
+ text = (project_dir / CONFIG_NAME).read_text(encoding="utf-8")
23
+ return cls.model_validate(yaml.safe_load(text) or {})
24
+
25
+ def save(self, project_dir: Path) -> Path:
26
+ path = project_dir / CONFIG_NAME
27
+ path.write_text(yaml.safe_dump(self.model_dump(), sort_keys=False), encoding="utf-8")
28
+ return path
@@ -0,0 +1,6 @@
1
+ """Locale pack registry. Importing this package registers every shipped pack."""
2
+
3
+ from vakforge.locales import en # noqa: F401 (registers packs on import)
4
+ from vakforge.locales.base import LocalePack, get_pack, list_packs, register
5
+
6
+ __all__ = ["LocalePack", "get_pack", "list_packs", "register"]
@@ -0,0 +1,56 @@
1
+ """LocalePack base and registry. Everything language- or market-specific lives in a pack.
2
+
3
+ Phase 0 ships the skeleton: identity, language tags, inheritance, and the two text hooks
4
+ core needs for validation and WER. Formats, PII patterns, generators and recipe support
5
+ land in Phase 1 (docs/LOCALE_PACKS.md).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import ClassVar
12
+
13
+ _PUNCT = re.compile(r"[^\w\s]", re.UNICODE)
14
+
15
+
16
+ class LocalePack:
17
+ """Subclass and set the class attributes. Register with `register()`."""
18
+
19
+ id: ClassVar[str]
20
+ languages: ClassVar[list[str]]
21
+ parent: ClassVar[str | None] = None
22
+
23
+ def all_languages(self) -> set[str]:
24
+ """Tags this pack accepts on a turn, including inherited ones."""
25
+ langs = set(self.languages)
26
+ if self.parent:
27
+ langs |= get_pack(self.parent).all_languages()
28
+ return langs
29
+
30
+ def detect_lang(self, text: str) -> str:
31
+ """Per-turn language tag. Default: the pack's first language."""
32
+ return self.languages[0]
33
+
34
+ def normalize_text(self, text: str) -> str:
35
+ """Text normalization for WER. Default: lowercase, strip punctuation, collapse spaces."""
36
+ return " ".join(_PUNCT.sub(" ", text.lower()).split())
37
+
38
+
39
+ _REGISTRY: dict[str, LocalePack] = {}
40
+
41
+
42
+ def register(cls: type[LocalePack]) -> type[LocalePack]:
43
+ """Class decorator: instantiate and register a pack by id."""
44
+ _REGISTRY[cls.id] = cls()
45
+ return cls
46
+
47
+
48
+ def get_pack(pack_id: str) -> LocalePack:
49
+ try:
50
+ return _REGISTRY[pack_id]
51
+ except KeyError:
52
+ raise KeyError(f"unknown locale pack {pack_id!r}; known: {sorted(_REGISTRY)}") from None
53
+
54
+
55
+ def list_packs() -> list[str]:
56
+ return sorted(_REGISTRY)
vakforge/locales/en.py ADDED
@@ -0,0 +1,36 @@
1
+ """English packs: `en` parent plus en-US, en-GB, en-IN.
2
+
3
+ Phase 0 skeletons. Formats, PII patterns, consent notes and generators come in Phase 1;
4
+ split each into its own package when it grows past a screen.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from vakforge.locales.base import LocalePack, register
10
+
11
+
12
+ @register
13
+ class En(LocalePack):
14
+ id = "en"
15
+ languages = ["en"]
16
+
17
+
18
+ @register
19
+ class EnUS(LocalePack):
20
+ id = "en-US"
21
+ languages = ["en-US"]
22
+ parent = "en"
23
+
24
+
25
+ @register
26
+ class EnGB(LocalePack):
27
+ id = "en-GB"
28
+ languages = ["en-GB"]
29
+ parent = "en"
30
+
31
+
32
+ @register
33
+ class EnIN(LocalePack):
34
+ id = "en-IN"
35
+ languages = ["en-IN"]
36
+ parent = "en"
vakforge/schema.py ADDED
@@ -0,0 +1,189 @@
1
+ """Canonical dataset schema (`vakforge.jsonl`). Source of truth for docs/DATA_FORMAT.md.
2
+
3
+ Structural rules that need only the record itself live here as pydantic validators.
4
+ Rules that need the filesystem or the locale registry live in `vakforge.validate`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime
10
+ from typing import Any, Literal
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
13
+
14
+ SCHEMA_VERSION = "0.1"
15
+
16
+ Speaker = Literal["user", "agent", "tool"]
17
+ Condition = Literal["studio", "clean", "phone", "noisy"]
18
+ Source = Literal["real", "synthetic", "public"]
19
+ Consent = Literal["recorded_verbal", "written", "synthetic", "public_license", "none"]
20
+ Split = Literal["train", "val", "test"]
21
+
22
+
23
+ class _Strict(BaseModel):
24
+ model_config = ConfigDict(extra="forbid")
25
+
26
+
27
+ class Audio(_Strict):
28
+ path: str
29
+ sample_rate: int = 24000
30
+ channels: int = Field(ge=1, le=2)
31
+ channel_map: dict[str, Speaker] | None = None
32
+ duration_s: float = Field(ge=0)
33
+ condition: Condition = "clean"
34
+
35
+ @model_validator(mode="after")
36
+ def _channel_map_matches(self) -> Audio:
37
+ if self.channels == 2 and self.channel_map is None:
38
+ raise ValueError("stereo audio needs channel_map, e.g. {'0': 'user', '1': 'agent'}")
39
+ if self.channel_map is not None and set(self.channel_map) != {
40
+ str(i) for i in range(self.channels)
41
+ }:
42
+ raise ValueError(f"channel_map keys must be {[str(i) for i in range(self.channels)]}")
43
+ return self
44
+
45
+
46
+ class Language(_Strict):
47
+ primary: str
48
+ mix: list[str] = Field(default_factory=list)
49
+
50
+
51
+ class Tool(_Strict):
52
+ name: str
53
+ description: str = ""
54
+ parameters: dict[str, Any] = Field(default_factory=lambda: {"type": "object"})
55
+
56
+
57
+ class ToolCall(_Strict):
58
+ id: str
59
+ name: str
60
+ arguments: dict[str, Any] = Field(default_factory=dict)
61
+
62
+
63
+ class ToolResult(_Strict):
64
+ id: str
65
+ content: dict[str, Any] = Field(default_factory=dict)
66
+
67
+
68
+ class Entity(_Strict):
69
+ type: str
70
+ text: str
71
+ start_char: int | None = None
72
+ end_char: int | None = None
73
+ normalized: Any = None
74
+
75
+
76
+ class Turn(_Strict):
77
+ speaker: Speaker
78
+ start: float = Field(ge=0)
79
+ end: float = Field(ge=0)
80
+ text: str | None = None
81
+ lang: str | None = None
82
+ entities: list[Entity] = Field(default_factory=list)
83
+ overlap: bool = False
84
+ tool_call: ToolCall | None = None
85
+ tool_result: ToolResult | None = None
86
+
87
+ @property
88
+ def spoken(self) -> bool:
89
+ return self.tool_call is None and self.tool_result is None
90
+
91
+ @model_validator(mode="after")
92
+ def _shape(self) -> Turn:
93
+ if self.end < self.start:
94
+ raise ValueError(f"end ({self.end}) < start ({self.start})")
95
+ if self.tool_call and self.tool_result:
96
+ raise ValueError("a turn carries either tool_call or tool_result, not both")
97
+ if self.tool_call and self.speaker != "agent":
98
+ raise ValueError("tool_call turns must have speaker='agent'")
99
+ if self.tool_result and self.speaker != "tool":
100
+ raise ValueError("tool_result turns must have speaker='tool'")
101
+ if self.speaker == "tool" and not self.tool_result:
102
+ raise ValueError("speaker='tool' turns must carry tool_result")
103
+ if self.spoken:
104
+ if not self.text:
105
+ raise ValueError("spoken turns need non-empty text")
106
+ if not self.lang:
107
+ raise ValueError("spoken turns need lang (BCP-47, e.g. 'en-US', 'hi-Latn')")
108
+ return self
109
+
110
+
111
+ class Transcription(_Strict):
112
+ engine: str
113
+ verified_by_human: bool = False
114
+
115
+
116
+ class Diarization(_Strict):
117
+ engine: str
118
+ confidence: float = Field(ge=0, le=1, default=1.0)
119
+
120
+
121
+ class Meta(_Strict):
122
+ source: Source
123
+ consent: Consent
124
+ consent_ref: str | None = None
125
+ voice_consent_ref: str | None = None
126
+ license: str | None = None
127
+ pii_redacted: bool
128
+ redaction_log: str | None = None
129
+ transcription: Transcription | None = None
130
+ diarization: Diarization | None = None
131
+ split: Split
132
+ created: datetime
133
+
134
+
135
+ class Conversation(_Strict):
136
+ """One conversation. Audio is optional: records built from documents, tables or chat
137
+ logs have no recording until `synth` renders one."""
138
+
139
+ id: str
140
+ schema_version: str = SCHEMA_VERSION
141
+ audio: Audio | None = None
142
+ locale: str
143
+ language: Language
144
+ domain: str | None = None
145
+ scenario: str | None = None
146
+ system_prompt: str | None = None
147
+ tools: list[Tool] = Field(default_factory=list)
148
+ turns: list[Turn] = Field(min_length=1)
149
+ meta: Meta
150
+
151
+ @model_validator(mode="after")
152
+ def _cross_turn_rules(self) -> Conversation:
153
+ prev_start = -1.0
154
+ for i, t in enumerate(self.turns):
155
+ if t.start < prev_start:
156
+ raise ValueError(f"turns[{i}]: turns must be sorted by start")
157
+ prev_start = t.start
158
+
159
+ tool_names = {t.name for t in self.tools}
160
+ call_ids: set[str] = set()
161
+ for i, t in enumerate(self.turns):
162
+ if t.tool_call:
163
+ if t.tool_call.id in call_ids:
164
+ raise ValueError(f"turns[{i}]: duplicate tool_call id {t.tool_call.id!r}")
165
+ call_ids.add(t.tool_call.id)
166
+ if t.tool_call.name not in tool_names:
167
+ raise ValueError(
168
+ f"turns[{i}]: tool_call {t.tool_call.name!r} not declared in tools"
169
+ )
170
+ if t.tool_result and t.tool_result.id not in call_ids:
171
+ raise ValueError(
172
+ f"turns[{i}]: tool_result references unknown call id {t.tool_result.id!r}"
173
+ )
174
+
175
+ if self.audio and self.turns:
176
+ last_end = max(t.end for t in self.turns)
177
+ if last_end > self.audio.duration_s + 0.5:
178
+ raise ValueError(
179
+ f"turns end at {last_end}s but audio.duration_s is {self.audio.duration_s}s"
180
+ )
181
+ return self
182
+
183
+
184
+ def json_schema() -> dict[str, Any]:
185
+ """JSON Schema for one `vakforge.jsonl` line, for external validators."""
186
+ schema = Conversation.model_json_schema()
187
+ schema["$schema"] = "https://json-schema.org/draft/2020-12/schema"
188
+ schema["title"] = f"vakforge conversation v{SCHEMA_VERSION}"
189
+ return schema
vakforge/validate.py ADDED
@@ -0,0 +1,226 @@
1
+ """`vakforge validate`: file-level rules from docs/DATA_FORMAT.md.
2
+
3
+ Schema-only rules are enforced by `vakforge.schema`; this module adds the checks that need
4
+ the filesystem (audio files), the locale registry, JSON-Schema tool arguments, and splits.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ import jsonschema
14
+ from pydantic import ValidationError
15
+
16
+ from vakforge.locales import get_pack
17
+ from vakforge.schema import Conversation
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Issue:
22
+ conv_id: str
23
+ field: str
24
+ message: str
25
+ fix: str = ""
26
+ line: int | None = None
27
+
28
+ def __str__(self) -> str:
29
+ where = f"line {self.line} " if self.line else ""
30
+ s = f"{where}{self.conv_id} · {self.field}: {self.message}"
31
+ return f"{s} → {self.fix}" if self.fix else s
32
+
33
+
34
+ def _pydantic_issues(conv_id: str, line: int, err: ValidationError) -> list[Issue]:
35
+ out = []
36
+ for e in err.errors():
37
+ loc = ".".join(str(p) for p in e["loc"]) or "<record>"
38
+ msg = e["msg"].removeprefix("Value error, ")
39
+ out.append(Issue(conv_id, loc, msg, line=line))
40
+ return out
41
+
42
+
43
+ def _check_audio(conv: Conversation, root: Path, line: int) -> list[Issue]:
44
+ if conv.audio is None:
45
+ return []
46
+ import soundfile as sf # local import keeps `import vakforge.schema` light
47
+
48
+ path = root / conv.audio.path
49
+ if not path.exists():
50
+ return [Issue(conv.id, "audio.path", f"{path} does not exist", "fix the path", line)]
51
+ try:
52
+ info = sf.info(str(path))
53
+ except Exception as exc: # soundfile raises RuntimeError/LibsndfileError
54
+ return [Issue(conv.id, "audio.path", f"cannot decode: {exc}", "re-encode as WAV", line)]
55
+ issues = []
56
+ if info.samplerate != conv.audio.sample_rate:
57
+ issues.append(
58
+ Issue(
59
+ conv.id,
60
+ "audio.sample_rate",
61
+ f"declared {conv.audio.sample_rate}, file is {info.samplerate}",
62
+ "run `vakforge prepare` to resample or fix the declaration",
63
+ line,
64
+ )
65
+ )
66
+ if info.channels != conv.audio.channels:
67
+ issues.append(
68
+ Issue(
69
+ conv.id,
70
+ "audio.channels",
71
+ f"declared {conv.audio.channels}, file has {info.channels}",
72
+ "fix the declaration or channel_map",
73
+ line,
74
+ )
75
+ )
76
+ if abs(info.duration - conv.audio.duration_s) > 0.5:
77
+ issues.append(
78
+ Issue(
79
+ conv.id,
80
+ "audio.duration_s",
81
+ f"declared {conv.audio.duration_s}, file is {info.duration:.2f}",
82
+ "set duration_s from the file",
83
+ line,
84
+ )
85
+ )
86
+ return issues
87
+
88
+
89
+ def _check_locale(conv: Conversation, line: int) -> list[Issue]:
90
+ try:
91
+ pack = get_pack(conv.locale)
92
+ except KeyError as exc:
93
+ return [Issue(conv.id, "locale", str(exc), "use a registered pack id", line)]
94
+ allowed = pack.all_languages()
95
+ return [
96
+ Issue(
97
+ conv.id,
98
+ f"turns[{i}].lang",
99
+ f"{t.lang!r} is not declared by pack {conv.locale!r} (allowed: {sorted(allowed)})",
100
+ "tag the turn with a language the pack declares, or pick another locale",
101
+ line,
102
+ )
103
+ for i, t in enumerate(conv.turns)
104
+ if t.lang and t.lang not in allowed
105
+ ]
106
+
107
+
108
+ def _check_tools(conv: Conversation, line: int) -> list[Issue]:
109
+ issues = []
110
+ schemas = {}
111
+ for i, tool in enumerate(conv.tools):
112
+ try:
113
+ jsonschema.Draft202012Validator.check_schema(tool.parameters)
114
+ schemas[tool.name] = jsonschema.Draft202012Validator(tool.parameters)
115
+ except jsonschema.SchemaError as exc:
116
+ issues.append(
117
+ Issue(
118
+ conv.id,
119
+ f"tools[{i}].parameters",
120
+ f"invalid JSON Schema: {exc.message}",
121
+ "fix the parameters schema",
122
+ line,
123
+ )
124
+ )
125
+ for i, t in enumerate(conv.turns):
126
+ if t.tool_call and (v := schemas.get(t.tool_call.name)):
127
+ for err in v.iter_errors(t.tool_call.arguments):
128
+ issues.append(
129
+ Issue(
130
+ conv.id,
131
+ f"turns[{i}].tool_call.arguments",
132
+ err.message,
133
+ "make the arguments match tools[].parameters",
134
+ line,
135
+ )
136
+ )
137
+ return issues
138
+
139
+
140
+ def _check_consent(conv: Conversation, line: int, allow_unconsented: bool) -> list[Issue]:
141
+ if conv.meta.consent == "none" and not allow_unconsented:
142
+ return [
143
+ Issue(
144
+ conv.id,
145
+ "meta.consent",
146
+ "consent is 'none'",
147
+ "record a consent basis, or pass --allow-unconsented (row stays unexportable)",
148
+ line,
149
+ )
150
+ ]
151
+ return []
152
+
153
+
154
+ def _check_splits(convs: list[Conversation], root: Path) -> list[Issue]:
155
+ """`splits.json`, when present, must agree with meta.split and cover every id."""
156
+ path = root / "splits.json"
157
+ if not path.exists():
158
+ return []
159
+ try:
160
+ splits: dict[str, list[str]] = json.loads(path.read_text(encoding="utf-8"))
161
+ except json.JSONDecodeError as exc:
162
+ return [Issue("<splits.json>", "splits.json", f"invalid JSON: {exc}", "fix the file")]
163
+ assigned: dict[str, str] = {}
164
+ issues = []
165
+ for split, ids in splits.items():
166
+ if split == "seed":
167
+ continue
168
+ for cid in ids:
169
+ if cid in assigned:
170
+ issues.append(
171
+ Issue(cid, "splits.json", f"in both {assigned[cid]} and {split}", "keep one")
172
+ )
173
+ assigned[cid] = split
174
+ for c in convs:
175
+ if c.id not in assigned:
176
+ issues.append(Issue(c.id, "splits.json", "not assigned to any split", "add it"))
177
+ elif assigned[c.id] != c.meta.split:
178
+ issues.append(
179
+ Issue(
180
+ c.id,
181
+ "meta.split",
182
+ f"row says {c.meta.split!r}, splits.json says {assigned[c.id]!r}",
183
+ "make them agree",
184
+ )
185
+ )
186
+ return issues
187
+
188
+
189
+ def validate_manifest(
190
+ manifest: Path, *, allow_unconsented: bool = False
191
+ ) -> tuple[list[Conversation], list[Issue]]:
192
+ """Validate a `vakforge.jsonl`. Returns the parsed conversations and every issue found.
193
+
194
+ Audio paths resolve relative to the manifest's directory, per docs/DATA_FORMAT.md.
195
+ """
196
+ root = manifest.parent
197
+ convs: list[Conversation] = []
198
+ issues: list[Issue] = []
199
+ seen_ids: set[str] = set()
200
+
201
+ with manifest.open(encoding="utf-8") as fh:
202
+ for line_no, raw in enumerate(fh, start=1):
203
+ if not raw.strip():
204
+ continue
205
+ try:
206
+ data = json.loads(raw)
207
+ except json.JSONDecodeError as exc:
208
+ issues.append(Issue("<unparsed>", "json", str(exc), "fix the JSON", line_no))
209
+ continue
210
+ conv_id = str(data.get("id", "<no id>")) if isinstance(data, dict) else "<no id>"
211
+ try:
212
+ conv = Conversation.model_validate(data)
213
+ except ValidationError as exc:
214
+ issues.extend(_pydantic_issues(conv_id, line_no, exc))
215
+ continue
216
+ if conv.id in seen_ids:
217
+ issues.append(Issue(conv.id, "id", "duplicate id", "ids must be unique", line_no))
218
+ seen_ids.add(conv.id)
219
+ convs.append(conv)
220
+ issues += _check_audio(conv, root, line_no)
221
+ issues += _check_locale(conv, line_no)
222
+ issues += _check_tools(conv, line_no)
223
+ issues += _check_consent(conv, line_no, allow_unconsented)
224
+
225
+ issues += _check_splits(convs, root)
226
+ return convs, issues
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.5
2
+ Name: vakforge
3
+ Version: 0.0.1
4
+ Summary: Turn the data your company already has into a self-hosted, real-time voice assistant.
5
+ Project-URL: Homepage, https://github.com/vakforge-ai/vakforge
6
+ Project-URL: Repository, https://github.com/vakforge-ai/vakforge
7
+ Author-email: vakforge <vakforge.ai@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: fine-tuning,locale,realtime,speech-to-speech,voice-agent
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: jsonschema>=4.21
19
+ Requires-Dist: numpy>=1.26
20
+ Requires-Dist: pydantic>=2.7
21
+ Requires-Dist: pyyaml>=6
22
+ Requires-Dist: rich>=13
23
+ Requires-Dist: soundfile>=0.12
24
+ Requires-Dist: typer>=0.12
25
+ Provides-Extra: cascade
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Requires-Dist: ruff>=0.5; extra == 'dev'
29
+ Provides-Extra: lfm25
30
+ Provides-Extra: moshi
31
+ Provides-Extra: qwen
32
+ Description-Content-Type: text/markdown
33
+
34
+ <p align="center">
35
+ <img src="https://raw.githubusercontent.com/vakforge-ai/vakforge/main/site/assets/social/readme-banner.webp" alt="vakforge: your data, your voice assistant, your hardware" width="100%">
36
+ </p>
37
+
38
+ # vakforge
39
+
40
+ **Turn the data your company already has into a self-hosted, real-time voice assistant.**
41
+
42
+ Documents, FAQs, database tables, chat logs, CRM records, recorded calls: vakforge works out what your assistant actually needs (knowledge, behaviour, tools, voice, language), generates the conversational data you lack, trains only what needs training, proves the result beats the base model on your own held-out data, and serves it on your hardware behind protocols your clients already speak, starting with the OpenAI Realtime WebSocket format. Open models only, nothing calls a hosted API, any language through locale packs. Launch locales: English (US, UK, India) and Hinglish.
43
+
44
+ > Status: pre-alpha. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what exists today.
45
+
46
+ ## The problem
47
+
48
+ Open speech-to-speech models exist (Moshi, PersonaPlex, LFM2.5-Audio, Qwen-Omni). Fine-tuning scripts exist for some of them. Evaluation tools exist. Serving frameworks exist. What does not exist is one path from *"here is what my company knows"* to *"here is a voice assistant that handles my workflow, I can prove it is better than the base model, and my existing voice client can talk to it without a rewrite."* Every team rebuilds that path badly, and most of them fine-tune when they should have used retrieval.
49
+
50
+ ## What ships
51
+
52
+ vakforge is three things in one repo:
53
+
54
+ 1. **A core library and CLI** (`pip install vakforge`). Zero ML dependencies. Canonical dataset schema, validator, data inspector, decision engine, locale packs. Runs on a laptop.
55
+ 2. **An agent skill** (`skill/`). Drop it into Claude Code or any coding agent. The agent reads your data, runs the decision guide, writes the recipe-specific glue for your project, and verifies every upstream API against source before using it. The knowledge lives here; the glue code is generated per project.
56
+ 3. **Recipes** (`docs/RECIPES.md`). Tested paths from base model to served assistant. Each is an optional extra, isolated because model libraries conflict. Only recipes run end to end get listed.
57
+
58
+ ```
59
+ vakforge inspect ./data -> what is actually in your documents, tables, chats, audio
60
+ vakforge recommend -> what needs customizing (often: retrieval, not the model)
61
+ vakforge prepare -> ingest, transcribe, redact PII, canonical dataset
62
+ vakforge synth -> synthetic dialogues in your locale over your tools and facts
63
+ vakforge train --recipe X -> one tested recipe, not a menu of 400 models
64
+ vakforge eval -> base vs tuned: WER, entities, tool calls, latency, voice
65
+ vakforge serve -> your open model behind the Realtime protocol; WebRTC and SIP next
66
+ ```
67
+
68
+ ## Bring any data
69
+
70
+ | You have | vakforge does |
71
+ |---|---|
72
+ | Documents, FAQs, SOPs, knowledge base | Retrieval at inference. Facts stay out of weights. Synthetic dialogues grounded in them. |
73
+ | Database tables, CRM, product catalogue | Tool definitions over your data, synthetic dialogues that exercise every tool, behaviour fine-tune for reliable tool use. |
74
+ | Chat logs, transcripts | Behaviour and workflow fine-tune of the language component; rendered to audio via `synth`. |
75
+ | Recorded calls (mono or stereo) | Transcribe, diarize, redact, then everything above plus voice, timing and full-duplex recipes. |
76
+ | Nothing yet | Scenario templates in your locale, rendered with open TTS, so you can ship a v0 and collect real data. |
77
+
78
+ ## Locale packs
79
+
80
+ The pipeline is language-agnostic. Everything language- or market-specific lives in a locale pack: number/currency/date/address formats, PII patterns, privacy-law notes, name generators for synthetic data, preferred models, and a benchmark. See [`docs/LOCALE_PACKS.md`](docs/LOCALE_PACKS.md).
81
+
82
+ | Pack | Covers | Speech output today | Status |
83
+ |---|---|---|---|
84
+ | `en` | en-US, en-GB, en-IN | native (all recipes) | launch |
85
+ | `hi-Latn` | Hinglish / Roman Hindi, Hindi-English code-switching | English output; Hindi via cascade | launch, the hard-case showcase |
86
+ | `zh-CN` | Mandarin | via `qwen-omni` | planned |
87
+ | `es`, `de`, `fr`, `pt-BR`, `ja`, `ar` | | via `qwen-omni` or cascade | planned, contributions welcome |
88
+
89
+ ## Recipes
90
+
91
+ | Recipe | Base model | Good for | Duplex | Hardware (train) | Status |
92
+ |---|---|---|---|---|---|
93
+ | `lfm25-audio` | LiquidAI LFM2.5-Audio-1.5B | workflow, tool use, style, CPU deploy | turn-based | 1x 24 GB GPU | planned (first) |
94
+ | `moshi-lora` | Kyutai Moshi / NVIDIA PersonaPlex | interruptions, natural timing, persona | full-duplex | 1x 40-80 GB GPU | planned |
95
+ | `qwen-omni` | Qwen3-Omni | multilingual incl. Mandarin, function calling | near-duplex | 80 GB / multi-GPU | planned |
96
+ | `cascade` | STT + LLM LoRA + TTS chosen by locale | any language with a good STT+TTS pair | turn-based | 1x 24 GB GPU | planned |
97
+
98
+ Details in [`docs/RECIPES.md`](docs/RECIPES.md).
99
+
100
+ ## Serving: open models, standard protocols
101
+
102
+ "OpenAI Realtime compatible" describes the wire format, not the model. Every recipe serves an open model on your hardware; nothing calls OpenAI or any hosted API. We speak the Realtime WebSocket format first because it is the closest thing voice agents have to a common protocol: teams already on GPT Realtime change one URL, and Pipecat, LiveKit and Twilio integrations work unchanged. Open speech-to-speech models each ship their own ad-hoc protocol, so copying a widely used shape beats inventing another.
103
+
104
+ The server separates the model backend from the protocol, so more front ends plug in without touching recipes:
105
+
106
+ | Protocol | For | Status |
107
+ |---|---|---|
108
+ | OpenAI Realtime WebSocket (documented subset) | teams migrating off GPT Realtime; Pipecat, LiveKit, Twilio clients | first |
109
+ | WebRTC via LiveKit or Pipecat transports | browser and mobile apps, lowest latency | next |
110
+ | SIP / telephony | call centres and phone lines | next |
111
+ | Plain HTTP, one turn per request | batch jobs, simple integrations | planned |
112
+ | Gemini Live API format | teams on Google's stack | on request |
113
+
114
+ ## Why launch with English and Hinglish
115
+
116
+ English is where the strongest open speech-to-speech models are, so every recipe works out of the box for US, UK and Indian English. Hinglish is the stress test: code-switching, Roman vs Devanagari script, Indian names and rupee amounts, noisy phone lines. If the pipeline handles that, a new locale pack is mostly formats and models, not new architecture.
117
+
118
+ ## Quick start (target UX, not all steps implemented yet)
119
+
120
+ ```bash
121
+ uv sync
122
+ uv run vakforge init my-assistant --locale en-US && cd my-assistant
123
+ uv run vakforge inspect ./data
124
+ uv run vakforge recommend
125
+ ```
126
+
127
+ ## Documentation
128
+
129
+ - [`docs/DECISION_GUIDE.md`](docs/DECISION_GUIDE.md): what actually needs customizing; when not to fine-tune
130
+ - [`docs/LOCALE_PACKS.md`](docs/LOCALE_PACKS.md): what a locale pack contains; how to add one
131
+ - [`docs/DATA_FORMAT.md`](docs/DATA_FORMAT.md): canonical dataset schema
132
+ - [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md): package layout
133
+ - [`docs/RECIPES.md`](docs/RECIPES.md): per-model training recipes
134
+ - [`docs/EVALUATION.md`](docs/EVALUATION.md): metrics, report format, per-locale benchmarks
135
+ - [`docs/DATA_ETHICS.md`](docs/DATA_ETHICS.md): consent, PII, licences, privacy law by region
136
+ - [`docs/ROADMAP.md`](docs/ROADMAP.md): status
137
+ - [`CONTRIBUTING.md`](CONTRIBUTING.md)
138
+
139
+ ## Related projects (we build on these, not against them)
140
+
141
+ Unsloth, LLaMA-Factory, ms-swift, kyutai-labs/moshi-finetune, NVIDIA PersonaPlex, liquid-audio, Qwen-Omni, Pipecat, LiveKit Agents, vLLM-omni, UltraEval-Audio, AI4Bharat, Common Voice
142
+
143
+ ## Licence
144
+
145
+ Apache-2.0 for this code. Each recipe's base model has its own licence, see `docs/RECIPES.md`. Datasets you create with vakforge are yours; the consent metadata we require is there to keep it that way.
@@ -0,0 +1,13 @@
1
+ vakforge/__init__.py,sha256=5h9Ii_gTeHNgUtGEmpnWp265KGKbEd6IId5AJA5lB6o,114
2
+ vakforge/cli.py,sha256=0IwEmnxwtEpqfRLHeHKThUofFJXWxTQi-8n7FSC1n3c,3667
3
+ vakforge/config.py,sha256=PSNJnKkFyWeqHAkSHtfghIzKWHlHjfhOOcT6sHB7Z_Y,815
4
+ vakforge/schema.py,sha256=M5-U03o03fBJ95p32NuMajf5RMIgCCL8FMYX1BqYWGU,6277
5
+ vakforge/validate.py,sha256=zKMGive36ixTk1vzMc0Dy944zzLRgKxYTOMdL-pktRI,7965
6
+ vakforge/locales/__init__.py,sha256=ZZSOQQh6N7HKIBXlCY-gUnKunBC4Wm2rTooWm1Fpl5c,298
7
+ vakforge/locales/base.py,sha256=kqLMp3LgW3ooMu_QRH5vUDDySVEOhyPMyruX7iRE8ys,1722
8
+ vakforge/locales/en.py,sha256=CZ_Zl3VFUJGNezFXOHubcSy26Mw5b5rOu1A9qZnfTP0,664
9
+ vakforge-0.0.1.dist-info/METADATA,sha256=E0o03pfq6lojnC50H5-v2CeyvZTM6-hRDT62kbYgSoY,9151
10
+ vakforge-0.0.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
11
+ vakforge-0.0.1.dist-info/entry_points.txt,sha256=jYQ3xAhnUbJesULZn-Y8OVVJzVmdiAe9ueHTXaZQKgc,46
12
+ vakforge-0.0.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ vakforge-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vakforge = vakforge.cli:app
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.