-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
jlcparts_db_convert.py
489 lines (403 loc) · 15.1 KB
/
jlcparts_db_convert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/bin/env python3
"""Use the amazing work of https://github.com/yaqwsx/jlcparts and convert their database into something we can conveniently use for this plugin.
This replaces the old .csv based database creation that JLCPCB no longer supports.
Before this script can run, the cache.sqlite3 file has to be
present in db_build folder. Download and reassemble it like
jlcparts does it in their build pipeline:
https://github.com/yaqwsx/jlcparts/blob/1a07e1ff42fef2d35419cfb9ba47df090037cc7b/.github/workflows/update_components.yaml#L45-L50
by @markusdd
"""
from datetime import date, datetime
import json
import os
from pathlib import Path
import sqlite3
import zipfile
from zipfile import ZipFile
import humanize
class Generate:
"""Base class for database generation."""
def __init__(self, output_db: Path, chunk_num: Path):
self.output_db = output_db
self.jlcparts_db_name = "cache.sqlite3"
self.compressed_output_db = f"{self.output_db}.zip"
self.chunk_num = chunk_num
def remove_original(self):
"""Remove the original output database."""
if self.output_db.exists():
self.output_db.unlink()
def connect_sqlite(self):
"""Connect to the sqlite databases."""
# connection to the jlcparts db
db_uri = f"file:{self.jlcparts_db_name}?mode=rw"
self.conn_jp = sqlite3.connect(db_uri, uri=True)
# connection to the plugin db we want to write
self.conn = sqlite3.connect(self.output_db)
def load_tables(self):
"""Load the input data into the output database."""
# load the tables into memory
print("Reading manufacturers")
res = self.conn_jp.execute("SELECT * FROM manufacturers")
mans = dict(res.fetchall())
print("Reading categories")
res = self.conn_jp.execute("SELECT * FROM categories")
cats = {i: (c, sc) for i, c, sc in res.fetchall()}
res = self.conn_jp.execute("select count(*) from components")
results = res.fetchone()
print(f"{humanize.intcomma(results[0])} parts to import")
self.part_count = 0
print("Reading components")
res = self.conn_jp.execute("SELECT * FROM components")
while True:
comps = res.fetchmany(size=100000)
print(f"Read {humanize.intcomma(len(comps))} parts")
# if we have no more parts exit out of the loop
if len(comps) == 0:
break
self.part_count += len(comps)
# now extract the data from the jlcparts db and fill
# it into the plugin database
print("Building parts rows to insert")
rows = []
for c in comps:
price = json.loads(c[10])
price_str = ",".join(
[
f"{entry.get('qFrom')}-{entry.get('qTo') if entry.get('qTo') is not None else ''}:{entry.get('price')}"
for entry in price
]
)
row = (
f"C{c[0]}", # LCSC Part
cats[c[1]][0], # First Category
cats[c[1]][1], # Second Category
c[2], # MFR.Part
c[3], # Package
int(c[4]), # Solder Joint
mans[c[5]], # Manufacturer
"Basic" if c[6] else "Extended", # Library Type
c[7], # Description
c[8], # Datasheet
price_str, # Price
str(c[9]), # Stock
)
rows.append(row)
print("Inserting into parts table")
self.conn.executemany(
"INSERT INTO parts VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", rows
)
self.conn.commit()
print("Done importing parts")
def meta_data(self):
"""Populate the metadata table."""
# metadata
db_size = os.stat(self.output_db).st_size
self.conn.execute(
"INSERT INTO meta VALUES(?, ?, ?, ?, ?)",
[
"cache.sqlite3",
db_size,
self.part_count,
date.today(),
datetime.now().isoformat(),
],
)
self.conn.commit()
def close_sqlite(self):
"""Close sqlite connections."""
self.conn_jp.close()
self.conn.close()
def compress(self):
"""Compress the output database into a new compressed file."""
print(f"Compressing {self.output_db}")
with ZipFile(self.compressed_output_db, "w", zipfile.ZIP_DEFLATED) as zf:
zf.write(self.output_db)
def split(self):
"""Split the compressed so we stay below githubs 100M limit."""
# Set the size of each split file (in bytes)
split_size = 80000000 # 80 MB
# Open the zip file for byte-reading
print(f"Chunking {self.compressed_output_db}")
with open(self.compressed_output_db, "rb") as z:
# Read the file data in chunks
chunk = z.read(split_size)
chunk_num = 1
while chunk:
split_file_name = f"{self.compressed_output_db}.{chunk_num:03}"
with open(split_file_name, "wb") as split_file:
# Write the chunk to the new split file
split_file.write(chunk)
# Read the next chunk of data from the file
chunk = z.read(split_size)
chunk_num += 1
# create a helper file for the downloader which indicates the number of chunk files
with open(self.chunk_num, "w", encoding="utf-8") as f:
f.write(str(chunk_num - 1))
def display_stats(self):
"""Print out some stats."""
jlcparts_db_size = humanize.naturalsize(os.path.getsize(self.jlcparts_db_name))
print(f"jlcparts database ({self.jlcparts_db_name}): {jlcparts_db_size}")
print(
f"output db: {humanize.naturalsize(os.path.getsize(self.output_db.name))}"
)
print(
f"output db (compressed): {humanize.naturalsize(os.path.getsize(self.compressed_output_db))}"
)
def cleanup(self):
"""Remove the compressed zip file und output db after splitting."""
print(f"Deleting {self.compressed_output_db}")
os.unlink(self.compressed_output_db)
print(f"Deleting {self.output_db}")
os.unlink(self.output_db)
class Jlcpcb(Generate):
"""Sqlite parts database generator."""
def __init__(self, output_db: Path):
chunk_num = Path("chunk_num.txt")
super().__init__(output_db, chunk_num)
def create_tables(self):
"""Create the tables in the output database."""
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS parts (
'LCSC Part',
'First Category',
'Second Category',
'MFR.Part',
'Package',
'Solder Joint',
'Manufacturer',
'Library Type',
'Description',
'Datasheet',
'Price',
'Stock'
)
"""
)
self.conn.execute(
"""
CREATE UNIQUE INDEX parts_lcsc_part_index
ON parts ('LCSC Part')
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS mapping (
'footprint',
'value',
'LCSC'
)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS meta (
'filename',
'size',
'partcount',
'date',
'last_update'
)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS rotation (
'regex',
'correction'
)
"""
)
def build(self):
"""Run all of the steps to generate the database files for upload."""
self.remove_original()
self.connect_sqlite()
self.create_tables()
self.load_tables()
self.meta_data()
self.close_sqlite()
self.compress()
self.split()
self.display_stats()
self.cleanup()
class JlcpcbFTS5(Generate):
"""FTS5 specific database generation."""
def __init__(self, output_db: Path):
chunk_num = Path("chunk_num_fts5.txt")
super().__init__(output_db, chunk_num)
def create_tables(self):
"""Create tables."""
self.conn.execute(
"""
CREATE virtual TABLE IF NOT EXISTS parts using fts5 (
'LCSC Part',
'First Category',
'Second Category',
'MFR.Part',
'Package',
'Solder Joint' unindexed,
'Manufacturer',
'Library Type',
'Description',
'Datasheet',
'Price' unindexed,
'Stock' unindexed
, tokenize="trigram")
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS mapping (
'footprint',
'value',
'LCSC'
)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS meta (
'filename',
'size',
'partcount',
'date',
'last_update'
)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS rotation (
'regex',
'correction'
)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS categories (
'First Category',
'Second Category'
)
"""
)
def load_tables(self):
"""Load the input data into the output database."""
# load the tables into memory
print("Reading manufacturers")
res = self.conn_jp.execute("SELECT * FROM manufacturers")
mans = dict(res.fetchall())
print("Reading categories")
res = self.conn_jp.execute("SELECT * FROM categories")
cats = {i: (c, sc) for i, c, sc in res.fetchall()}
res = self.conn_jp.execute("select count(*) from components")
results = res.fetchone()
print(f"{humanize.intcomma(results[0])} parts to import")
self.part_count = 0
print("Reading components")
res = self.conn_jp.execute("SELECT * FROM components")
while True:
comps = res.fetchmany(size=100000)
print(f"Read {humanize.intcomma(len(comps))} parts")
# if we have no more parts exit out of the loop
if len(comps) == 0:
break
self.part_count += len(comps)
# now extract the data from the jlcparts db and fill
# it into the plugin database
print("Building parts rows to insert")
rows = []
for c in comps:
price = json.loads(c[10])
price_str = ",".join(
[
f"{entry.get('qFrom')}-{entry.get('qTo') if entry.get('qTo') is not None else ''}:{entry.get('price')}"
for entry in price
]
)
description = c[7]
# strip ROHS out of descriptions where present
# and add 'not ROHS' where ROHS is not present
# as 99% of parts are ROHS at this point
if " ROHS".lower() not in description.lower():
description += " not ROHS"
else:
description = description.replace(" ROHS", "")
second_category = cats[c[1]][1]
# strip the 'Second category' out of the description if it
# is duplicated there
description = description.replace(second_category, "")
package = c[3]
# remove 'Package' from the description if it is duplicated there
description = description.replace(package, "")
# replace double spaces with single spaces in description
description.replace(" ", " ")
# remove trailing spaces from description
description = description.strip()
row = (
f"C{c[0]}", # LCSC Part
cats[c[1]][0], # First Category
cats[c[1]][1], # Second Category
c[2], # MFR.Part
package, # Package
int(c[4]), # Solder Joint
mans[c[5]], # Manufacturer
"Basic" if c[6] else "Extended", # Library Type
description, # Description
c[8], # Datasheet
price_str, # Price
str(c[9]), # Stock
)
rows.append(row)
print("Inserting into parts table")
self.conn.executemany(
"INSERT INTO parts VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", rows
)
self.conn.commit()
print("Done importing parts")
def populate_categories(self):
"""Populate the categories table."""
self.conn.execute(
'INSERT INTO categories SELECT DISTINCT "First Category", "Second Category" FROM parts ORDER BY UPPER("First Category"), UPPER("Second Category")'
)
def optimize(self):
"""FTS5 optimize to minimize query times."""
print("Optimizing fts5 parts table")
self.conn.execute("insert into parts(parts) values('optimize')")
print("Done optimizing fts5 parts table")
def build(self):
"""Run all of the steps to generate the database files for upload."""
self.remove_original()
self.connect_sqlite()
self.create_tables()
self.load_tables()
self.populate_categories()
self.optimize()
self.meta_data()
self.close_sqlite()
self.compress()
self.split()
self.display_stats()
self.cleanup()
output_directory = "db_build"
os.chdir(output_directory)
# sqlite database
start = datetime.now()
output_name = "parts.db"
partsdb = Path(output_name)
print(f"Generating {output_name} in {output_directory} directory")
generator = Jlcpcb(partsdb)
generator.build()
end = datetime.now()
deltatime = end - start
print(f"Elapsed time: {humanize.precisedelta(deltatime, minimum_unit='seconds')}")
# sqlite fts5 database
start = datetime.now()
output_name = "parts-fts5.db"
partsdb = Path(output_name)
print(f"Generating {output_name} in {output_directory} directory")
generator = JlcpcbFTS5(partsdb)
generator.build()
end = datetime.now()
deltatime = end - start
print(f"Elapsed time: {humanize.precisedelta(deltatime, minimum_unit='seconds')}")