borg-nlp 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.
borg/__init__.py ADDED
@@ -0,0 +1,150 @@
1
+ """Public Python API for borg-cube.
2
+
3
+ Usage::
4
+
5
+ from borg import cube
6
+ nlp = cube('en')
7
+ sentences = nlp("The cat sat on the mat.")
8
+ print(sentences)
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from typing import List, Mapping, Optional
14
+ from urllib.parse import unquote
15
+
16
+ from src.config import BorgConfig
17
+ from src.data.conllu import Sentence
18
+ from src.pipeline.pipeline import BorgPipeline
19
+
20
+
21
+ class Cube:
22
+ """High-level interface to the borg-cube NLP pipeline.
23
+
24
+ Parameters
25
+ ----------
26
+ lang:
27
+ Language code (used for locating default model files).
28
+ model_path:
29
+ Base directory containing sub-directories for each component
30
+ (``tokenizer/``, ``mwt/``, ``tagger/``, ``parser/``, ``lemmatizer/``).
31
+ If *None*, defaults to ``~/.borg_cube/<lang>/``.
32
+ components:
33
+ List of components to load. Defaults to all pipeline components.
34
+ config:
35
+ Optional :class:`~src.config.BorgConfig` instance.
36
+ """
37
+
38
+ DEFAULT_COMPONENTS = ["tokenizer", "mwt", "tagger", "parser", "lemmatizer"]
39
+
40
+ def __init__(
41
+ self,
42
+ lang: str = "en",
43
+ model_path: Optional[str] = None,
44
+ components: Optional[List[str]] = None,
45
+ config: Optional[BorgConfig] = None,
46
+ _component_paths: Optional[Mapping[str, str]] = None,
47
+ ):
48
+ self.lang = lang
49
+ if model_path is None and _component_paths is None:
50
+ model_path = os.path.join(os.path.expanduser("~"), ".borg_cube", lang)
51
+ self.model_path = model_path
52
+
53
+ if config is None:
54
+ config = BorgConfig(lang=lang)
55
+ self.config = config
56
+
57
+ components = self.DEFAULT_COMPONENTS if components is None else components
58
+
59
+ self.pipeline = BorgPipeline(config)
60
+ for component in components:
61
+ if _component_paths is not None:
62
+ self.pipeline.load_component(
63
+ component,
64
+ _component_paths[component],
65
+ )
66
+ else:
67
+ component_dir = os.path.join(model_path, component)
68
+ if os.path.isdir(component_dir):
69
+ self.pipeline.load_component(component, component_dir)
70
+
71
+ # ------------------------------------------------------------------
72
+ def __call__(self, text: str) -> List[Sentence]:
73
+ """Process *text* and return a list of annotated :class:`Sentence` objects."""
74
+ return self.pipeline.process(text)
75
+
76
+ def __repr__(self) -> str:
77
+ loaded = [
78
+ c for c in self.DEFAULT_COMPONENTS
79
+ if getattr(self.pipeline, f"{c}_model") is not None
80
+ ]
81
+ return f"Cube(lang={self.lang!r}, loaded={loaded})"
82
+
83
+
84
+ def cube(
85
+ model: str,
86
+ components: Optional[List[str]] = None,
87
+ config: Optional[BorgConfig] = None,
88
+ *,
89
+ adapter_variant: Optional[str] = None,
90
+ checkpoint: str = "best",
91
+ ) -> Cube:
92
+ """Load a local model or download component adapters from the Hub.
93
+
94
+ ``cube("en")`` loads local components from ``~/.borg_cube/en/``.
95
+ ``cube("file:///path/to/models")`` loads from a local folder.
96
+ A Hub base ID such as ``"racai/borg"`` downloads component repos named
97
+ ``racai/borg-<component>``; ``adapter_variant="combined"`` appends
98
+ ``-combined`` to each component repo name. No base pipeline repo is needed.
99
+ """
100
+ if model.startswith("file://"):
101
+ model_path = unquote(model[len("file://"):])
102
+ if not model_path:
103
+ raise ValueError("A file:// model URI must include a folder path")
104
+ lang = os.path.basename(os.path.normpath(model_path)) or "en"
105
+ return Cube(lang=lang, model_path=model_path, components=components, config=config)
106
+
107
+ if model.count("/") == 1 and not model.startswith((".", "/")):
108
+ selected_components = (
109
+ Cube.DEFAULT_COMPONENTS if components is None else components
110
+ )
111
+ if not selected_components:
112
+ return Cube(
113
+ lang=config.lang if config is not None else "en",
114
+ components=[],
115
+ config=config,
116
+ _component_paths={},
117
+ )
118
+ unknown = set(selected_components) - set(Cube.DEFAULT_COMPONENTS)
119
+ if unknown:
120
+ raise ValueError(f"Unknown components: {', '.join(sorted(unknown))}")
121
+
122
+ from src.models.hub import download_component_checkpoints
123
+
124
+ component_paths = download_component_checkpoints(
125
+ model,
126
+ selected_components,
127
+ variant=adapter_variant,
128
+ checkpoint=checkpoint,
129
+ )
130
+ if config is None:
131
+ import json
132
+
133
+ first_checkpoint = next(iter(component_paths.values()))
134
+ with (first_checkpoint / "borg_config.json").open(
135
+ encoding="utf-8"
136
+ ) as source:
137
+ config = BorgConfig.from_dict(json.load(source))
138
+ config.device = "auto"
139
+
140
+ return Cube(
141
+ lang=config.lang,
142
+ components=selected_components,
143
+ config=config,
144
+ _component_paths={
145
+ component: str(path)
146
+ for component, path in component_paths.items()
147
+ },
148
+ )
149
+
150
+ return Cube(lang=model, components=components, config=config)
borg/cli.py ADDED
@@ -0,0 +1,215 @@
1
+ """CLI entry point for borg-cube.
2
+
3
+ Commands
4
+ --------
5
+ borg train --component <component> <train_file> <dev_file> <model_file>
6
+ borg test <model_file> <input_file> <output_file>
7
+ borg upload <component_path> <repo_id>
8
+ borg upload <base_repo_id> --pipeline
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import sys
14
+ import tempfile
15
+ from pathlib import Path
16
+
17
+ from huggingface_hub import HfApi
18
+ from src.config import BorgConfig
19
+ from src.pipeline.pipeline import BorgPipeline
20
+
21
+
22
+ def _build_parser() -> argparse.ArgumentParser:
23
+ top = argparse.ArgumentParser(
24
+ prog="borg",
25
+ description="borg-cube NLP pipeline CLI",
26
+ )
27
+ sub = top.add_subparsers(dest="command", required=True)
28
+
29
+ # ---- train ----
30
+ train_p = sub.add_parser("train", help="Train a pipeline component")
31
+ train_p.add_argument(
32
+ "--component",
33
+ choices=["tokenizer", "mwt", "tagger", "parser", "lemmatizer"],
34
+ required=True,
35
+ help="Component to train",
36
+ )
37
+ train_p.add_argument("train_file", help="Path to CoNLL-U training file")
38
+ train_p.add_argument("dev_file", help="Path to CoNLL-U development file")
39
+ train_p.add_argument("model_file", help="Model folder; the component is saved in its subfolder")
40
+ train_p.add_argument("--resume", action="store_true", help="Resume from the component's last checkpoint")
41
+
42
+ # Optional training hyper-parameter overrides
43
+ train_p.add_argument("--epochs", type=int, default=None)
44
+ train_p.add_argument("--batch-size", type=int, default=None)
45
+ train_p.add_argument("--lr", type=float, default=None)
46
+ train_p.add_argument("--device", type=str, default=None)
47
+ train_p.add_argument("--lang", type=str, default="en")
48
+
49
+ # ---- test ----
50
+ test_p = sub.add_parser("test", help="Run inference with a trained model/pipeline")
51
+ test_p.add_argument("model_file", help="Model directory (or pipeline root)")
52
+ test_p.add_argument("input_file", help="Input file (.txt for raw text, .conllu for annotated)")
53
+ test_p.add_argument("output_file", help="Output CoNLL-U file")
54
+ test_p.add_argument(
55
+ "--component",
56
+ choices=["tokenizer", "mwt", "tagger", "parser", "lemmatizer"],
57
+ default=None,
58
+ help="Single component to apply (default: auto-detect from directory contents)",
59
+ )
60
+ test_p.add_argument("--device", type=str, default=None)
61
+ test_p.add_argument("--lang", type=str, default="en")
62
+
63
+ # ---- upload ----
64
+ upload_p = sub.add_parser(
65
+ "upload",
66
+ help="Upload a component or complete pipeline to the Hugging Face Hub",
67
+ )
68
+ upload_p.add_argument(
69
+ "model_path",
70
+ nargs="?",
71
+ help="Component directory for raw upload; ignored with --pipeline",
72
+ )
73
+ upload_p.add_argument(
74
+ "repo_id",
75
+ nargs="?",
76
+ help="Hub repository ID (or the only positional argument with --pipeline)",
77
+ )
78
+ upload_p.add_argument(
79
+ "--pipeline",
80
+ action="store_true",
81
+ help="Upload pipeline metadata/code; adapters use <repo_id>-<component> repos",
82
+ )
83
+ upload_p.add_argument(
84
+ "--components",
85
+ nargs="+",
86
+ choices=["tokenizer", "mwt", "tagger", "parser", "lemmatizer"],
87
+ default=None,
88
+ help="Components to include in the pipeline (default: all)",
89
+ )
90
+ upload_p.add_argument(
91
+ "--checkpoint",
92
+ choices=["best", "last"],
93
+ default="best",
94
+ help=(
95
+ "Use this checkpoint subfolder, or a root-level adapter if absent "
96
+ "(default: best)"
97
+ ),
98
+ )
99
+
100
+ return top
101
+
102
+
103
+ def _make_config(args: argparse.Namespace) -> BorgConfig:
104
+ cfg = BorgConfig(lang=getattr(args, "lang", "en"))
105
+ if getattr(args, "epochs", None) is not None:
106
+ cfg.num_epochs = args.epochs
107
+ if getattr(args, "batch_size", None) is not None:
108
+ cfg.batch_size = args.batch_size
109
+ if getattr(args, "lr", None) is not None:
110
+ cfg.learning_rate = args.lr
111
+ if getattr(args, "device", None) is not None:
112
+ cfg.device = args.device
113
+ return cfg
114
+
115
+
116
+ def cmd_train(args: argparse.Namespace) -> None:
117
+ config = _make_config(args)
118
+ pipeline = BorgPipeline(config)
119
+ pipeline.train_component(
120
+ args.component, args.train_file, args.dev_file, args.model_file,
121
+ resume=args.resume,
122
+ )
123
+ print(
124
+ f"Saved {args.component} last and best models to "
125
+ f"{args.model_file}/{args.component}/{{last,best}}"
126
+ )
127
+
128
+
129
+ def cmd_test(args: argparse.Namespace) -> None:
130
+ import os
131
+
132
+ config = _make_config(args)
133
+ pipeline = BorgPipeline(config)
134
+
135
+ if args.component is not None:
136
+ # Single component test
137
+ pipeline.load_component(args.component, args.model_file)
138
+ else:
139
+ # Auto-detect: try to load whichever component directories exist
140
+ for comp in ["tokenizer", "mwt", "tagger", "parser", "lemmatizer"]:
141
+ comp_dir = os.path.join(args.model_file, comp)
142
+ if os.path.isdir(comp_dir):
143
+ pipeline.load_component(comp, comp_dir)
144
+ elif os.path.isfile(os.path.join(args.model_file, "borg_config.json")):
145
+ # model_file IS a single component directory
146
+ # figure out which one
147
+ import json
148
+ with open(os.path.join(args.model_file, "borg_config.json")) as f:
149
+ info = json.load(f)
150
+ detected = info.get("component")
151
+ if detected:
152
+ pipeline.load_component(detected, args.model_file)
153
+ break
154
+
155
+ pipeline.test(args.model_file, args.input_file, args.output_file)
156
+
157
+
158
+ def _upload_folder(folder: Path, repo_id: str) -> None:
159
+ api = HfApi()
160
+ api.create_repo(repo_id, repo_type="model", exist_ok=True)
161
+ api.upload_folder(
162
+ repo_id=repo_id,
163
+ repo_type="model",
164
+ folder_path=str(folder),
165
+ )
166
+ print(f"Uploaded to https://huggingface.co/{repo_id}")
167
+
168
+
169
+ def cmd_upload(args: argparse.Namespace) -> None:
170
+ if args.pipeline:
171
+ repo_id = args.repo_id or args.model_path
172
+ if not repo_id:
173
+ raise ValueError("A Hub repo ID is required for pipeline upload")
174
+ from src.pipeline.hf.export import export_hf_repo
175
+
176
+ with tempfile.TemporaryDirectory(prefix="borg-hf-upload-") as temp_dir:
177
+ export_path = Path(temp_dir) / "model"
178
+ export_hf_repo(
179
+ export_path,
180
+ components=args.components,
181
+ checkpoint=args.checkpoint,
182
+ )
183
+ _upload_folder(export_path, repo_id)
184
+ return
185
+
186
+ if args.model_path is None or args.repo_id is None:
187
+ raise ValueError("Raw component upload requires a directory and a Hub repo ID")
188
+ if args.components is not None:
189
+ raise ValueError("--components can only be used with --pipeline")
190
+ model_path = Path(args.model_path).expanduser()
191
+ if not model_path.is_dir():
192
+ raise FileNotFoundError(f"Model directory not found: {model_path}")
193
+
194
+ if args.checkpoint != "best":
195
+ raise ValueError("--checkpoint can only be used with --pipeline")
196
+ _upload_folder(model_path, args.repo_id)
197
+
198
+
199
+ def main(argv=None) -> None:
200
+ parser = _build_parser()
201
+ args = parser.parse_args(argv)
202
+
203
+ if args.command == "train":
204
+ cmd_train(args)
205
+ elif args.command == "test":
206
+ cmd_test(args)
207
+ elif args.command == "upload":
208
+ cmd_upload(args)
209
+ else:
210
+ parser.print_help()
211
+ sys.exit(1)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ main()
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: borg-nlp
3
+ Version: 0.1.0
4
+ Summary: A complete NLP processing pipeline using DeBERTa-v3 and adapters
5
+ Classifier: Programming Language :: Python :: 3
6
+ Classifier: License :: OSI Approved :: MIT License
7
+ Classifier: Operating System :: OS Independent
8
+ Requires-Python: >=3.8
9
+ Requires-Dist: torch>=2.0.0
10
+ Requires-Dist: transformers>=4.35.0
11
+ Requires-Dist: huggingface_hub>=0.19.0
12
+ Requires-Dist: adapters>=0.1.1
13
+ Requires-Dist: numpy>=1.24.0
14
+ Requires-Dist: tqdm>=4.65.0
15
+ Requires-Dist: sentencepiece>=0.1.99
16
+ Requires-Dist: protobuf>=3.20.0
17
+ Dynamic: classifier
18
+ Dynamic: requires-dist
19
+ Dynamic: requires-python
20
+ Dynamic: summary
@@ -0,0 +1,33 @@
1
+ borg/__init__.py,sha256=RE0LVc0iPffaXts2LorOGR-dgqQv_Vn0Tnl4Ynbdjnw,5225
2
+ borg/cli.py,sha256=1MkPcdK-MzKX8KHeABjyxS4sEGLm2sAfNgzmHy2SDws,7468
3
+ eval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ eval/conll18_ud_eval.py,sha256=LzMy4wTAStz1bcHHlJfe60qc0FPVrwk8vEBDaMMivMk,14549
5
+ src/__init__.py,sha256=uokoi8vPiC2ztuusrwNJQcQmoOfieewSJFb7AYBTV40,46
6
+ src/config.py,sha256=kCX-4hl2-u4JD-hCsPkTpvDI2FKZMIrN1vw46sLeqZQ,4158
7
+ src/data/__init__.py,sha256=zjIRUxGJaTWHErLK_Gfxa3k0b2P5dChuWkuLYnzPm8M,24
8
+ src/data/conllu.py,sha256=e8WxnO5M7Z4y56svpkbLO7pSln6DdZvc_f4S3i4y0nc,7038
9
+ src/data/dataset.py,sha256=28StGcxn-L6IqnEDVjOdjAKegfoxFM8w6PtBZaC565s,24221
10
+ src/models/__init__.py,sha256=dOtj1x8VJZ2qVhV324yYfNI8IDwNVxlnbP_QkXqB84A,26
11
+ src/models/base.py,sha256=oMR4J4VONBRx8N4YrksqA5DOXEBGm0xBVQow1hn98k4,3436
12
+ src/models/checkpoints.py,sha256=KYPr60_366yqShjJgfvpLOGDEu6hRTpH9zBHUZStlec,4799
13
+ src/models/evaluation.py,sha256=5JPpjiDu7HOxXM4ONrfvtyXZrMi9UoJrnB2QtLPMA4Q,2047
14
+ src/models/hub.py,sha256=HWBFxgNP9ZRIt70ByKuPkIEs_H3lp5zBmvDa2MZU5FU,1838
15
+ src/models/inference.py,sha256=3fpcLZLat2ItNGJ510vyxXrww-pdvxna776lMemyIYs,4508
16
+ src/models/lemmatizer.py,sha256=waPWFQyPmVG5YbQNwxNKvTBOezchFYGxgmBY9kA47Ac,17047
17
+ src/models/mwt.py,sha256=Gx4J72Z3TEB-rQbooWkinwwCrii_q-c16K3mQ72E2pg,16607
18
+ src/models/parser.py,sha256=fN2wemp6W1hAW81fIFmE1vMN5JxbWChxFZ35Wg4LESU,20019
19
+ src/models/tagger.py,sha256=hYfVyBrf0Ffc_-69QrEnh7X_0KhPm2nQSm9Urv6NGAk,10265
20
+ src/models/tokenizer.py,sha256=vCKdsDD5SdLkRba58_7vrj4iEJgJgPGf0zGZaKInwXI,15144
21
+ src/pipeline/__init__.py,sha256=c_50JIixQKIq0E31OAYJAFtBy2d6uSPNDTXoonQeHlA,28
22
+ src/pipeline/pipeline.py,sha256=h4qK-_OM6cplDNP_6EumUZHbvdcNubFsWbIARcOhC7k,6489
23
+ src/pipeline/hf/__init__.py,sha256=LYch0ZrZd2HQCWmEFcw_Obuk_mvEJ6o5jZZ0jAt-BoI,152
24
+ src/pipeline/hf/config.json,sha256=B7ZilI0rh-6qwPZgYwpXH6G4BPJihweD_8420AqKc4Y,413
25
+ src/pipeline/hf/configuration_borg.py,sha256=zl-yuskijss_XEKz527oHz5Lv1hN7zA5w2X4PJv_J68,642
26
+ src/pipeline/hf/export.py,sha256=Vyidnyi9Azw2mQd2HgicI0qM1GYfWQ50IrU27Afy9ds,4632
27
+ src/pipeline/hf/modeling_borg.py,sha256=6ssag5EvxoarmpTW7SuzGWn0XE3FnryELUbfQKrkfw4,807
28
+ src/pipeline/hf/pipeline.py,sha256=8EzqD5c6P_4sgB8Arhpl2dsoy65_9MqBb5gsJfbAec0,6875
29
+ borg_nlp-0.1.0.dist-info/METADATA,sha256=Ys1dayjDLxvN0Y5fXOl-XU40c5SJ0-u6POj3o1niJC4,640
30
+ borg_nlp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
31
+ borg_nlp-0.1.0.dist-info/entry_points.txt,sha256=U7oYX5vgKMOvSYwJdtoFQ61ZMxtP8i1sypc8UPFjhAg,39
32
+ borg_nlp-0.1.0.dist-info/top_level.txt,sha256=kVAHZGFSdjNkM6WPeYUgHUznMkucZ-sIaLKfd6iy1Fw,14
33
+ borg_nlp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ borg = borg.cli:main
@@ -0,0 +1,3 @@
1
+ borg
2
+ eval
3
+ src
eval/__init__.py ADDED
File without changes