indian-address-parser 0.1.0__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .pytest_cache/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .venv/
@@ -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.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: indian-address-parser
3
+ Version: 0.1.0
4
+ Summary: Parse raw Indian address strings into structured fields using a fine-tuned Qwen3 LoRA adapter
5
+ Project-URL: Homepage, https://github.com/innerkorehq/indian-address-parser
6
+ Project-URL: Repository, https://github.com/innerkorehq/indian-address-parser
7
+ Project-URL: Model, https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser
8
+ Author: Gagandeep
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: address-parsing,india,lora,named-entity-recognition,nlp,qwen
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Text Processing :: Linguistic
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: huggingface-hub>=0.25.0
18
+ Requires-Dist: peft>=0.12.0
19
+ Requires-Dist: torch>=2.0.0
20
+ Requires-Dist: transformers>=4.45.0
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7.0.0; extra == 'test'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # indian-address-parser
26
+
27
+ Parse raw, unstructured Indian address strings into 13 structured fields using a
28
+ Qwen3-0.6B model fine-tuned with LoRA. Model weights are downloaded automatically from
29
+ [Hugging Face](https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser) — this
30
+ package ships only inference code, no weights.
31
+
32
+ ```
33
+ Input: "FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029"
34
+ Output: {"houseNumber": "FLAT NO.32", "houseName": "UTTARA TOWERS", "poi": null,
35
+ "street": "MG ROAD", "subsubLocality": null, "subLocality": null, "locality": null,
36
+ "village": null, "subDistrict": null, "district": "Kamrup", "city": "GUWAHATI",
37
+ "state": "AS", "pincode": "781029"}
38
+ ```
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install indian-address-parser
44
+ ```
45
+
46
+ ## Usage
47
+
48
+ ### Python
49
+
50
+ ```python
51
+ from indian_address_parser import AddressParser
52
+
53
+ parser = AddressParser() # downloads model weights from HF on first use
54
+ result = parser.parse("FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029")
55
+ print(result)
56
+
57
+ # Batch
58
+ results = parser.parse_batch([addr1, addr2, addr3])
59
+ ```
60
+
61
+ ### CLI
62
+
63
+ ```bash
64
+ # Single address
65
+ indian-address-parser "FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029"
66
+
67
+ # Batch from stdin
68
+ cat addresses.txt | indian-address-parser --stdin
69
+
70
+ # Batch from a file, JSONL output
71
+ indian-address-parser --file addresses.txt --out results.jsonl
72
+ ```
73
+
74
+ ## Fields
75
+
76
+ ```
77
+ houseNumber, houseName, poi, street, subsubLocality, subLocality,
78
+ locality, village, subDistrict, district, city, state, pincode
79
+ ```
80
+
81
+ Any field not present in the address is `null`. If the model output can't be parsed as
82
+ JSON, all fields are `null` and a `_parse_error` key holds the raw model output.
83
+
84
+ ## Model details, evaluation metrics, and known limitations
85
+
86
+ See the [model card](https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser)
87
+ for training data, LoRA config, per-field evaluation results (100% JSON parse rate, 82.4%
88
+ mean field accuracy on held-out test data), and known limitations (locality/subLocality/
89
+ subsubLocality/village field-boundary ambiguity, etc.).
90
+
91
+ ## Apple Silicon (MLX) users
92
+
93
+ This package uses `transformers`+`peft`, which works on CUDA, MPS, and CPU but is not the
94
+ fastest path on Apple Silicon. For MLX-native inference, see the `mlx/` subfolder of the
95
+ [Hugging Face repo](https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser/tree/main/mlx)
96
+ instead.
97
+
98
+ ## License
99
+
100
+ Apache 2.0 (matching the base model, Qwen/Qwen3-0.6B).
@@ -0,0 +1,76 @@
1
+ # indian-address-parser
2
+
3
+ Parse raw, unstructured Indian address strings into 13 structured fields using a
4
+ Qwen3-0.6B model fine-tuned with LoRA. Model weights are downloaded automatically from
5
+ [Hugging Face](https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser) — this
6
+ package ships only inference code, no weights.
7
+
8
+ ```
9
+ Input: "FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029"
10
+ Output: {"houseNumber": "FLAT NO.32", "houseName": "UTTARA TOWERS", "poi": null,
11
+ "street": "MG ROAD", "subsubLocality": null, "subLocality": null, "locality": null,
12
+ "village": null, "subDistrict": null, "district": "Kamrup", "city": "GUWAHATI",
13
+ "state": "AS", "pincode": "781029"}
14
+ ```
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install indian-address-parser
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ### Python
25
+
26
+ ```python
27
+ from indian_address_parser import AddressParser
28
+
29
+ parser = AddressParser() # downloads model weights from HF on first use
30
+ result = parser.parse("FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029")
31
+ print(result)
32
+
33
+ # Batch
34
+ results = parser.parse_batch([addr1, addr2, addr3])
35
+ ```
36
+
37
+ ### CLI
38
+
39
+ ```bash
40
+ # Single address
41
+ indian-address-parser "FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029"
42
+
43
+ # Batch from stdin
44
+ cat addresses.txt | indian-address-parser --stdin
45
+
46
+ # Batch from a file, JSONL output
47
+ indian-address-parser --file addresses.txt --out results.jsonl
48
+ ```
49
+
50
+ ## Fields
51
+
52
+ ```
53
+ houseNumber, houseName, poi, street, subsubLocality, subLocality,
54
+ locality, village, subDistrict, district, city, state, pincode
55
+ ```
56
+
57
+ Any field not present in the address is `null`. If the model output can't be parsed as
58
+ JSON, all fields are `null` and a `_parse_error` key holds the raw model output.
59
+
60
+ ## Model details, evaluation metrics, and known limitations
61
+
62
+ See the [model card](https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser)
63
+ for training data, LoRA config, per-field evaluation results (100% JSON parse rate, 82.4%
64
+ mean field accuracy on held-out test data), and known limitations (locality/subLocality/
65
+ subsubLocality/village field-boundary ambiguity, etc.).
66
+
67
+ ## Apple Silicon (MLX) users
68
+
69
+ This package uses `transformers`+`peft`, which works on CUDA, MPS, and CPU but is not the
70
+ fastest path on Apple Silicon. For MLX-native inference, see the `mlx/` subfolder of the
71
+ [Hugging Face repo](https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser/tree/main/mlx)
72
+ instead.
73
+
74
+ ## License
75
+
76
+ Apache 2.0 (matching the base model, Qwen/Qwen3-0.6B).
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "indian-address-parser"
7
+ version = "0.1.0"
8
+ description = "Parse raw Indian address strings into structured fields using a fine-tuned Qwen3 LoRA adapter"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9"
12
+ authors = [
13
+ { name = "Gagandeep" }
14
+ ]
15
+ keywords = ["nlp", "address-parsing", "india", "named-entity-recognition", "lora", "qwen"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Operating System :: OS Independent",
20
+ "Topic :: Text Processing :: Linguistic",
21
+ ]
22
+ dependencies = [
23
+ "torch>=2.0.0",
24
+ "transformers>=4.45.0",
25
+ "peft>=0.12.0",
26
+ "huggingface_hub>=0.25.0",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/innerkorehq/indian-address-parser"
31
+ Repository = "https://github.com/innerkorehq/indian-address-parser"
32
+ Model = "https://huggingface.co/gagan1985/qwen3-0.6b-indian-address-parser"
33
+
34
+ [project.scripts]
35
+ indian-address-parser = "indian_address_parser.cli:main"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/indian_address_parser"]
39
+
40
+ [tool.pytest.ini_options]
41
+ markers = ["slow: requires network access, downloads real model weights"]
42
+
43
+ [project.optional-dependencies]
44
+ test = ["pytest>=7.0.0"]
@@ -0,0 +1,4 @@
1
+ from .parser import ALL_FIELDS, DEFAULT_ADAPTER_REPO, DEFAULT_BASE_MODEL, SYSTEM_PROMPT, AddressParser
2
+
3
+ __all__ = ["AddressParser", "ALL_FIELDS", "SYSTEM_PROMPT", "DEFAULT_ADAPTER_REPO", "DEFAULT_BASE_MODEL"]
4
+ __version__ = "0.1.0"
@@ -0,0 +1,56 @@
1
+ """CLI for indian-address-parser.
2
+
3
+ Usage:
4
+ indian-address-parser "FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029"
5
+ cat addresses.txt | indian-address-parser --stdin
6
+ indian-address-parser --file addresses.txt --out results.jsonl
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+
14
+ from .parser import DEFAULT_ADAPTER_REPO, DEFAULT_BASE_MODEL, AddressParser
15
+
16
+
17
+ def main():
18
+ p = argparse.ArgumentParser(description="Parse Indian addresses into structured fields")
19
+ p.add_argument("address", nargs="?", help="Single address to parse")
20
+ p.add_argument("--stdin", action="store_true", help="Read addresses from stdin, one per line")
21
+ p.add_argument("--file", help="Read addresses from a text file, one per line")
22
+ p.add_argument("--out", help="Write JSONL output to file (default: stdout)")
23
+ p.add_argument("--adapter-repo", default=DEFAULT_ADAPTER_REPO, help="HF Hub repo for the LoRA adapter")
24
+ p.add_argument("--base-model", default=DEFAULT_BASE_MODEL, help="HF Hub repo for the base model")
25
+ args = p.parse_args()
26
+
27
+ if args.address:
28
+ addresses = [args.address]
29
+ elif args.stdin:
30
+ addresses = [line.rstrip("\n") for line in sys.stdin if line.strip()]
31
+ elif args.file:
32
+ with open(args.file, encoding="utf-8") as f:
33
+ addresses = [line.rstrip("\n") for line in f if line.strip()]
34
+ else:
35
+ p.print_help()
36
+ return
37
+
38
+ parser = AddressParser(adapter_repo=args.adapter_repo, base_model=args.base_model)
39
+
40
+ out_f = open(args.out, "w", encoding="utf-8") if args.out else None
41
+ for addr in addresses:
42
+ result = parser.parse(addr)
43
+ result["_raw_address"] = addr
44
+ line = json.dumps(result, ensure_ascii=False)
45
+ if out_f:
46
+ out_f.write(line + "\n")
47
+ else:
48
+ print(line)
49
+
50
+ if out_f:
51
+ out_f.close()
52
+ print(f"Wrote {len(addresses):,} results to {args.out}", file=sys.stderr)
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()
@@ -0,0 +1,118 @@
1
+ """Core AddressParser class.
2
+
3
+ Loads a LoRA adapter from Hugging Face Hub on top of a base Qwen3 model and parses
4
+ raw Indian address strings into structured fields. Model tensors are always fetched
5
+ from the Hugging Face repo (default: gagan1985/qwen3-0.6b-indian-address-parser) —
6
+ this package ships only inference code, no weights.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+
12
+ DEFAULT_ADAPTER_REPO = "gagan1985/qwen3-0.6b-indian-address-parser"
13
+ DEFAULT_BASE_MODEL = "Qwen/Qwen3-0.6B"
14
+
15
+ ALL_FIELDS = (
16
+ "houseNumber",
17
+ "houseName",
18
+ "poi",
19
+ "street",
20
+ "subsubLocality",
21
+ "subLocality",
22
+ "locality",
23
+ "village",
24
+ "subDistrict",
25
+ "district",
26
+ "city",
27
+ "state",
28
+ "pincode",
29
+ )
30
+
31
+ SYSTEM_PROMPT = (
32
+ "You are an Indian address parser. Given a raw address string, extract address "
33
+ "fields and return them as a JSON object. Use null for fields not present in the "
34
+ "address. Output only the JSON object, no explanation.\n\n"
35
+ "Fields: " + ", ".join(ALL_FIELDS)
36
+ )
37
+
38
+ USER_TEMPLATE = "Parse this address:\n{raw_address}"
39
+
40
+
41
+ class AddressParser:
42
+ """Parses raw Indian address strings into 13 structured fields.
43
+
44
+ Example:
45
+ >>> parser = AddressParser()
46
+ >>> parser.parse("FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029")
47
+ {'houseNumber': 'FLAT NO.32', 'houseName': 'UTTARA TOWERS', 'poi': None, ...}
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ adapter_repo: str = DEFAULT_ADAPTER_REPO,
53
+ base_model: str = DEFAULT_BASE_MODEL,
54
+ device: str | None = None,
55
+ max_new_tokens: int = 256,
56
+ ):
57
+ import torch
58
+ from peft import PeftModel
59
+ from transformers import AutoModelForCausalLM, AutoTokenizer
60
+
61
+ self.max_new_tokens = max_new_tokens
62
+ self.tokenizer = AutoTokenizer.from_pretrained(adapter_repo)
63
+
64
+ dtype = torch.float32
65
+ if device is None:
66
+ if torch.cuda.is_available():
67
+ device = "cuda"
68
+ dtype = torch.bfloat16
69
+ elif torch.backends.mps.is_available():
70
+ device = "mps"
71
+ dtype = torch.float16
72
+ else:
73
+ device = "cpu"
74
+
75
+ base = AutoModelForCausalLM.from_pretrained(base_model, torch_dtype=dtype)
76
+ self.model = PeftModel.from_pretrained(base, adapter_repo)
77
+ self.model.to(device)
78
+ self.model.eval()
79
+ self.device = device
80
+
81
+ def parse(self, raw_address: str) -> dict:
82
+ """Parse a single raw address string. Returns a dict with all 13 ALL_FIELDS
83
+ keys (null for fields not present). On generation output that isn't valid
84
+ JSON, all fields are null and `_parse_error` holds the raw model output."""
85
+ import torch
86
+
87
+ messages = [
88
+ {"role": "system", "content": SYSTEM_PROMPT},
89
+ {"role": "user", "content": USER_TEMPLATE.format(raw_address=raw_address)},
90
+ ]
91
+ try:
92
+ text = self.tokenizer.apply_chat_template(
93
+ messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
94
+ )
95
+ except TypeError:
96
+ text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
97
+
98
+ inputs = self.tokenizer(text, return_tensors="pt").to(self.device)
99
+ with torch.no_grad():
100
+ out = self.model.generate(
101
+ **inputs,
102
+ max_new_tokens=self.max_new_tokens,
103
+ do_sample=False,
104
+ pad_token_id=self.tokenizer.eos_token_id,
105
+ )
106
+ generated = self.tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
107
+
108
+ try:
109
+ result = json.loads(generated.strip())
110
+ result = {f: result.get(f) for f in ALL_FIELDS}
111
+ except json.JSONDecodeError:
112
+ result = {f: None for f in ALL_FIELDS}
113
+ result["_parse_error"] = generated.strip()
114
+ return result
115
+
116
+ def parse_batch(self, addresses: list[str]) -> list[dict]:
117
+ """Parse multiple addresses sequentially. See `parse` for the per-item shape."""
118
+ return [self.parse(addr) for addr in addresses]
@@ -0,0 +1,45 @@
1
+ """Tests for indian_address_parser.
2
+
3
+ test_import_and_constants runs offline. test_parse_real_address actually downloads
4
+ the model from HF Hub and runs real inference — slow (~1-2 min) and requires network,
5
+ but is the only way to verify the package genuinely works end to end.
6
+ """
7
+ import json
8
+
9
+ import pytest
10
+
11
+
12
+ def test_import_and_constants():
13
+ from indian_address_parser import ALL_FIELDS, DEFAULT_ADAPTER_REPO, DEFAULT_BASE_MODEL, SYSTEM_PROMPT
14
+
15
+ assert len(ALL_FIELDS) == 13
16
+ assert "pincode" in ALL_FIELDS
17
+ assert DEFAULT_ADAPTER_REPO == "gagan1985/qwen3-0.6b-indian-address-parser"
18
+ assert DEFAULT_BASE_MODEL == "Qwen/Qwen3-0.6B"
19
+ assert "Fields:" in SYSTEM_PROMPT
20
+
21
+
22
+ @pytest.mark.slow
23
+ def test_parse_real_address():
24
+ from indian_address_parser import AddressParser
25
+
26
+ parser = AddressParser()
27
+ result = parser.parse("FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029")
28
+
29
+ assert result["houseNumber"] == "FLAT NO.32"
30
+ assert result["houseName"] == "UTTARA TOWERS"
31
+ assert result["pincode"] == "781029"
32
+ assert "_parse_error" not in result
33
+
34
+
35
+ @pytest.mark.slow
36
+ def test_parse_batch():
37
+ from indian_address_parser import AddressParser
38
+
39
+ parser = AddressParser()
40
+ results = parser.parse_batch([
41
+ "FLAT NO.32, UTTARA TOWERS, MG ROAD GUWAHATI , Kamrup Unclassified AS 781029",
42
+ "SHOP NO 5, GANDHI MARKET, NEAR CIVIL HOSPITAL, SILCHAR , Cachar Unclassified AS 788001",
43
+ ])
44
+ assert len(results) == 2
45
+ assert all(json.dumps(r) for r in results) # each is JSON-serializable