-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDigikeyLabelGen.py
452 lines (427 loc) · 17.6 KB
/
DigikeyLabelGen.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
import argparse
import ast
import csv
from collections import namedtuple
import re
from labelannotator import *
# Simple annotator that adds a column whose value is the name of the specified
# parametrics field.
def RemapParametric(out_name, field_name):
def annotate_fn(row_dict):
parametrics_str = row_dict['parametrics']
if not parametrics_str:
return {}
paramterics = ast.literal_eval(parametrics_str)
return {out_name: paramterics[field_name]}
return annotate_fn
ParametricPreprocess = namedtuple('ParametricPreprocess', ['name', 'fn'])
"""
Return a function which takes a string (formatted as a list of sub-strings, with
the specified separator), and returns the truncated version, optionally with an
end part to indicate truncation.
"""
def list_truncate(num_elements, end="...", separator=', '):
def fn(in_string):
substrings = in_string.split(separator)
if len(substrings) > num_elements:
substrings = substrings[:num_elements]
if end:
substrings.append(end)
return separator.join(substrings)
return fn
"""
Returns a function that takes a string, looks up that string in a dict, and
returns the found value (or the input value, if no match and default is True).
Throws an exception if no match is found and default is False.
"""
def remap(remap_dict, default=True):
def fn(in_string):
if in_string in remap_dict:
return remap_dict[in_string]
else:
if default:
return in_string
else:
raise Exception("Failed to remap '%s' with dict %s" % (in_string, remap_dict))
return fn
"""
Returns a function that takes a string and tries to match it against the
specified regexes (in sequence). If a match is found, the capture groups are
interpolated into the output string associated with the regex.
If no match is found, returns the input (if default is True) or throws an
exception (if default is False).
"""
def regex_capture_map(regex_output_pair_list, default=True):
regex_output_pair_compiled_list = [(re.compile('^' + regex + '$'), output) for (regex, output) in regex_output_pair_list]
def fn(in_string):
for regex, output in regex_output_pair_compiled_list:
match = regex.match(in_string)
if match:
return output % match.groups()
if default:
return in_string
else:
raise Exception("Failed to remap '%s' with regex list %s" % (in_string, regex_output_pair_list))
return fn
QuickDescStruct = namedtuple('QuickDescStruct', ['preprocessors', 'title', 'quickdesc'])
quickdesc_rules = {
"Through Hole Resistors":
QuickDescStruct([ParametricPreprocess("Power (Watts)",
regex_capture_map([(".*(\d+/\d+W).*", "%s"),
], default=False)),
ParametricPreprocess("Resistance",
regex_capture_map([(".*(\d+\.?\d*) ([kM]?)Ohms.*", "%s %s\u03a9"),
], default=False)),
],
"Resistor, %(Resistance)s",
"%(Tolerance)s, %(Power (Watts))s"
),
"Ceramic Capacitors":
QuickDescStruct([],
"Capacitor, %(Capacitance)s",
"Ceramic, %(Voltage - Rated)s, %(Temperature Coefficient)s, %(Tolerance)s"
),
"Aluminum Electrolytic Capacitors":
QuickDescStruct([],
"Capacitor, %(Capacitance)s",
"Aluminum, %(Voltage - Rated)s, %(Tolerance)s"
),
### Electromechanical
"Slide Switches":
QuickDescStruct([],
"Slide switch",
"%(Current Rating)s, %(Voltage Rating - DC)s"
),
"Tactile Switches":
QuickDescStruct([],
"Tactile switch",
"%(Operating Force)s"
),
### Discrete Semiconductors
"Diodes - Rectifiers - Single":
QuickDescStruct([ParametricPreprocess("Voltage - Forward (Vf) (Max) @ If",
regex_capture_map([("(\d+.?\d*\w*V)\s*@.*", "%s"),
], default=False)),
],
"Diode, %(Voltage - DC Reverse (Vr) (Max))s %(Current - Average Rectified (Io))s",
"%(Diode Type)s, %(Voltage - Forward (Vf) (Max) @ If)s(f)"
),
"Diodes - Zener - Single":
QuickDescStruct([ParametricPreprocess("Voltage - Forward (Vf) (Max) @ If",
regex_capture_map([("(\d+.?\d*\w*V)\s*@.*", "%s"),
], default=False)),
],
"Zener, %(Voltage - Zener (Nom) (Vz))s",
"%(Voltage - Forward (Vf) (Max) @ If)s(f)"
),
"TVS - Diodes":
QuickDescStruct([],
"TVS Diode, %(Voltage - Reverse Standoff (Typ))s",
"%(Applications)s"
),
"Transistors - Bipolar (BJT) - Single":
QuickDescStruct([],
"BJT, %(Transistor Type)s",
"%(Voltage - Collector Emitter Breakdown (Max))s, %(Current - Collector (Ic) (Max))s",
),
"Transistors - FETs, MOSFETs - Single":
QuickDescStruct([ParametricPreprocess("FET Type", list_truncate(1, '')), # take first element of list
],
"MOSFET, %(FET Type)s",
u"%(Drain to Source Voltage (Vdss))s, %(Current - Continuous Drain (Id) @ 25\u00B0C)s",
),
### ICs, Power conversion
"PMIC - Voltage Regulators - Linear":
QuickDescStruct([ParametricPreprocess("Voltage - Output (Min/Fixed)",
regex_capture_map([(".*~.*", "Adjustable"),
("(\d+.?\d*\w*V)", "%s"),
(".*", ''),
], default=False)),
ParametricPreprocess("Voltage Dropout (Max)",
regex_capture_map([("(\d+.?\d*\w*V)\s*@.*", "%s"),
("\?", "?"),
], default=False)),
],
"IC, LDO, %(Voltage - Output (Min/Fixed))s",
"%(Current - Output)s, %(Voltage Dropout (Max))s(d)"
),
"PMIC - Voltage Reference":
QuickDescStruct([],
"IC, %(Voltage - Output (Min/Fixed))s Reference",
"%(Tolerance)s"
),
"PMIC - Voltage Regulators - DC DC Switching Regulators":
QuickDescStruct([ParametricPreprocess("Topology", list_truncate(2)),
],
"IC, DC/DC: %(Topology)s",
"Regulator, %(Frequency - Switching)s"
),
"PMIC - Voltage Regulators - DC DC Switching Controllers":
QuickDescStruct([ParametricPreprocess("Topology", list_truncate(2)),
],
"IC, DC/DC: %(Topology)s",
"Controller, %(Frequency - Switching)s"
),
### ICs, Logic
"Logic - Flip Flops":
QuickDescStruct([ParametricPreprocess("Type",
regex_capture_map([("(\w+).Type*", "%s"),
("\?", "?"),
], default=False)),
ParametricPreprocess("Max Propagation Delay @ V, Max CL",
regex_capture_map([("(\d+.?\d*\w*s)\s*@.*", "%s"),
("\?", "?"),
], default=False)),
],
"IC, %(Type)s Flip-flop",
"%(Number of Elements)sx %(Number of Bits per Element)s bits, %(Max Propagation Delay @ V, Max CL)s delay"
),
"Logic - Gates and Inverters":
QuickDescStruct([ParametricPreprocess("Max Propagation Delay @ V, Max CL",
regex_capture_map([("(\d+.?\d*\w*s)\s*@.*", "%s"),
("\?", "?"),
], default=False)),
],
"IC, %(Logic Type)s",
"%(Number of Circuits)s circuits, %(Number of Inputs)s inputs, %(Max Propagation Delay @ V, Max CL)s delay"
),
"Logic - Shift Registers":
QuickDescStruct([],
"IC, Shift Register",
"%(Number of Elements)sx %(Number of Bits per Element)s bits"
),
"Logic - Translators, Level Shifters":
QuickDescStruct([],
"IC, Level Shifter",
"%(Number of Circuits)sx %(Channels per Circuit)s channel"
),
"Logic - Buffers, Drivers, Receivers, Transceivers":
QuickDescStruct([],
"IC, Transceiver",
"%(Number of Elements)sx %(Number of Bits per Element)s bits"
),
### ICs, Misc
"Linear - Amplifiers - Instrumentation, OP Amps, Buffer Amps":
QuickDescStruct([],
"IC, Op-amp",
"%(Slew Rate)s"
),
"Linear - Amplifiers - Audio":
QuickDescStruct([],
"IC, Audio Op-amp",
"%(Type)s"
),
"Linear - Comparators":
QuickDescStruct([],
"IC, Comparator",
""
),
"Data Acquisition - Analog to Digital Converters (ADC)":
QuickDescStruct([],
"IC, ADC, %(Number of Bits)s bits",
"%(Sampling Rate (Per Second))ssps"
),
"Data Acquisition - Digital to Analog Converters (DAC)":
QuickDescStruct([],
"IC, DAC, %(Number of Bits)s bits",
"%(Settling Time)s"
),
"Data Acquisition - Digital Potentiometers":
QuickDescStruct([],
"IC, Digipot, %(Resistance (Ohms))s\u03a9",
"%(Number of Taps)s taps"
),
"Clock/Timing - Real Time Clocks":
QuickDescStruct([],
"IC, Real-Time Clock",
"%(Interface)s"
),
"Clock/Timing - Programmable Timers and Oscillators":
QuickDescStruct([],
"IC, Timer",
"%(Frequency)s"
),
"PMIC - Current Regulation/Management":
QuickDescStruct([],
"IC, %(Function)s",
"%(Sensing Method)s Sensing"
),
"PMIC - V/F and F/V Converters":
QuickDescStruct([],
"IC, %(Type)s",
"%(Frequency - Max)s max"
),
"PMIC - LED Drivers":
QuickDescStruct([],
"IC, LED Driver",
"%(Number of Outputs)sx, %(Current - Output / Channel)s"
),
"PMIC - Full, Half-Bridge Drivers":
QuickDescStruct([],
"IC, %(Output Configuration)s",
"%(Voltage - Load)s, %(Current - Output / Channel)s/channel"
),
"PMIC - Gate Drivers":
QuickDescStruct([],
"IC, Gate Driver",
"%(Number of Drivers)s drivers"
),
"PMIC - Battery Chargers":
QuickDescStruct([],
"IC, Battery Charger",
"%(Battery Chemistry)s, %(Battery Pack Voltage)s, %(Charge Current - Max)s"
),
"Interface - Analog Switches, Multiplexers, Demultiplexers": # TODO: make this better
QuickDescStruct([],
"IC, Analog Switch",
"%(Number of Circuits)sx %(Multiplexer/Demultiplexer Circuit)s circuit, %(-3db Bandwidth)s (-3db)"
),
"Interface - I/O Expanders":
QuickDescStruct([],
"IC, I/O Expander",
"%(Interface)s, %(Number of I/O)s I/O"
),
"Embedded - Microcontrollers":
QuickDescStruct([ParametricPreprocess("Program Memory Size",
regex_capture_map([("(\d+[KMG]B)", "%s"),
], default=False)),
],
"IC, MCU, %(Core Processor)s",
"%(Number of I/O)s I/O, %(Speed)s, %(Program Memory Size)s"
),
"Embedded - CPLDs (Complex Programmable Logic Devices)":
QuickDescStruct([],
"IC, CPLD",
"%(Number of I/O)s I/O, %(Number of Macrocells)s MCs"
),
"Memory":
QuickDescStruct([ParametricPreprocess("Memory Size",
regex_capture_map([("(\d+[KMG]b)", "%s"),
], default=False)),
],
"IC, %(Memory Format)s, %(Memory Size)s",
"%(Memory Interface)s"
),
### ICs, Misc, Sensors
"Magnetic Sensors - Linear, Compass (ICs)":
QuickDescStruct([],
"Sensor, Magnetic",
"%(Axis)s axis, %(Bandwidth)s"
),
"Motion Sensors - Accelerometers":
QuickDescStruct([],
"Sensor, Accelerometer",
"%(Axis)s axis, %(Bandwidth)s"
),
"Optical Sensors - Photo Detectors - CdS Cells":
QuickDescStruct([],
"CdS Photocell",
""
),
"Optical Sensors - Photodiodes":
QuickDescStruct([],
"Photodiode",
""
),
"Optical Sensors - Reflective - Analog Output":
QuickDescStruct([],
"Optical Reflective Sensor",
""
),
"Microphones":
QuickDescStruct([],
"Microphone",
"%(Type)s"
),
### Misc
"Crystals":
QuickDescStruct([],
"Crystal, %(Frequency)s",
"%(Frequency Tolerance)s, %(Load Capacitance)s"
),
"PTC Resettable Fuses":
QuickDescStruct([],
"PTC Fuse, %(Current - Hold (Ih) (Max))s(h)",
"%(Voltage - Max)s, %(Current - Trip (It))s(t)"
),
"Temperature Sensors - NTC Thermistors":
QuickDescStruct([],
"Thermistor, NTC, %(Resistance in Ohms @ 25\u00b0C)s",
""
),
}
"""
Return a function which takes a string (formatted as a list of sub-strings, with
the specified separator). Matches the sub-strings in the list against the regex
strings in matches (in order of matches), returning the first sub-string that
matches.
Intended use case is to pick a desired sub-string element by format (ranked in
matches).
Raises an exception if no match is found. Matches can include a wildcard as a
fallback, which will just return the first sub-string.
"""
def list_regex_map(matches, separator=', ', default=True):
match_progs = [(re.compile('^' + elt[0] + '$'), elt[1]) for elt in matches]
def fn(in_string):
substrings = in_string.split(separator)
substrings = [substr.strip() for substr in substrings]
for match_prog, output in match_progs:
for substr in substrings:
match = match_prog.match(substr)
if match:
return output % match.groups()
if default:
return substrings[0]
else:
raise Exception("Failed to match on '%s' with matchers %s" % (in_string, matches))
return fn
package_priority_map = {
('(D\u00B2?Pak)', '%s'),
('(TO-220).*', '%s'),
('(TO-92).*', '%s'),
('(TO-\d+).*', '%s'),
('(SOT-23).*', '%s'),
('(SOT-\d+).*', '%s'),
('(SOD-\d+).*', '%s'),
('(DO-\d+)', '%s'),
('(\d+-TSSOP)', '%s'),
('SOT-753', 'SOT-23'),
('(Radial)', '%s'),
}
paren_removal_regex = re.compile("\s*\([^\(^\)]+\)\s*")
def DigikeyQuickDesc(row_dict):
print("Processing digikey_pn='%s'" % row_dict['digikey_pn'])
parametrics_str = row_dict['parametrics']
if not parametrics_str:
return {}
parametrics = ast.literal_eval(parametrics_str)
family = parametrics['Categories']
assert family in quickdesc_rules, "no rule for part family '%s'" % family
# Do global pre-process
for k, v in parametrics.items():
# Eliminate supplemental information in parentheses
v = re.sub(paren_removal_regex, '', v)
if v == '-':
v = '?'
parametrics[k] = v
# Global package preference selection
if 'Package / Case' in parametrics:
package = list_regex_map(package_priority_map)(parametrics['Package / Case'])
parametrics['Package / Case'] = package
quickdesc_rule = quickdesc_rules[family]
for processor in quickdesc_rule.preprocessors:
assert processor.name in parametrics, "Preprocessor for family '%s' needs pamametric '%s'" % (family, processor.name)
parametrics[processor.name] = processor.fn(parametrics[processor.name])
title = quickdesc_rule.title % parametrics
if 'Package / Case' in parametrics:
package = parametrics['Package / Case']
else:
package = ''
quickdesc = quickdesc_rule.quickdesc % parametrics
return {'dist_title': title,
'dist_package': package,
'dist_quickdesc': quickdesc}
load().map_append(DigikeyQuickDesc) \
.map_append(RemapParametric('dist_mfrpn', 'Manufacturer Part Number')) \
.map_append(RemapParametric('dist_desc', 'Description')) \
.write()