Plutonergy

Cython MTG Price compressor

Mar 15th, 2021 (edited)
549
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 23.88 KB | None | 0 0
  1. from database_stuff  import  MTG, PRC, mtgcursor, priceconnection, pricecursor
  2. from datetime        import  date, datetime
  3. from sqlite3         import  Error
  4. from time            import  gmtime, strftime
  5. from tricks          import  tech
  6. from PyQt5.Qt        import  QObject, QRunnable
  7. from PyQt5.QtCore    import  pyqtSignal, pyqtSlot
  8. from PyQt5.Qt        import  QThreadPool
  9. from functools import partial
  10. import traceback
  11. import copy
  12. import json
  13. import os
  14. import sqlite3
  15. import sys
  16. import tempfile
  17. import time
  18.  
  19. memoryconnection = sqlite3.connect(":memory:")
  20. memorycursor = memoryconnection.cursor()
  21.  
  22. class WorkerSignals(QObject):
  23.     finished = pyqtSignal()
  24.     error = pyqtSignal(tuple)
  25.     result = pyqtSignal(object)
  26.     progress = pyqtSignal(int)
  27.  
  28. class Worker(QRunnable):
  29.     def __init__(self, function):
  30.         super(Worker, self).__init__()
  31.         self.fn = function
  32.         self.signals = WorkerSignals()
  33.  
  34.     @pyqtSlot()
  35.     def run(self):
  36.         try:
  37.             result = self.fn()
  38.         except:
  39.             traceback.print_exc()
  40.             exctype, value = sys.exc_info()[:2]
  41.             self.signals.error.emit((exctype, value, traceback.format_exc()))
  42.         else:
  43.             self.signals.result.emit(result)  # Return the result of the processing
  44.         finally:
  45.             self.signals.finished.emit()  # Done
  46.  
  47. class PrinterClass:
  48.     """
  49.    this is just a printer class that prints to the CLI for
  50.    nicer user experience, dont think it drains much time
  51.    """
  52.     def __init__(self):
  53.         cdef float start_time
  54.         cdef dict time_keeper, time_timer
  55.         cdef int total_count
  56.  
  57.         self.threadpool = QThreadPool(maxThreadCount=1)
  58.         self.start_time = time.time() - 1.0
  59.         self.time_keeper = {'work': 0, 'query': 0, 'deleting': 0, 'start': 0, 'iter': 0}
  60.         self.time_timer = {}
  61.         self.total_count = 0
  62.         self.clear_screen = lambda: os.system('clear')
  63.         self.skipped = 0
  64.         self.from_memory = 0
  65.         self.from_card_memory = 0
  66.  
  67.     def take_time(self, str who, bint start):
  68.         """
  69.        :param who: string name of the timer
  70.        :param start:
  71.        if True, timer restarts,
  72.        if False timer stops and stores
  73.        the value in self.time_keeper
  74.        """
  75.         if start == True:
  76.             self.time_timer[who] = time.time()
  77.  
  78.         elif start == False:
  79.             try: self.time_keeper[who] += time.time() - self.time_timer[who]
  80.             except KeyError: self.time_keeper[who] = time.time() - self.time_timer[who]
  81.  
  82.     def output_results(self, int count, str uuid, str current_setcode):
  83.         self.take_time('minute', False)
  84.         if self.time_keeper['minute'] < 10:
  85.             return
  86.  
  87.         self.take_time('minute', True)
  88.         self.time_keeper['minute'] = 0.0
  89.  
  90.         cdef float time_elapsed = time.time() - self.time_timer['start']
  91.         if time_elapsed <= 0:
  92.             return
  93.  
  94.         cdef float time_per_input = time_elapsed / (count+1)
  95.         if time_per_input <= 0:
  96.             return
  97.  
  98.         cdef float inputs_per_minut = 60 / time_per_input
  99.         if inputs_per_minut <= 0:
  100.             return
  101.  
  102.         cdef str part1, part2, part3, part4, part5, part6, part7, part8, part9, parta
  103.         cdef str ending = tech.color.END + "]}>-", card_memory
  104.         cdef str current_color = tech.color.GREEN, end_col = tech.color.END
  105.  
  106.         self.clear_screen()
  107.  
  108.         part1 = "CURRENT{[" + tech.color.PURPLE + current_setcode + ' - ' + uuid + ending
  109.         part2 = " PROGRESS{[" + current_color + str(count+1) + end_col + " of " + current_color + str(self.total_count) + ending
  110.         part3 = " SPEED{[" + tech.color.YELLOW + str(round(inputs_per_minut)) + end_col + "]cards/min}>-"
  111.         part4 = " DURATION{[" + tech.color.CYAN + str(round(time_elapsed)) + ending
  112.         part5 = " WORK/ITER{[" + tech.color.DARKCYAN + str(round(self.time_keeper['work']))
  113.         part6 = end_col + "/" + tech.color.BLUE + str(round(self.time_keeper['iter'])) + ending
  114.         part7 = " QUERY TIME{[" + tech.color.YELLOW + str(round(self.time_keeper['query'])) + ending
  115.         part8 = " DELETE TIME{[" + tech.color.RED + str(round(self.time_keeper['deleting'])) + ending
  116.         part9 = " SKIPPED{[" + tech.color.RED + str(self.skipped) + ending
  117.  
  118.         if self.from_card_memory == True:
  119.             current_color = tech.color.GREEN
  120.         else:
  121.             current_color = tech.color.RED
  122.  
  123.         card_memory = tech.color.END + '/' + current_color + 'JSON' + end_col + ']'
  124.  
  125.         if self.from_memory == True:
  126.             current_color = tech.color.GREEN
  127.         else:
  128.             current_color = tech.color.RED
  129.  
  130.         parta = " MEMORY[" + current_color + 'LOCAL' + card_memory
  131.  
  132.         print(part1 + part2 + part3 + part4 + part5 + part6 + part7 + part8 + part9, parta)
  133.  
  134. def copy_sqlite_table_setcode(fromcursor, toconnection, tocursor, str table, str setcode):
  135.     """
  136.    drops old table and inserts an entire
  137.    table from another with all the data
  138.    from a specific setCode ONLY!
  139.    """
  140.     cdef str query
  141.     cdef list table_data, source_data
  142.  
  143.     fromcursor.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='{}'".format(table, ))
  144.     table_data = fromcursor.fetchall()
  145.  
  146.     with toconnection: # dropping old table
  147.         query = 'drop table ' + table
  148.         try: tocursor.execute(query)
  149.         except Error: pass
  150.  
  151.     with toconnection: # copy same table structure
  152.         query = table_data[0][0]
  153.         try: tocursor.execute(query)
  154.         except Error: pass
  155.  
  156.     query = 'select * from ' + table + ' where setCode = (?)'
  157.     fromcursor.execute(query, (setcode,))
  158.     source_data = fromcursor.fetchall()
  159.  
  160.     if source_data == []:
  161.         return
  162.  
  163.     query, _ = tech.empty_insert_query(fromcursor, table)
  164.  
  165.     with toconnection:
  166.         tocursor.executemany(query, source_data)
  167.  
  168. cdef bint price_guard(float newprice, float oldprice, float percent):
  169.     if newprice > oldprice:
  170.         if oldprice * ((percent / 100) +1) <= newprice:
  171.             return True
  172.     elif newprice < oldprice:
  173.         if newprice * ((percent / 100) +1) <= oldprice:
  174.             return True
  175.  
  176.     return False
  177.  
  178. cdef list price_masher(list combine_pricelist, list timelist, list values):
  179.     """
  180.    takes a list with prices, both new, old and mixed.
  181.    mashes them together and flattens out the price
  182.    returns a list of tiples
  183.    :param combine_pricelist:
  184.    :return: a sorted list of tuples
  185.    """
  186.     cdef list input_list, executemany_list = [], _values
  187.     cdef dict single_dict = {}, newdict
  188.     cdef tuple input
  189.     cdef float input_time, pricetime, newprice, oldprice
  190.     cdef int count, dict_count, weight_div, price
  191.     cdef bint good_job, rv = False
  192.     cdef list price_cycle = [PRC.mtgoReg, PRC.mtgoFoil, PRC.euReg, PRC.euFoil, PRC.usReg, PRC.usFoil]
  193.  
  194.     combine_pricelist.sort(key=lambda x:x[PRC.unixTime])
  195.  
  196.     if len(combine_pricelist) > 1:
  197.         for count in range(1, len(combine_pricelist)):
  198.             for price in price_cycle:
  199.                 if combine_pricelist[count][price] == None and combine_pricelist[count-1][price] != None:
  200.                     _values = list(combine_pricelist[count])
  201.                     _values[price] = combine_pricelist[count-1][price]
  202.                     combine_pricelist[count] = tuple(_values)
  203.  
  204.     for input in combine_pricelist:
  205.  
  206.         input_time = input[PRC.unixTime]
  207.  
  208.         for count in range(1, len(timelist)):
  209.             if input_time > timelist[count-1] and input_time <= timelist[count]:
  210.                 try: single_dict[timelist[count]].append(input)
  211.                 except KeyError: single_dict[timelist[count]] = [input]
  212.  
  213.     for dict_count, (pricetime, input_list) in enumerate(single_dict.items()):
  214.  
  215.         good_job = True
  216.         _values = copy.copy(values)
  217.         _values[PRC.unixTime] = pricetime
  218.         _values[PRC.uuid] = combine_pricelist[0][PRC.uuid]
  219.         _values[PRC.weight] = 0
  220.         weight_div = 0
  221.         newdict = {}
  222.  
  223.         for price in price_cycle:
  224.             newdict[price] = [0,0]
  225.  
  226.         for input in input_list:
  227.             for price in price_cycle:
  228.                 if input[price] != None and input[price] != 0:
  229.                     newdict[price][0] += (input[price] * input[PRC.weight])
  230.                     newdict[price][1] += input[PRC.weight]
  231.  
  232.         for price, valuelist in newdict.items():
  233.  
  234.             if valuelist[0] == 0 or valuelist[1] == 0:
  235.                 continue
  236.  
  237.             _values[price] = round(valuelist[0] / valuelist[1], 2)
  238.             _values[PRC.weight] += valuelist[1]
  239.             weight_div += 1
  240.  
  241.         for count, price in enumerate(price_cycle):
  242.             if _values[price] != None:
  243.                 _values[PRC.weight] = round(_values[PRC.weight] / weight_div)
  244.                 break
  245.             elif count+1 == len(price_cycle):
  246.                 good_job = False
  247.  
  248.         if len(executemany_list) > 0 and executemany_list[-1][PRC.uuid] == _values[PRC.uuid] and good_job == True:
  249.  
  250.             for price in price_cycle:
  251.                 if _values[price] == None and executemany_list[-1][price] != None:
  252.                     _values[price] = executemany_list[-1][price]
  253.  
  254.             if dict_count+1 < len(single_dict): # always inlcudes the most previous price without checking criteria
  255.  
  256.                 for count in range(2, len(price_cycle)):
  257.  
  258.                     price = price_cycle[count]
  259.  
  260.                     if _values[price] != None:
  261.  
  262.                         newprice = _values[price]
  263.  
  264.                         if executemany_list[-1][price] != None:
  265.  
  266.                             oldprice = executemany_list[-1][price]
  267.  
  268.                             if _values[price] > 100:
  269.                                 rv = price_guard(newprice, oldprice, 5.0)
  270.                             elif _values[price] > 10:
  271.                                 rv = price_guard(newprice, oldprice, 15.0)
  272.                             elif _values[price] >= 1:
  273.                                 rv = price_guard(newprice, oldprice, 30.0)
  274.                             elif _values[price] < 1:
  275.                                 rv = price_guard(newprice, oldprice, 75.0)
  276.  
  277.                             if rv == True:
  278.                                 break
  279.  
  280.                             elif rv == False and count == len(price_cycle)-1:
  281.                                 good_job = False
  282.  
  283.         if good_job == True:
  284.             executemany_list.append(tuple(_values))
  285.     return executemany_list
  286.  
  287. def extract_known_uuids(dict price_dict):
  288.     """
  289.    takes all data and sorts them i smart
  290.    order for speeding up the later processing
  291.    :param price_dict: all the uncut data
  292.    :return:
  293.    dictionary that replaces price_dict['data'] and a list
  294.    with all UUID's so that we'll know later which ones we
  295.    need to regather before deleting them all
  296.    """
  297.     cdef str current_uuid = 'NONE!', tmp_uuid
  298.     cdef list price_data, unique_uuid_list = []
  299.     cdef dict temp_dict = {'data': {}}
  300.     cdef tuple price_tuple
  301.     cdef list sort_cards = []
  302.     cdef int count
  303.  
  304.     pricecursor.execute('select * from prices where setCode is not NULL')
  305.     price_data = pricecursor.fetchall()
  306.  
  307.     if price_data != []:
  308.         price_data.sort(key=lambda x:x[PRC.setCode])
  309.  
  310.     for price_tuple in price_data:
  311.         if price_tuple[PRC.uuid] != current_uuid: # speeding trick
  312.             current_uuid = price_tuple[PRC.uuid]
  313.             unique_uuid_list.append(current_uuid)
  314.             if current_uuid in price_dict['data']:
  315.                 temp_dict['data'][current_uuid] = copy.copy(price_dict['data'][current_uuid])
  316.                 price_dict['data'].pop(current_uuid)
  317.  
  318.     for current_uuid in price_dict['data']:
  319.         mtgcursor.execute('select * from cards where uuid = (?)', (current_uuid,))
  320.         price_tuple = mtgcursor.fetchone()
  321.         if price_tuple != None:
  322.             sort_cards.append(price_tuple)
  323.  
  324.     if sort_cards != []:
  325.         sort_cards.sort(key=lambda x:x[MTG.cards.setCode])
  326.         for price_tuple in sort_cards:
  327.             current_uuid = price_tuple[MTG.cards.uuid]
  328.             temp_dict['data'][current_uuid] = copy.copy(price_dict['data'][current_uuid])
  329.  
  330.     return temp_dict, unique_uuid_list
  331.  
  332. cdef list mash_together_new_and_old_pricelist(list combine_pricelist, dict current_work, list values):
  333.     cdef list _values, suppliers_list = ['cardmarket', 'cardhoarder', 'tcgplayer']
  334.     cdef str PO, surface, human_date, supplier
  335.     cdef dict uuid_price
  336.     cdef float unixtime, price
  337.     cdef int pricekey = 0
  338.  
  339.     for PO in current_work:
  340.         for supplier in current_work[PO]:
  341.  
  342.             if supplier not in suppliers_list:
  343.                 continue
  344.  
  345.             try: uuid_price = current_work[PO][supplier]['retail']
  346.             except KeyError: continue
  347.  
  348.             for surface in uuid_price:
  349.                 _values = copy.copy(values)
  350.  
  351.                 for human_date, price in uuid_price[surface].items():
  352.  
  353.                     unixtime = time.mktime(datetime.strptime(human_date, "%Y-%m-%d").timetuple())
  354.  
  355.                     if len(combine_pricelist) > 0 and unixtime <= combine_pricelist[-1][PRC.unixTime]:
  356.                         continue
  357.  
  358.                     if supplier == 'cardmarket':
  359.  
  360.                         if surface == 'foil':
  361.                             pricekey = PRC.euFoil
  362.                         else:
  363.                             pricekey = PRC.euReg
  364.  
  365.                     elif supplier == 'tcgplayer':
  366.  
  367.                         if surface == 'foil':
  368.                             pricekey = PRC.usFoil
  369.                         else:
  370.                             pricekey = PRC.usReg
  371.                     elif supplier == 'cardhoarder':
  372.  
  373.                         if surface == 'foil':
  374.                             pricekey = PRC.mtgoFoil
  375.                         else:
  376.                             pricekey = PRC.mtgoReg
  377.  
  378.                     _values[PRC.unixTime] = unixtime
  379.                     _values[pricekey] = price
  380.  
  381.                     combine_pricelist.append(tuple(_values))
  382.  
  383.     return combine_pricelist
  384.  
  385. def gather_local_combine_pricelist(str uuid, list values, str current_setcode, object printer):
  386.     """
  387.    first looks into memoryconnection for inputs, if not it goes to priceconnection for one.
  388.    If one is found, its entire setcode from pricecursor will be the new prices in memoryconnection.
  389.    secondly setcode are'nt found it looks into memoryconnection for its uuid to find its setcode,
  390.    if not it cathces the entire setcode from MTGJson and make a new memoryconnection from that set.
  391.    :return: values and setcode + continue-bool
  392.    """
  393.     cdef list combine_pricelist = []
  394.     try:
  395.         memorycursor.execute('select * from prices where uuid = (?)', (uuid,))
  396.         combine_pricelist = memorycursor.fetchall()
  397.     except Error:
  398.         combine_pricelist = []
  399.     finally:
  400.         if combine_pricelist == []:
  401.             printer.from_memory = False
  402.             pricecursor.execute('select * from prices where uuid = (?)', (uuid,))
  403.             combine_pricelist = pricecursor.fetchall()
  404.  
  405.             if combine_pricelist != [] and combine_pricelist[0][PRC.setCode] != None:
  406.                 current_setcode = combine_pricelist[0][PRC.setCode]
  407.                 copy_sqlite_table_setcode(pricecursor, memoryconnection, memorycursor, 'prices', current_setcode)
  408.         else:
  409.             printer.from_memory = True
  410.  
  411.     if combine_pricelist == [] or combine_pricelist[0][PRC.setCode] == None:
  412.         try:
  413.             memorycursor.execute('select * from cards where uuid = (?)', (uuid,))
  414.             mtgdata = memorycursor.fetchone()
  415.  
  416.         except Error:
  417.             mtgdata = None
  418.  
  419.         finally:
  420.  
  421.             if mtgdata == None:
  422.                 printer.from_card_memory = False
  423.  
  424.                 mtgcursor.execute('select * from cards where uuid = (?)', (uuid,))
  425.                 mtgdata = mtgcursor.fetchone()
  426.                 if mtgdata == None:
  427.                     return combine_pricelist, values, current_setcode, False
  428.                 else:
  429.                     copy_sqlite_table_setcode(mtgcursor, memoryconnection, memorycursor, 'cards', mtgdata[MTG.cards.setCode])
  430.             else:
  431.                 printer.from_card_memory = True
  432.  
  433.             if mtgdata != None:
  434.                 current_setcode = mtgdata[MTG.cards.setCode]
  435.                 values[PRC.setCode] = current_setcode
  436.  
  437.                 if combine_pricelist != [] and combine_pricelist[0][PRC.setCode] == None:
  438.  
  439.                     with priceconnection:
  440.                         pricecursor.execute('update prices set setCode = (?) where uuid = (?)', (current_setcode, uuid,))
  441.  
  442.                     pricecursor.execute('select * from prices where uuid = (?)', (uuid,))
  443.                     combine_pricelist = pricecursor.fetchall()
  444.  
  445.     else:
  446.         values[PRC.setCode] = combine_pricelist[0][PRC.setCode]
  447.  
  448.     return combine_pricelist, values, current_setcode, True
  449.  
  450. def finaliaze_work(list uuidlist, list values, list timelist, list final_injectlist, str query):
  451.     cdef str uuid
  452.     cdef list combine_pricelist, execute_many_list, temp_list
  453.     cdef int count
  454.  
  455.     print('Injecting orphans:', len(uuidlist))
  456.     for uuid in uuidlist:
  457.         pricecursor.execute('select * from prices where uuid = (?)', (uuid,))
  458.         combine_pricelist = pricecursor.fetchall()
  459.  
  460.         if combine_pricelist == [] or combine_pricelist[0][PRC.setCode] == None:
  461.             continue
  462.  
  463.         values[PRC.uuid] = uuid
  464.         values[PRC.weight] = 1
  465.         values[PRC.setCode] = combine_pricelist[0][PRC.setCode]
  466.  
  467.         execute_many_list = price_masher(combine_pricelist, timelist, values)
  468.         final_injectlist += execute_many_list
  469.  
  470.     for count in range(len(final_injectlist)-1,-1,-1): # clears old sqlite ID!
  471.         if final_injectlist[count][PRC.setCode] == None:
  472.             final_injectlist.pop(count)
  473.             continue
  474.  
  475.         if final_injectlist[count][0] == None:
  476.             continue
  477.  
  478.         temp_list = list(final_injectlist[count])
  479.         temp_list[0] = None
  480.         final_injectlist[count] = tuple(temp_list)
  481.  
  482.     if final_injectlist != []:
  483.         final_injectlist.sort(key=lambda x:x[PRC.setCode])
  484.  
  485.         with priceconnection:
  486.             pricecursor.execute('delete from prices;')
  487.             pricecursor.executemany(query, final_injectlist)
  488.  
  489. def start_working_on_files(str unpack_location, list timelist):
  490.     """ the larger part of the process starts here """
  491.  
  492.     cdef list final_injectlist = [], values, uuidlist = []
  493.     cdef int count_count
  494.     cdef str uuid, query, current_setcode = ":NONE:"
  495.     cdef dict price_data, current_work
  496.     cdef bint carry_on
  497.  
  498.     query, values = tech.empty_insert_query(pricecursor, 'prices')
  499.  
  500.     with open(unpack_location, 'r') as raw_dump:
  501.         print('Loading dump:', unpack_location)
  502.         price_data = json.load(raw_dump)
  503.  
  504.         printer = PrinterClass()
  505.  
  506.         printer.total_count = len(price_data['data'])
  507.  
  508.         printer.take_time('start', True)
  509.         printer.take_time('minute', True)
  510.  
  511.         printer.take_time('query', True)
  512.         price_data, uuidlist = extract_known_uuids(price_data)
  513.         printer.take_time('query', False)
  514.  
  515.         printer.skipped =  printer.total_count - len(price_data['data'])
  516.  
  517.         printer.total_count = len(price_data['data'])
  518.  
  519.         for count, uuid in enumerate(price_data['data']):
  520.  
  521.             thread = Worker(partial(printer.output_results, count, uuid, current_setcode))
  522.             printer.threadpool.start(thread)
  523.  
  524.             values[PRC.uuid] = uuid
  525.             values[PRC.weight] = 1
  526.  
  527.             current_work = price_data['data'][uuid]
  528.  
  529.             # if uuid != "b9f2a87e-3b67-5547-8cca-91b6bd06b4f1":
  530.             #     continue
  531.  
  532.             printer.take_time('query', True)
  533.             combine_pricelist, values, current_setcode, carry_on = gather_local_combine_pricelist(uuid, values, current_setcode, printer)
  534.             printer.take_time('query', False)
  535.  
  536.             if carry_on == False:
  537.                 printer.skipped += 1
  538.                 continue
  539.  
  540.             printer.take_time('iter', True)
  541.             combine_pricelist = mash_together_new_and_old_pricelist(combine_pricelist, current_work, values)
  542.             printer.take_time('iter', False)
  543.  
  544.             if combine_pricelist == []:
  545.                 printer.skipped += 1
  546.                 continue
  547.  
  548.             printer.take_time('work', True)
  549.             execute_many_list = price_masher(combine_pricelist, timelist, values)
  550.             final_injectlist += execute_many_list
  551.             printer.take_time('work', False)
  552.  
  553.             printer.take_time('deleting', True)
  554.             for count_count in range(len(uuidlist)-1,-1,-1):
  555.                 if uuidlist[count_count] == uuid:
  556.                     uuidlist.pop(count_count)
  557.                     break
  558.             printer.take_time('deleting', False)
  559.  
  560.     finaliaze_work(uuidlist, values, timelist, final_injectlist, query)
  561.     printer.output_results(count, uuid, current_setcode)
  562.  
  563. cdef list make_timelist():
  564.     """
  565.    makes a list with time thresholds that price inputs will fall inbetween
  566.    :return: list with unixtimes
  567.    """
  568.     cdef float unixtime = time.mktime(datetime.strptime("2019-1-1", "%Y-%m-%d").timetuple())
  569.  
  570.     cdef float one_year = time.time() - (86400 * 365)
  571.     cdef float three_months = time.time() - (86400 * 90)
  572.     cdef float one_months = time.time() - (86400 * 30)
  573.     cdef float one_week = time.time() - (86400 * 7)
  574.     cdef float three_days = time.time() - (86400 * 3)
  575.     cdef float one_day = time.time() - 86400
  576.  
  577.     cdef list cycle = [
  578.         [unixtime, one_year, 86400*90],
  579.         [one_year, three_months, 86400*30],
  580.         [three_months, one_months, 86400*7],
  581.         [one_months, one_week, 86400*3],
  582.         [one_week, one_day, 86400]
  583.     ]
  584.  
  585.     cdef list timelist = [unixtime]
  586.  
  587.     cdef int count
  588.     for count in range(len(cycle)):
  589.         while timelist[-1] + cycle[count][2] < cycle[count][1]:
  590.             timelist.append(timelist[-1] + cycle[count][2])
  591.  
  592.     return timelist
  593.  
  594. def loading_raw_files():
  595.     """
  596.    prepeares local files and user
  597.    input decides if to be redownloaded
  598.    """
  599.     cdef str default_download_location = '/home/plutonergy/Downloads/AllPrices.json'
  600.     cdef str default_unpack_location = '/mnt/ramdisk/AllPrices.txt'
  601.     cdef str unpack_location = tempfile.gettempdir() + "/AllPrices.txt"
  602.     cdef str delete = 'n'
  603.  
  604.     print('Default download location: /home/plutonergy/Downloads/AllPrices.json pressing enter == NO CHANGE!')
  605.     cdef str download_to = input('Channge download location to: ')
  606.     cdef list timelist
  607.  
  608.     if download_to == "":
  609.         download_to = default_download_location
  610.  
  611.     if os.path.exists(download_to):
  612.         delete = input('File exists, would you like to redownload ' + download_to + ": ")
  613.         if delete.lower() == 'y':
  614.             os.remove(download_to)
  615.             print('Downloading https://mtgjson.com/api/v5/AllPrices.json to', download_to)
  616.             tech.download_file('https://mtgjson.com/api/v5/AllPrices.json', download_to)
  617.     else:
  618.         print('Downloading https://mtgjson.com/api/v5/AllPrices.json to', download_to)
  619.         tech.download_file('https://mtgjson.com/api/v5/AllPrices.json', download_to)
  620.  
  621.     if os.path.exists(download_to) == False:
  622.         print("Shit happened!")
  623.         sys.exit()
  624.  
  625.     if os.path.exists('/mnt/ramdisk'):
  626.         unpack_location = default_unpack_location
  627.  
  628.     if delete.lower() == 'y' or os.path.exists(unpack_location) == False:
  629.         if os.path.exists(unpack_location):
  630.             os.remove(unpack_location)
  631.  
  632.         with open(download_to, 'r') as raw:
  633.             print('Loading:', download_to)
  634.             load = json.load(raw)
  635.  
  636.         with open(unpack_location, "w") as file:
  637.             print('Dumping raw-data to:', unpack_location)
  638.             json.dump(load, file)
  639.  
  640.     timelist = make_timelist()
  641.     start_working_on_files(unpack_location, timelist)
Advertisement
Add Comment
Please, Sign In to add comment