2adif 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.

Potentially problematic release.


This version of 2adif might be problematic. Click here for more details.

@@ -0,0 +1,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.2
2
+ Name: 2adif
3
+ Version: 0.1.0
4
+ Summary: Convert table to ADIF format.
5
+ Author: uiolee
6
+ Maintainer: uiolee
7
+ License: MPL 2.0
8
+ Project-URL: Homepage, https://github.com/uiolee/2adif
9
+ Project-URL: Repository, https://github.com/uiolee/2adif.git
10
+ Project-URL: Issues, https://github.com/uiolee/2adif/issues
11
+ Keywords: ADIF,csv,hamradio
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: End Users/Desktop
16
+ Classifier: Topic :: File Formats
17
+ Classifier: Topic :: Utilities
18
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
19
+ Classifier: Natural Language :: English
20
+ Classifier: Operating System :: Microsoft :: Windows
21
+ Classifier: Operating System :: POSIX :: Linux
22
+ Classifier: Operating System :: MacOS
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: Scrapy
27
+
28
+ # 2adif
29
+
30
+ [![CI](https://github.com/uiolee/2adif/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/uiolee/2adif/actions/workflows/ci.yml)
31
+ [![Publish](https://github.com/uiolee/2adif/actions/workflows/publish.yml/badge.svg)](https://github.com/uiolee/2adif/actions/workflows/publish.yml)
32
+
33
+ Convert tables to [ADIF](https://adif.org/) format.
34
+
35
+ ## Feat
36
+
37
+ - [x] convert `csv` to `adi` format.
38
+ - [ ] convert `xlsx` to `adi` format.
39
+ - [ ] convert `ods` to `adi` format.
40
+
41
+ ## Usage
42
+
43
+ [![PyPI - Version](https://img.shields.io/pypi/v/2adif)](https://pypi.org/p/2adif/#history)
44
+ [![PyPI - Status](https://img.shields.io/pypi/status/2adif)](https://pypi.org/p/2adif)
45
+ [![PyPI - Implementation](https://img.shields.io/pypi/implementation/2adif)](https://pypi.org/p/2adif)
46
+ [![PyPI - Format](https://img.shields.io/pypi/format/2adif)](https://pypi.org/p/2adif/#files)
47
+ [![PyPI - Wheel](https://img.shields.io/pypi/wheel/2adif)](https://pypi.org/p/2adif/#files)
48
+ [![PyPI - License](https://img.shields.io/pypi/l/2adif)](./LICENSE)
49
+ [![PyPI - Downloads](https://img.shields.io/pypi/dm/2adif)](https://pypi.org/p/2adif)
50
+
51
+ ### pipx
52
+
53
+ #### Install
54
+
55
+ ```bash
56
+ pipx install 2adif
57
+ ```
58
+
59
+ #### convert `csv` to `adi`
60
+
61
+ - Convert the specified `csv` file
62
+
63
+ ```bash
64
+ 2adif ./test/test.csv
65
+ ```
66
+
67
+ - Convert all csv files in the specified directory
68
+
69
+ ```bash
70
+ 2adif ./test/
71
+ ```
72
+
73
+ ### source
74
+
75
+ <details>
76
+ <summary>source</summary>
77
+
78
+ #### Python
79
+
80
+ see [./src/main.py](./src/main.py#L140) for more.
81
+
82
+ </details>
83
+
84
+ ## Develop Env
85
+
86
+ ```plain
87
+ Python 3.11.9
88
+ ```
@@ -0,0 +1,12 @@
1
+ cli.py,sha256=7lvWPXbIykSF5AKf5l_gLnrUnm84bThTKiANEW0bTAw,1119
2
+ db.py,sha256=iaYuK43z1CIVu-JZILSfmw5pY5oBVvBg6lQuX4a2N1Y,2879
3
+ fields.py,sha256=4NAKWVMRksVf4Js1BkWMD9q-ZjsvPfPhPrwIklDY_co,3449
4
+ info.py,sha256=-InFxCd6cXmK79i4s-7jywFYEfkE-Zz6rLVrDkO4-w8,375
5
+ main.py,sha256=PodWZhuwo8CcAzzDaomxMRpROYXG--ry3o5WujWE7Tw,4790
6
+ time_helper.py,sha256=XqFfPsSfsffDNlSL8uVgWAhq3REbI1QZLnNCtzORfe8,1063
7
+ 2adif-0.1.0.dist-info/LICENSE,sha256=HyVuytGSiAUQ6ErWBHTqt1iSGHhLmlC8fO7jTCuR8dU,16725
8
+ 2adif-0.1.0.dist-info/METADATA,sha256=DPogH_KInU2bM3ilK-331WyGm2b5ThIFdJeWXfOe2pk,2499
9
+ 2adif-0.1.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
10
+ 2adif-0.1.0.dist-info/entry_points.txt,sha256=FjYEL0SxQvhCtVVw-EdUfptTqj6w1kYw2Cmby7YvOIs,34
11
+ 2adif-0.1.0.dist-info/top_level.txt,sha256=Q2kUllfDvBcCYXpvN0M-UTiuocpwGCEKBJWAEv-Go-Y,36
12
+ 2adif-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ 2adif = cli:cli
@@ -0,0 +1,6 @@
1
+ cli
2
+ db
3
+ fields
4
+ info
5
+ main
6
+ time_helper
cli.py ADDED
@@ -0,0 +1,54 @@
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ from main import TO_ADIF
5
+
6
+
7
+ def _do(path: Path):
8
+ to_adif = TO_ADIF(path)
9
+ # to_adif.get_adif_str()
10
+ to_adif.to_adif(path.with_suffix(path.suffix + ".adi"))
11
+
12
+
13
+ class Args(argparse.Namespace):
14
+ path: list[Path]
15
+
16
+
17
+ def cli():
18
+ parser = argparse.ArgumentParser(prog="2adif")
19
+
20
+ parser.add_argument(
21
+ "path",
22
+ nargs="+",
23
+ type=Path,
24
+ help="the .csv file(s) that you want to convert to .adi",
25
+ )
26
+
27
+ args: Args = parser.parse_args(namespace=Args())
28
+
29
+ print()
30
+ print("====== 2adif cli ======")
31
+ print(args)
32
+
33
+ paths: list[Path] = []
34
+ EXT = ".csv"
35
+ for path in args.path:
36
+ if path.suffix == EXT:
37
+ paths.append(path)
38
+ elif path.is_dir():
39
+ for child_path in path.iterdir():
40
+ if child_path.suffix == EXT:
41
+ paths.append(child_path)
42
+
43
+ for path in paths:
44
+ print()
45
+ print("[cli.py]", "processing:", path)
46
+ _do(path)
47
+
48
+ print()
49
+ print("[cli.py]", "processed files:", len(paths))
50
+
51
+
52
+ if __name__ == "__main__":
53
+ cli()
54
+ print()
db.py ADDED
@@ -0,0 +1,105 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Union
3
+
4
+ from scrapy import Field as sField
5
+ from scrapy import Item as sItem
6
+
7
+
8
+ class Item(sItem):
9
+ name = sField()
10
+ value = sField()
11
+ length = sField()
12
+ type = sField()
13
+
14
+ def __setitem__(self, key, value):
15
+ if key == "name":
16
+ value = value.upper()
17
+ elif key == "value":
18
+ value = value.strip("").strip(" ")
19
+ super(Item, self).__setitem__("length", len(value))
20
+
21
+ super(Item, self).__setitem__(key, value)
22
+
23
+ def __getitem__(self, key):
24
+ if key == "length":
25
+ # value = len(self["value"])
26
+ value = super(Item, self).__getitem__("value")
27
+ super(Item, self).__setitem__("length", value)
28
+ return super(Item, self).__getitem__(key)
29
+
30
+
31
+ @dataclass
32
+ class ItemContainer:
33
+ data: list[Item] = field(default_factory=list)
34
+ length: int = 0
35
+ fields: list[str] = field(default_factory=list)
36
+
37
+ def __init__(self):
38
+ self.data = []
39
+ self.fields = []
40
+ pass
41
+
42
+ def __iter__(self):
43
+ data = sorted(self.data, key=lambda x: x["name"])
44
+ for item in data:
45
+ yield item
46
+
47
+ def contains(self, obj: Union[str, Item]) -> bool:
48
+ data = self.data
49
+ if isinstance(obj, Item):
50
+ key = obj["name"]
51
+ else:
52
+ key = obj
53
+ for d in data:
54
+ if d["name"].upper() == key.upper():
55
+ return True
56
+ return False
57
+
58
+ def get(self, obj: Union[str, Item]):
59
+ if not self.contains(obj):
60
+ raise Exception("doesn't exists!")
61
+ else:
62
+ data = self.data
63
+ if isinstance(obj, Item):
64
+ key = obj["name"]
65
+ else:
66
+ key = obj
67
+ for d in data:
68
+ if d["name"].upper() == key.upper():
69
+ return d
70
+ return None
71
+
72
+ def _addField(self, obj: Item):
73
+ name = obj["name"]
74
+ if name not in (fields := self.fields):
75
+ fields.append(name)
76
+
77
+ def add(self, obj: Item):
78
+ if not self.contains(obj):
79
+ self.data.append(obj)
80
+ self._addField(obj)
81
+ self.length = len(self.data)
82
+ else:
83
+ print(f"{obj['name']} have existed!")
84
+
85
+ def append(self, obj: Item):
86
+ if not self.contains(obj):
87
+ self.data.append(obj)
88
+ self._addField(obj)
89
+ self.length = len(self.data)
90
+
91
+ else:
92
+ if d := self.get(obj):
93
+ d["value"] += obj["value"]
94
+
95
+ def setDefault(self):
96
+ items = [
97
+ Item(name="RST_RCVD", value=""),
98
+ Item(name="RST_SENT", value=""),
99
+ ]
100
+ for item in items:
101
+ self.add(item)
102
+
103
+ def stripValue(self, char: str = "\n"):
104
+ for item in self.__iter__():
105
+ item["value"] = item["value"].strip(char)
fields.py ADDED
@@ -0,0 +1,193 @@
1
+ HEADER_FIELDS_NAME = [
2
+ "ADIF_VER",
3
+ "CREATED_TIMESTAMP",
4
+ "PROGRAMID",
5
+ "PROGRAMVERSION",
6
+ # "USERDEFn", # fixme!n is a variable
7
+ ]
8
+
9
+ QSOS_FIELDS_NAME = [
10
+ "ADDRESS",
11
+ "AGE",
12
+ "ALTITUDE",
13
+ "ANT_AZ",
14
+ "ANT_EL",
15
+ "ANT_PATH",
16
+ "ARRL_SECT",
17
+ "AWARD_SUBMITTED",
18
+ "AWARD_GRANTED",
19
+ "A_INDEX",
20
+ "BAND",
21
+ "BAND_RX",
22
+ "CALL",
23
+ "CHECK",
24
+ "CLASS",
25
+ "CLUBLOG_QSO_UPLOAD_DATE",
26
+ "CLUBLOG_QSO_UPLOAD_STATUS",
27
+ "CNTY",
28
+ "CNTY_ALT",
29
+ "COMMENT",
30
+ "CONT",
31
+ "CONTACTED_OP",
32
+ "CONTEST_ID",
33
+ "COUNTRY",
34
+ "CQZ",
35
+ "CREDIT_SUBMITTED",
36
+ "CREDIT_GRANTED",
37
+ "DARC_DOK",
38
+ "DCL_QSLRDATE",
39
+ "DCL_QSLSDATE",
40
+ "DCL_QSL_RCVD",
41
+ "DCL_QSL_SENT",
42
+ "DISTANCE",
43
+ "DXCC",
44
+ "EMAIL",
45
+ "EQ_CALL",
46
+ "EQSL_QSLRDATE",
47
+ "EQSL_QSLSDATE",
48
+ "EQSL_QSL_RCVD",
49
+ "EQSL_QSL_SENT",
50
+ "FISTS",
51
+ "FISTS_CC",
52
+ "FORCE_INIT",
53
+ "FREQ",
54
+ "FREQ_RX",
55
+ "GRIDSQUARE",
56
+ "GRIDSQUARE_EXT",
57
+ "GUEST_OP",
58
+ "HAMLOGEU_QSO_UPLOAD_DATE",
59
+ "HAMLOGEU_QSO_UPLOAD_STATUS",
60
+ "HAMQTH_QSO_UPLOAD_DATE",
61
+ "HAMQTH_QSO_UPLOAD_STATUS",
62
+ "HRDLOG_QSO_UPLOAD_DATE",
63
+ "HRDLOG_QSO_UPLOAD_STATUS",
64
+ "IOTA",
65
+ "IOTA_ISLAND_ID",
66
+ "ITUZ",
67
+ "K_INDEX",
68
+ "LAT",
69
+ "LON",
70
+ "LOTW_QSLRDATE",
71
+ "LOTW_QSLSDATE",
72
+ "LOTW_QSL_RCVD",
73
+ "LOTW_QSL_SENT",
74
+ "MAX_BURSTS",
75
+ "MODE",
76
+ "MORSE_KEY_INFO",
77
+ "MORSE_KEY_TYPE",
78
+ "MS_SHOWER",
79
+ "MY_ALTITUDE",
80
+ "MY_ANTENNA",
81
+ "MY_ARRL_SECT",
82
+ "MY_CITY",
83
+ "MY_CNTY",
84
+ "MY_CNTY_ALT",
85
+ "MY_COUNTRY",
86
+ "MY_CQ_ZONE",
87
+ "MY_DARC_DOK",
88
+ "MY_DXCC",
89
+ "MY_FISTS",
90
+ "MY_GRIDSQUARE",
91
+ "MY_GRIDSQUARE_EXT",
92
+ "MY_IOTA",
93
+ "MY_IOTA_ISLAND_ID",
94
+ "MY_ITU_ZONE",
95
+ "MY_LAT",
96
+ "MY_LON",
97
+ "MY_MORSE_KEY_INFO",
98
+ "MY_MORSE_KEY_TYPE",
99
+ "MY_NAME",
100
+ "MY_POSTAL_CODE",
101
+ "MY_POTA_REF",
102
+ "MY_RIG",
103
+ "MY_SIG",
104
+ "MY_SIG_INFO",
105
+ "MY_SOTA_REF",
106
+ "MY_STATE",
107
+ "MY_STREET",
108
+ "MY_USACA_COUNTIES",
109
+ "MY_VUCC_GRIDS",
110
+ "MY_WWFF_REF",
111
+ "NAME",
112
+ "NOTES",
113
+ "NR_BURSTS",
114
+ "NR_PINGS",
115
+ "OPERATOR",
116
+ "OWNER_CALLSIGN",
117
+ "PFX",
118
+ "POTA_REF",
119
+ "PRECEDENCE",
120
+ "PROP_MODE",
121
+ "PUBLIC_KEY",
122
+ "QRZCOM_QSO_DOWNLOAD_DATE",
123
+ "QRZCOM_QSO_DOWNLOAD_STATUS",
124
+ "QRZCOM_QSO_UPLOAD_DATE",
125
+ "QRZCOM_QSO_UPLOAD_STATUS",
126
+ "QSLMSG",
127
+ "QSLMSG_RCVD",
128
+ "QSLRDATE",
129
+ "QSLSDATE",
130
+ "QSL_RCVD",
131
+ "QSL_RCVD_VIA",
132
+ "QSL_SENT",
133
+ "QSL_SENT_VIA",
134
+ "QSL_VIA",
135
+ "QSO_COMPLETE",
136
+ "QSO_DATE",
137
+ "QSO_DATE_OFF",
138
+ "QSO_RANDOM",
139
+ "QTH",
140
+ "REGION",
141
+ "RIG",
142
+ "RST_RCVD",
143
+ "RST_SENT",
144
+ "RX_PWR",
145
+ "SAT_MODE",
146
+ "SAT_NAME",
147
+ "SFI",
148
+ "SIG",
149
+ "SIG_INFO",
150
+ "SILENT_KEY",
151
+ "SKCC",
152
+ "SOTA_REF",
153
+ "SRX",
154
+ "SRX_STRING",
155
+ "STATE",
156
+ "STATION_CALLSIGN",
157
+ "STX",
158
+ "STX_STRING",
159
+ "SUBMODE",
160
+ "SWL",
161
+ "TEN_TEN",
162
+ "TIME_OFF",
163
+ "TIME_ON",
164
+ "TX_PWR",
165
+ "UKSMG",
166
+ "USACA_COUNTIES",
167
+ "VE_PROV",
168
+ "VUCC_GRIDS",
169
+ "WEB",
170
+ "WWFF_REF",
171
+ ]
172
+
173
+ QSOS_FIELDS_NAME_INTL = [
174
+ "ADDRESS_INTL",
175
+ "COMMENT_INTL",
176
+ "COUNTRY_INTL",
177
+ "MY_ANTENNA_INTL",
178
+ "MY_CITY_INTL",
179
+ "MY_COUNTRY_INTL",
180
+ "MY_NAME_INTL",
181
+ "MY_POSTAL_CODE_INTL",
182
+ "MY_RIG_INTL",
183
+ "MY_SIG_INTL",
184
+ "MY_SIG_INFO_INTL",
185
+ "MY_STREET_INTL",
186
+ "NAME_INTL",
187
+ "NOTES_INTL",
188
+ "QSLMSG_INTL",
189
+ "QTH_INTL",
190
+ "RIG_INTL",
191
+ "SIG_INTL",
192
+ "SIG_INFO_INTL",
193
+ ]
info.py ADDED
@@ -0,0 +1,18 @@
1
+ def _i():
2
+ def _k():
3
+ return {
4
+ "name": "2adif",
5
+ "version": "0.1.0",
6
+ "description": "Converts CSV to ADIF",
7
+ "author": "uiolee",
8
+ "ADIF_VER": "3.1.5",
9
+ "PROGRAMID": "uiolee-2adif",
10
+ "PROGRAMVERSION": "0.1.0",
11
+ }
12
+
13
+ i = _k()
14
+
15
+ def _r(_k):
16
+ return i[_k]
17
+
18
+ return _r
main.py ADDED
@@ -0,0 +1,143 @@
1
+ import csv
2
+ from pathlib import Path
3
+
4
+ from db import Item, ItemContainer
5
+ from fields import HEADER_FIELDS_NAME, QSOS_FIELDS_NAME
6
+ from info import _i
7
+ from time_helper import convert_to_hhmmss, convert_to_yyyymmdd, get_ymdhms
8
+
9
+
10
+ class TO_ADIF:
11
+ def __init__(
12
+ self,
13
+ filepath: str | Path = "",
14
+ ) -> None:
15
+ if filepath:
16
+ self.read(filepath)
17
+ self.qsos: list[ItemContainer] = []
18
+ self.adif_str = ""
19
+
20
+ def __len__(self):
21
+ return len(self.qsos)
22
+
23
+ def __iter__(self):
24
+ qsos = self.qsos
25
+ # qsos = sorted(self.qsos, key=lambda x: x.get("QSO_DATE")["value"])
26
+ for qso in qsos:
27
+ yield qso
28
+
29
+ def _get_input(self, filepath, encoding: str = "utf-8-sig") -> list[dict]:
30
+ def csv_to_dicts(file) -> list[dict]:
31
+ res = []
32
+ with open(file, "r", encoding=encoding) as fp:
33
+ res = list(csv.DictReader(fp))
34
+ return res
35
+
36
+ return csv_to_dicts(filepath)
37
+
38
+ def read(self, filepath: str | Path, encoding: str = "utf-8-sig"):
39
+ self.data = self._get_input(filepath)
40
+ print(f"input: {len(self.data)}")
41
+
42
+ def _iteritems(self, row: dict):
43
+ for name, value in self._process_item(row.items()):
44
+ if value:
45
+ if name.upper() in QSOS_FIELDS_NAME and (
46
+ name.upper() not in ["CONTACTED_OP", "RX_PWR", "ALTITUDE"]
47
+ ):
48
+ yield [
49
+ Item(name=name, value=value),
50
+ ]
51
+ elif name.upper() in ["CONTACTED_OP", "RX_PWR", "ALTITUDE"]:
52
+ # Standard filed name but contains non-standard values
53
+ yield [
54
+ Item(name=name, value=value),
55
+ Item(name="notes", value=f"{name}: {value}\n"),
56
+ ]
57
+ elif name.upper() not in ["YYYY", "MM", "DD", "HH", "SS"]:
58
+ yield [
59
+ Item(name="notes", value=f"{name}: {value}\n"),
60
+ ]
61
+
62
+ def _iterrows(self):
63
+ for index, row in enumerate(self.data):
64
+ qso = ItemContainer()
65
+ print(f"iter row {index}")
66
+ for items in self._iteritems(row):
67
+ for item in items:
68
+ qso.append(item)
69
+ yield qso
70
+
71
+ @staticmethod
72
+ def _gen_item(item: Item):
73
+ k = item["name"]
74
+ v = item["value"]
75
+ return f"<{k.upper()}:{len(v)}>{v}"
76
+
77
+ @staticmethod
78
+ def _process_item(item):
79
+ for name, value in item:
80
+ if name.lower().endswith("date") or name.lower().endswith("date_off"):
81
+ ymd = convert_to_yyyymmdd(value)
82
+ yield name, ymd
83
+ elif name.lower().startswith("time_"):
84
+ hms = convert_to_hhmmss(value)
85
+ yield name, hms
86
+ else:
87
+ yield name, value
88
+
89
+ def _process(self):
90
+ qsos = self.qsos
91
+ for qso in self._iterrows():
92
+ qso.setDefault()
93
+ qso.stripValue()
94
+ qsos.append(qso)
95
+ print(f"processed: {len(self)}")
96
+
97
+ def _gen_adif_header(self):
98
+ _d = _i()
99
+ head_slist = ["# Exported By 2ADIF."]
100
+ header_item = [
101
+ Item(name="ADIF_VER", value=_d("ADIF_VER")),
102
+ Item(name="CREATED_TIMESTAMP", value=get_ymdhms()),
103
+ Item(name="PROGRAMID", value=_d("PROGRAMID")),
104
+ Item(name="PROGRAMVERSION", value=_d("PROGRAMVERSION")),
105
+ ]
106
+ for item in header_item:
107
+ head_slist.append((self._gen_item(item)))
108
+ head_slist.append("<EOH>")
109
+ head_slist.append("")
110
+ self.head_str = "\n".join(head_slist)
111
+ return head_slist
112
+
113
+ def get_adif_str(self):
114
+ self._process()
115
+ adif_slist = []
116
+ adif_slist.extend(self._gen_adif_header())
117
+ for qso in self:
118
+ qso_slist = []
119
+ for item in qso:
120
+ qso_slist.append(self._gen_item(item))
121
+ qso_slist.append("<EOR>")
122
+ qso_slist.append("")
123
+ adif_slist.extend(qso_slist)
124
+
125
+ self.adif_str = "\n".join(adif_slist)
126
+ return self.adif_str
127
+
128
+ def to_adif(self, filepath: str | Path, encoding="utf-8-sig"):
129
+ adif_str = self.get_adif_str()
130
+ file_ext = ".adi"
131
+ if isinstance(filepath, str):
132
+ filepath = Path(filepath)
133
+ if not filepath.suffix == file_ext:
134
+ filepath = filepath.with_name(filepath.stem + file_ext)
135
+ with open(filepath, "w", encoding=encoding) as fp:
136
+ fp.write(adif_str)
137
+ print(f"Write {len(adif_str)} to {filepath}")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ TEST_FILE = "./test/test.csv"
142
+ to_adif = TO_ADIF(TEST_FILE)
143
+ to_adif.to_adif(TEST_FILE + ".adi")
time_helper.py ADDED
@@ -0,0 +1,46 @@
1
+ from datetime import UTC, datetime
2
+
3
+
4
+ def convert_to_yyyymmdd(date_str: str) -> str:
5
+ date_formats = [
6
+ "%Y-%m-%d",
7
+ "%d/%m/%Y",
8
+ "%m-%d-%Y",
9
+ "%Y/%m/%d",
10
+ "%d %b %Y",
11
+ "%b %d, %Y",
12
+ ]
13
+ for fmt in date_formats:
14
+ try:
15
+ date_obj = datetime.strptime(date_str, fmt)
16
+ return date_obj.strftime("%Y%m%d")
17
+ except ValueError:
18
+ continue
19
+
20
+ return date_str
21
+
22
+
23
+ def convert_to_hhmmss(time_str: str) -> str:
24
+ time_formats = [
25
+ "%H:%M:%S",
26
+ "%H:%M:%S%:z",
27
+ "%I:%M:%S %p",
28
+ "%H:%M",
29
+ "%I:%M %p",
30
+ "%H%M%S",
31
+ ]
32
+
33
+ for fmt in time_formats:
34
+ try:
35
+ time_obj = datetime.strptime(time_str, fmt)
36
+ return time_obj.strftime("%H%M%S")
37
+ except ValueError:
38
+ continue
39
+
40
+ return time_str
41
+
42
+
43
+ def get_ymdhms() -> str:
44
+ cur = datetime.now(UTC)
45
+ datestr, timestr = cur.isoformat(timespec="seconds").split("T")
46
+ return " ".join([convert_to_yyyymmdd(datestr), convert_to_hhmmss(timestr[:8])])