-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathK2PK.py
executable file
·2455 lines (2005 loc) · 85.1 KB
/
K2PK.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import decimal
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
import http.server
import socketserver
from datetime import datetime
# from pprint import pprint
import requests
from math import log10, ceil
import numpy as np
import numpy.ma as ma
from fpdf import FPDF
from currency_converter import CurrencyConverter
from json2html import *
from K2PKConfig import *
from mysql.connector import Error, MySQLConnection
# NOTE: Set precision to cope with nano, pico & giga multipliers.
ctx = decimal.Context()
ctx.prec = 12
# Set colourscheme (this could go into preferences.ini)
# Colour seems to be most effective when used against a white background
adequate = 'rgb(253,246,227)'
# adequate = 'rgba(0, 60, 0, 0.15)'
lowstock = '#f6f6f6'
# lowstock = 'rgba(255, 255, 255, 0)'
nopkstock = '#c5c5c5'
# nopkstock = 'rgba(0, 60, 60, 0.3)'
multistock = '#e5e5e5'
# multistock = 'rgba(255, 255, 255, 0)'
minPriceCol = 'rgb(133,153,0)'
try:
currencyConfig = read_currency_config()
baseCurrency = (currencyConfig['currency'])
except KeyError:
print("No currency configured in config.ini")
assert sys.version_info >= (3, 4)
file_name = sys.argv[1]
projectName, ext = file_name.split(".")
print(projectName)
numBoards = 0
try:
while numBoards < 1:
qty = input("How many boards? (Enter 1 or more) > ")
numBoards = int(qty)
print("Calculations for ", numBoards, " board(s)")
except ValueError:
print("Integer values only, >= 1. Quitting now")
raise SystemExit
# Make baseline barcodes and web directories
try:
os.makedirs('./assets/barcodes')
except OSError:
pass
try:
os.makedirs('./assets/web')
except OSError:
pass
invalidate_BOM_Cost = False
try:
distribConfig = read_distributors_config()
preferred = (distribConfig['preferred'])
except KeyError:
print('No preferred distributors in config.ini')
pass
# Initialise empty cost and coverage matrix
prefCount = preferred.count(",") + 1
costMatrix = [0] * prefCount
coverageMatrix = [0] * prefCount
countMatrix = [0] * prefCount
voidMatrix = [0] * prefCount
def float_to_str(f):
d1 = ctx.create_decimal(repr(f))
return format(d1, 'f')
def convert_units(num):
'''
Converts metric multipliers values into a decimal float.
Takes one input eg 12.5m and returns the decimal (0.0125) as a string. Also supports
using the multiplier as the decimal marker e.g. 4k7
'''
factors = ["G", "M", "K", "k", "R", "", ".", "m", "u", "n", "p"]
conversion = {
'G': '1000000000',
'M': '1000000',
'K': '1000',
'k': '1000',
'R': '1',
'.': '1',
'': '1',
'm': '0.001',
"u": '0.000001',
'n': '0.000000001',
'p': '0.000000000001'
}
val = ""
mult = ""
for i in range(len(num)):
if num[i] == ".":
mult = num[i]
if num[i] in factors:
mult = num[i]
val = val + "."
else:
if num[i].isdigit():
val = val + (num[i])
else:
print("Invalid multiplier")
return "0"
if val.endswith("."):
val = val[:-1]
m = float(conversion[mult])
v = float(val)
r = float_to_str(m * v)
r = r.rstrip("0")
r = r.rstrip(".")
return r
def limit(num, minimum=10, maximum=11):
'''
Limits input 'num' between minimum and maximum values.
Default minimum value is 10 and maximum value is 11.
'''
return max(min(num, maximum), minimum)
def partStatus(partID, parameter):
dbconfig = read_db_config()
try:
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
sql = "SELECT DISTINCT R.stringValue FROM PartParameter R WHERE (R.name = '{}') AND (R.part_id = {})".format(
parameter, partID)
cursor.execute(sql)
partStatus = cursor.fetchall()
if partStatus == []:
part = "Unknown"
else:
part = str(partStatus[0])[2:-3]
return part
except UnicodeEncodeError as err:
print(err)
finally:
cursor.close()
conn.close()
def getDistrib(partID):
dbconfig = read_db_config()
try:
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
sql = """SELECT D.name, PD.sku, D.skuurl FROM Distributor D
LEFT JOIN PartDistributor PD on D.id = PD.distributor_id
WHERE PD.part_id = {}""".format(partID)
cursor.execute(sql)
distrbs = cursor.fetchall()
unique = []
d = []
distributor = []
for distributor in distrbs:
if distributor[0] not in unique and distributor[0] in preferred:
unique.append(distributor[0])
d.append(distributor)
return d
except UnicodeEncodeError as err:
print(err)
finally:
cursor.close()
conn.close()
def labelsetup():
pdf = FPDF(orientation='P', unit='mm', format='A4')
rows = 4
cols = 3
margin = 4 # In mm
labelWidth = (210 - 2 * margin) / cols
labelHeight = (297 - 2 * margin) / rows
pdf.add_page()
return (labelWidth, labelHeight, pdf)
def picksetup(BOMname, dateBOM, timeBOM):
pdf2 = FPDF(orientation='L', unit='mm', format='A4')
margin = 10 # In mm
pdf2.add_page()
pdf2.set_auto_page_break(1, 4.0)
pdf2.set_font('Courier', 'B', 9)
pdf2.multi_cell(80, 10, BOMname, align="L", border=0)
pdf2.set_auto_page_break(1, 4.0)
pdf2.set_font('Courier', 'B', 9)
pdf2.set_xy(90, 10)
pdf2.multi_cell(30, 10, dateBOM, align="L", border=0)
pdf2.set_xy(120, 10)
pdf2.multi_cell(30, 10, timeBOM, align="L", border=0)
pdf2.set_font('Courier', 'B', 7)
pdf2.set_xy(5, 20)
pdf2.multi_cell(10, 10, "Line", border=1)
pdf2.set_xy(15, 20)
pdf2.multi_cell(40, 10, "Ref", border=1)
pdf2.set_xy(55, 20)
pdf2.multi_cell(95, 10, "Part", border=1)
pdf2.set_xy(150, 20)
pdf2.multi_cell(10, 10, "Stock", border=1)
pdf2.set_xy(160, 20)
pdf2.multi_cell(50, 10, "P/N", border=1)
pdf2.set_xy(210, 20)
pdf2.multi_cell(50, 10, "Location", border=1)
pdf2.set_xy(260, 20)
pdf2.multi_cell(10, 10, "Qty", border=1)
pdf2.set_xy(270, 20)
pdf2.multi_cell(10, 10, "Pick", border=1)
return (pdf2)
def makepick(line, pdf2, pos):
index = ((pos - 1) % 16) + 1
pdf2.set_font('Courier', 'B', 6)
pdf2.set_xy(5, 20 + 10 * index) # Line Number
pdf2.multi_cell(10, 10, str(pos), align="C", border=1)
pdf2.set_xy(15, 20 + 10 * index) # Blank RefDes box
pdf2.multi_cell(40, 10, "", align="L", border=1)
pdf2.set_xy(15, 20 + 10 * index) # RefDes
pdf2.multi_cell(40, 5, line[6], align="L", border=0)
pdf2.set_xy(55, 20 + 10 * index) # Blank Part box
pdf2.multi_cell(95, 10, '', align="L", border=1)
pdf2.set_font('Courier', 'B', 8)
pdf2.set_xy(55, 20 + 10 * index) # Part name
pdf2.multi_cell(95, 5, line[1], align="L", border=0)
pdf2.set_font('Courier', '', 6)
pdf2.set_xy(55, 24 + 10 * index) # Part Description
pdf2.multi_cell(95, 5, line[0][:73], align="L", border=0)
pdf2.set_xy(150, 20 + 10 * index)
pdf2.multi_cell(10, 10, str(line[5]), align="C", border=1) # Stock
pdf2.set_xy(160, 20 + 10 * index)
pdf2.multi_cell(50, 10, '', align="C", border=1) # Blank cell
pdf2.set_xy(160, 23.5 + 10 * index)
pdf2.multi_cell(50, 10, line[2], align="C", border=0) # PartNum
pdf2.set_xy(172, 21 + 10 * index)
if line[2] != "":
pdf2.image('assets/barcodes/' + line[2] + '.png', h=6) # PartNum BC
pdf2.set_xy(210, 20 + 10 * index)
pdf2.multi_cell(50, 10, '', align="C", border=1) # Blank cell
pdf2.set_xy(210, 23.5 + 10 * index)
pdf2.multi_cell(50, 10, line[3], align="C", border=0) # Location
pdf2.set_xy(223, 21 + 10 * index)
if line[3] != "":
pdf2.image(
'assets/barcodes/' + line[3][1:] + '.png', h=6) # Location BC
pdf2.set_font('Courier', 'B', 8)
pdf2.set_xy(260, 20 + 10 * index)
pdf2.multi_cell(10, 10, line[4], align="C", border=1) # Qty
pdf2.set_xy(270, 20 + 10 * index)
pdf2.multi_cell(10, 10, "", align="L", border=1)
pdf2.set_xy(273, 23 + 10 * index)
if line[3] != "":
pdf2.multi_cell(4, 4, "", align="L", border=1)
if index % 16 == 0:
pdf2.add_page()
def makelabel(label, labelCol, labelRow, lblwidth, lblheight, pdf):
'''
Take label info and make a label at position defined by row & column
'''
lineHeight = 3
intMargin = 7
labelx = int((lblwidth * (labelCol % 3)) + intMargin)
labely = int((lblheight * (labelRow % 4)) + intMargin)
pdf.set_auto_page_break(1, 4.0)
pdf.set_font('Courier', 'B', 9)
pdf.set_xy(labelx, labely)
pdf.multi_cell(
lblwidth - intMargin, lineHeight, label[0], align="L", border=0)
pdf.set_font('Courier', '', 8)
pdf.set_xy(labelx, labely + 10)
pdf.cell(lblwidth, lineHeight, label[1], align="L", border=0)
pdf.image('assets/barcodes/' + label[1] + '.png', labelx, labely + 13, 62,
10)
pdf.set_xy(labelx, labely + 25)
pdf.cell(lblwidth, lineHeight, 'Part no: ' + label[2], align="L", border=0)
pdf.set_xy(labelx + 32, labely + 25)
pdf.cell(
lblwidth, lineHeight, 'Location: ' + label[3], align="L", border=0)
pdf.image('assets/barcodes/' + label[2] + '.png', labelx, labely + 28, 28,
10)
pdf.image('assets/barcodes/' + label[3][1:] + '.png', labelx + 30,
labely + 28, 32, 10)
pdf.set_xy(labelx, labely + 40)
pdf.cell(
lblwidth, lineHeight, 'Quantity: ' + label[4], align="L", border=0)
pdf.image('assets/barcodes/' + label[4] + '.png', labelx, labely + 43, 20,
10)
pdf.set_font('Courier', 'B', 8)
pdf.set_xy(labelx + 25, labely + 46)
pdf.multi_cell(35, lineHeight, label[9], align="L", border=0)
pdf.set_xy(labelx, labely + 56)
pdf.multi_cell(
lblwidth - intMargin, lineHeight, label[6], align="L", border=0)
if (labelCol == 2) & ((labelRow + 1) % 4 == 0):
pdf.add_page()
def getTable(partID, q, bcolour, row):
'''
There are 8 columns of manuf data /availability and pricing starts at col 9
Pricing in quanties of 1, 10, 100 - so use log function
background colour already set so ignored.
'''
index = int(log10(q)) + 9
tbl = ""
minPrice = 999999
classtype = ''
pricingExists = False
fn = "./assets/web/" + str(partID) + ".csv"
# If file is empty st_size should = 0 BUT file always contains exactly 1 byte ...
if os.stat(fn).st_size == 1: # File (almost) empty ...
tbl = "<td colspan = " + str(
len(preferred)
) + " class ='lineno' '><b>No data found from preferred providers</b></td>"
return tbl, voidMatrix, voidMatrix, voidMatrix
try:
minData = np.genfromtxt(fn, delimiter=",")
if np.ndim(minData) == 1: # If only one line, nanmin fails
minPrice = minData[index]
else:
minPrice = np.nanmin(minData[:, index])
except (UserWarning, ValueError, IndexError) as error:
print(
"ATTENTION ", error
) # Just fails when empty file or any other error, returning no data
tbl = "<td colspan = " + str(
len(preferred)
) + " class ='lineno'><b>No data found from preferred providers</b></td>"
return tbl, voidMatrix, voidMatrix, voidMatrix
csvFiles = open(fn, "r")
compPrefPrices = list(csv.reader(csvFiles))
line = ""
line2 = ""
n = len(preferred)
_costRow = [0] * n
_coverageRow = [0] * n
_countRow = [0] * n
# line += "<form>"
for d, dist in enumerate(preferred):
line += "<td"
terminated = False
low = 0
magnitude = 0
i = 0
for _comp in compPrefPrices:
price = ""
priceLine = ""
try:
if _comp[0] in dist:
try:
price = str("{0:2.2f}".format(float(_comp[index])))
dispPrice = price
except:
ValueError
price = "-" # DEBUG "-"
try:
priceLine = str("{0:2.2f}".format(
q * float(_comp[index])))
calcPL = priceLine
except:
ValueError
priceLine = "-" # DEBUG "-"
calcPL = "0.0"
if i == 0: # 1st row only being considered
try:
_costRow[d] = q * float(_comp[index])
except:
ValueError
_costRow[d] = 0.0
_coverageRow[d] = 1
_countRow[d] = q
try:
_moq = int(_comp[3])
except:
ValueError
_moq = 999999
if bcolour == 'rgb(238, 232, 213)':
classtype = 'ambig'
else:
classtype = 'mid'
if _comp[index].strip() == str(minPrice):
pricingExists = True
classtype = 'min'
line += " class = '" + classtype + "'>"
line += " <input id = '" + str(d) + "-"+str(row)+"' type='radio' name='" + str(row) + "' value='" + \
calcPL + "' checked >"
else:
pricingExists = True
line += " class = '" + classtype + "'>"
line += " <input id='" + str(d) + "-"+str(row)+"' type='radio' name='" + str(row) + "' value='" + \
calcPL + "'>"
line += "<label for=" + str(d) + "></label>"
line += " <b><a href = '" + _comp[4] + "'>" + _comp[1] + "</a></b><br>"
if price == "-":
line += "<p class ='null' style= 'padding:5px;'> Ea:"
line += "<span style='float: right; text-align: right;'>"
line += "<b >" + price + "</b> "
line += _comp[8]
price = "0"
else:
line += "<p style= 'padding:5px;'> Ea:"
line += "<span style='float: right; text-align: right;'>"
line += "<b>" + price + "</b> "
line += _comp[8]
line += "</span>"
if priceLine == "-":
line += "<p class ='null' style= 'padding:5px;'> Line:"
line += "<span style='float: right; text-align: right;'>"
line += "<b >" + priceLine + "</b> "
line += _comp[8]
priceline = "0"
else:
line += "<p style= 'padding:5px;'> Line:"
line += "<span style='float: right; text-align: right;'>"
line += "<b>" + priceLine + "</b> "
line += _comp[8]
line += "</span>"
line += "<p style= 'padding:5px;'> MOQ: "
line += "<span style='float: right; text-align: right;'><b>" + _comp[3] + "</b>"
if int(q) >= _moq: # MOQ satisfied
line += " <span class = 'icon'>🔹 </span></span><p>"
else:
line += " <span class = 'icon'>🔺 </span></span><p>"
line += "<p style= 'padding:5px;'> Stock:"
line += "<span style='float: right; text-align: right;'><b>"
line += _comp[2] + "</b>"
if int(q) <= int(_comp[2]): # Stock satisfied
line += " <span class = 'icon'>🔹 </span></span><p>"
else:
line += " <span class = 'icon'>🔸 </span></span><p>"
P1 = ""
P2 = ""
magnitude = 10**(index - 9)
if _moq == 999999:
low = q
next = 10 * magnitude
column = int(log10(low) + 9)
elif _moq > magnitude:
low = _moq
next = 10**(ceil(log10(low)))
column = int(log10(low) + 10)
else:
low = magnitude
next = 10 * magnitude
column = int(log10(low) + 9)
try:
if float(_comp[column]) > 1:
P1 = str("{0:2.2f}".format(
float(_comp[column])))
else:
P1 = str("{0:3.3f}".format(
float(_comp[column])))
except:
ValueError
P1 = "-"
line += "<p style='text-align: left; padding:5px;'>" + str(
low) + " +"
line += "<span style='float: right; text-align: right;'><b>" + P1 + "</b> " + _comp[8] + "</span>"
if column <= 12:
try:
if float(_comp[column]) > 1:
P2 = str("{0:2.2f}".format(
float(_comp[column + 1])))
else:
P2 = str("{0:3.3f}".format(
float(_comp[column + 1])))
except:
ValueError
P2 = "-"
line += "<p style='text-align: left; padding:5px;'>" + str(
next) + " +"
line += "<span style='float: right; text-align: right;'><b>" + P2 + "</b> " + _comp[8] + "</span>"
else: # Nasty kludge - relly need to iterate through these to get best deal
if i == 1:
line += "<br><br><br><p style= 'padding:5px;'><b> Alternatives</b><br>"
try:
if _comp[index].strip() == str(minPrice):
if classtype != 'min':
line += "<div class = 'min'>"
price = str("{0:2.2f}".format(float(_comp[index])))
priceLine = str("{0:2.2f}".format(
q * float(_comp[index])))
line += "<p style= 'padding:5px;'><b><a href = '" + _comp[4] + "' > " + _comp[1] + " </b></a><br>"
line += "<p style= 'padding:5px;'> Ea: <b>"
line += price + "</b> " + _comp[8]
except:
ValueError
line += "<p style= 'padding:5px;'><b><a href = '" + _comp[4] + "' > " + _comp[1] + " </b></a><br>"
line += " Pricing N/A"
i += 1
# FIXME This needs to count number of instances
if i <= 3:
terminated = True
else:
terminated = False
except IndexError:
pass
if not terminated:
line += ">"
_costRow[d] = 0
_countRow[d] = 0
_coverageRow[d] = 0
if pricingExists:
line += "<p style='padding:5px;'>"
pricingExists = False
line += "</td>"
# line += "</form>"
tbl += line
return tbl, _costRow, _coverageRow, _countRow
def octopartLookup(partIn, bean):
try:
octoConfig = read_octopart_config()
apikey = (octoConfig['apikey'])
except:
KeyError
print('No Octopart API key in config.ini')
return (2)
try:
currencyConfig = read_currency_config()
locale = (currencyConfig['currency'])
except:
KeyError
print("No currency configured in config.ini")
return (4)
# Get currency rates from European Central Bank
# Fall back on cached cached rates
try:
c = CurrencyConverter(
'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip')
except:
URLError
c = CurrencyConverter()
return (8)
# Remove invalid characters
partIn = partIn.replace("/", "-")
path = partIn.replace(" ", "")
web = str("./assets/web/" + path + ".html")
Part = partIn
webpage = open(web, "w")
combo = False
if " " in partIn:
# Possible Manufacturer/Partnumber combo. The Octopart mpn search does not include manufacturer
# Split on space and assume that left part is Manufacturer and right is partnumber.
# Mark as comboPart.
combo = True
comboManf, comboPart = partIn.split(" ")
aside = open("./assets/web/tmp.html", "w")
htmlHeader = """
<!DOCTYPE html>
<html lang = 'en'>
<meta charset="utf-8">
<head>
<html lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Octopart Lookup</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="Description" lang="en" content="Kicad2PartKeepr">
<meta name="author" content="jpateman@gmail.com">
<meta name="robots" content="index, follow">
<!-- icons -->
<link rel="apple-touch-icon" href="assets/img/apple-touch-icon.png">
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="../css/octopart.css">
</head>
<body>
<div class="header">
<h1 class="header-heading">Kicad2PartKeepr</h1>
</div>
<div class="nav-bar">
<div class="container">
<ul class="nav">
</ul>
</div>
</div>
"""
webpage.write(htmlHeader)
##################
bean = False
##################
if bean:
#
url = "https://octopart.com/api/v4/rest/parts/search"
url += '?apikey=' + apikey
url += '&q="' + Part + '"'
url += '&include[]=descriptions'
url += '&include[]=imagesets'
# url += '&include[]=specs'
# url += '&include[]=datasheets'
url += '&country=GB'
elif combo:
#
url = "https://octopart.com/api/v4/rest/parts/match"
url += '?apikey=' + apikey
url += '&queries=[{"brand":"' + comboManf + \
'","mpn":"' + comboPart + '"}]'
url += '&include[]=descriptions'
url += '&include[]=imagesets'
url += '&include[]=specs'
url += '&include[]=datasheets'
url += '&country=GB'
else:
url = "https://octopart.com/api/v4/rest/parts/match"
url += '?apikey=' + apikey
url += '&queries=[{"mpn":"' + Part + '"}]'
url += '&include[]=descriptions'
url += '&include[]=imagesets'
url += '&include[]=specs'
url += '&include[]=datasheets'
url += '&country=GB'
data = urllib.request.urlopen(url).read()
response = json.loads(data.decode('utf8'))
loop = False
for result in response['results']:
for item in result['items']:
if loop:
break
loop = True
partNum = item['mpn']
try:
description = str(item['descriptions'][0].get('value', None))
except:
IndexError
description = ""
try:
brand = str(item['brand']['name'])
except:
IndexError
brand = ""
# Get image (if present). Also need to get attribution for Octopart licensing
try:
# image = str(item['imagesets'][0]['medium_image'].get('url', None))
image = item['imagesets'][0]['large_image']['url']
except:
IndexError
image = ""
try:
credit = item['imagesets'][0]['credit_string']
crediturl = item['imagesets'][0]['credit_url']
except:
IndexError
credit = ""
crediturl = ""
webpage.write(
"<div class='content' id = 'thumbnail'><table class = 'table2'><tr><td style = 'width:100px;'><img src='"
+ image + "' alt='thumbnail'></td><td><h2>" + brand + " " + partNum + "</h2><h4>" +
description + "</h4></td></tr><tr><td style = 'color:#aaa;'>Image: " + credit +"</td><td></td></tr></table></div>")
specfile = open("./assets/web/" + path, 'w')
specfile.write(image)
aside.write(
"<div class = 'aside'><table class='table table-striped'><thead>")
aside.write("<th>Characteristic</th><th>Value</th></thead><tbody>")
for spec in item['specs']:
parm = item['specs'][spec]['metadata']['name']
try:
val = str(item['specs'][spec]['value'][0])
except:
IndexError
val = "Not Listed by Manufacturer"
parameter = (("{:34} ").format(parm))
value = (("{:40}").format(val))
print(("| {:30} : {:120} |").format(parameter, value))
aside.write("<tr><td>" + parameter + "</td><td>" + value +
"</td></tr>")
print(('{:_<162}').format(""))
aside.write("</tbody></table><table class='table table-striped'>")
aside.write(
"<thead><th>Datasheets</th><th>Date</th><th>Pages</th></thead><tbody>"
)
for d, datasheet in enumerate(item['datasheets']):
if d == 1:
specfile.write(',' + datasheet['url'])
try:
if (datasheet['metadata']['date_created']):
dateUpdated = (
datasheet['metadata']['date_created'])[:10]
else:
dateUpdated = "Unknown"
except:
IndexError
dateUpdated = "Unknown"
if datasheet['attribution']['sources'] is None:
source = "Unknown"
else:
source = datasheet['attribution']['sources'][0]['name']
try:
numPages = str(datasheet['metadata']['num_pages'])
except:
TypeError
numPages = "-"
documents = ((
"| {:30.30} {:11} {:12} {:7} {:7} {:1} {:84.84} |").format(
source, " Updated: ", dateUpdated, "Pages: ", numPages,
"", datasheet['url']))
print(documents)
aside.write("<tr><td><a href='" + datasheet['url'] + "'> " +
source + " </a></td><td>" + dateUpdated +
"</td><td>" + numPages + "</td></tr>")
# if loop:
# webpage.write("<table class='table table-striped'>")
# else:
# webpage.write("<p> No Octopart results found </>")
# Header row here
webpage.write(
"<div class ='main'><table><thead><th>Seller</th><th>SKU</th><th>Stock</th><th>MOQ</th><th>Package</th><th>Currency</th><th>1</th><th>10</th><th>100</th><th>1000</th><th>10000</th></thead><tbody>"
)
count = 0
for result in response['results']:
stockfile = open("./assets/web/" + path + '.csv', 'w')
for item in result['items']:
if count == 0:
print(('{:_<162}').format(""))
print(
("| {:24} | {:19} | {:>9} | {:>7} | {:11} | {:5} ").format(
"Seller", "SKU", "Stock", "MOQ", "Package",
"Currency"),
end="")
print(
("| {:>10}| {:>10}| {:>10}| {:>10}| {:>10}|").format(
"1", "10", "100", "1000", "10000"))
print(('{:-<162}').format(""), end="")
count += 1
# Breaks at 1, 10, 100, 1000, 10000
for offer in item['offers']:
loop = 0
_seller = offer['seller']['name']
_sku = (offer['sku'])[:19]
_stock = offer['in_stock_quantity']
_moq = str(offer['moq'])
_productURL = str(offer['product_url'])
_onOrderQuant = offer['on_order_quantity']
# _onOrderETA = offer['on_order_eta']
_factoryLead = offer['factory_lead_days']
_package = str(offer['packaging'])
_currency = str(offer['prices'])
if _moq == "None":
_moq = '-'
if _package == "None":
_package = "-"
# if not _factoryLead or _factoryLead == "None":
# _factoryLead = "-"
# else:
# _factoryLead = int(int(_factoryLead) / 7)
if _seller in preferred:
data = str(_seller) + ", " + str(_sku) + ", " + \
str(_stock) + ", " + str(_moq) + ", " + str(_productURL) + ", " +\
str(_factoryLead) + ", " + str("_onOrderETA") + ", " + str(_onOrderQuant) +\
", " + str(locale)
stockfile.write(data)
print()
print(
("| {:24.24} | {:19} | {:>9} | {:>7} | {:11} |").format(
_seller, _sku, _stock, _moq, _package),
end="")
line = "<tr><td>" + _seller + "</td><td><a target='_blank' href=" + str(
offer['product_url']) + ">" + str(
offer['sku']) + "</a></td><td>" + str(
_stock) + "</td><td>" + str(
_moq) + "</td><td>" + _package + "</td>"
webpage.write(line)
valid = False
points = ['-', '-', '-', '-', '-']
for currency in offer['prices']:
# Some Sellers don't have currency so use this to fill the line
valid = True
if currency == locale:
# Base currency is local
loop += 1
if loop == 1:
print((" {:3} |").format(currency), end="")
webpage.write("<td>" + currency + "</td>")
else:
# Only try and convert first currency
loop += 1
if loop == 1:
print((" {:3}* |").format(locale), end="")
webpage.write("<td>" + locale + "*</td>")
if loop == 1:
for breaks in offer['prices'][currency]:
_moqv = offer['moq']
if _moqv is None:
_moqv = 1
_moqv = int(_moqv)
i = 0
# Break 0 - 9
if breaks[0] < 10:
points[0] = round(
c.convert(breaks[1], currency, locale), 2)
for i in range(0, 4):
points[i + 1] = points[i]
# Break 10 to 99
if breaks[0] >= 10 and breaks[0] < 100:
points[1] = round(
c.convert(breaks[1], currency, locale), 3)
# if _moqv >= breaks[0]:
for i in range(1, 4):
points[i + 1] = points[i]
# Break 100 to 999
if breaks[0] >= 100 and breaks[0] < 1000:
points[2] = round(
c.convert(breaks[1], currency, locale), 4)
# if _moqv >= breaks[0]:
for i in range(2, 4):
points[i + 1] = points[i]
# Break 1000 to 9999
if breaks[0] >= 1000 and breaks[0] < 10000:
points[3] = round(