def _test_one_model(mdl_dir: Path, left_context: int, right_context: int) -> float: """Convert one model and check output. Args: mdl_dir: model dir for test. left_context: left context of kaldi model. right_context: right context of kaldi model. Returns: max err percent between tensorflow pb output and kaldi output. """ feat_input = np.loadtxt(str(mdl_dir / 'input.txt'), dtype=np.float32) feat_ivector = np.loadtxt(str(mdl_dir / 'ivector.txt'), dtype=np.float32) kaldi_output = np.loadtxt(str(mdl_dir / 'output.txt'), dtype=np.float32) feed_dict = {'input:0': feat_input, 'ivector:0': feat_ivector} with TemporaryDirectory() as tmp_dir: pb_file = Path(tmp_dir) / 'tf.pb' converter = Converter(mdl_dir / 'final.txt', left_context, right_context) converter.convert('tf', pb_file) tf.compat.v1.reset_default_graph() with tf.compat.v1.Session() as session: with gfile.FastGFile(str(pb_file), 'rb') as pb_file: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(pb_file.read()) tf.import_graph_def(graph_def, name="") out_tensor = session.graph.get_tensor_by_name('output.affine:0') output = session.run(out_tensor, feed_dict) return np.amax(np.absolute(np.subtract(output, kaldi_output)))
def convertResolution(self): all_ISINs = list(self.getAllUniqueIsin()) counter = 0 for isin in all_ISINs: converter = Converter() converter.convert(self.session, isin, ActionHour, 9, ActionDay) # converter.convert(self.session, isin, Action, 60, ActionHour) # converter.convert(self.session, isin, Action, 30, Action30Minutes) # converter.convert(self.session, isin, Action, 10, Action10Minutes) counter += 1 print "[+] {0} done {1}/{2}".format(isin, counter, len(all_ISINs))
def test_conversion(self): converter = Converter(ExchangeRateApi()) result = float(converter.convert(1, "EUR", "USD")) url = "https://api.exchangerate.host/latest" test_exchange_rates = StubExchangeRateApi(url) stub = test_exchange_rates.get_rates() self.assertAlmostEqual(result, float(stub["rates"]["USD"]), 4)
def get(): if request.args.get('amount') is not None: if request.args.get('input_currency') is not None and request.args.get('output_currency') is not None: try: # If all arguments are present converter = Converter(float(request.args.get('amount')), request.args.get('input_currency'), request.args.get('output_currency')) return jsonify(converter.convert()), status.HTTP_200_OK except (RatesNotAvailableError, TooManyInputCurrencies, ValueError) as e: return json.dumps({'error': str(e)}), status.HTTP_400_BAD_REQUEST elif request.args.get('input_currency') is not None: try: # If output_currency is ommited converter = Converter(float(request.args.get('amount')), request.args.get('input_currency'), None) return jsonify(converter.convert()), status.HTTP_200_OK except (RatesNotAvailableError, TooManyInputCurrencies, ValueError) as e: return json.dumps({'error': str(e)}), status.HTTP_400_BAD_REQUEST else: return jsonify({'error': 'Input argument was not set.'}), status.HTTP_400_BAD_REQUEST else: return jsonify({'error': 'Amount was not specified in parameters.'}), status.HTTP_400_BAD_REQUEST
def test_conversion(self, mock_rates): amount = 100.0 input_currency = 'EUR' output_currency = 'CZK' converter = Converter(amount, input_currency, output_currency) try: result = converter.convert() self.assertListEqual(list(result.get('output').values()), [2512.0]) except RatesNotAvailableError: self.assertTrue( False, 'Conversion failed. Should not have raised an exception.')
def test_correct_json_format_contains_input_and_output_fields(self): amount = 100.5 input_currency = 'CAD' output_currency = 'CZK' converter = Converter(amount, input_currency, output_currency) try: result = converter.convert() self.assertListEqual(list(result.keys()), ['input', 'output'], msg='Result json should contain input, and ' 'output fields.') except RatesNotAvailableError: self.assertTrue( False, 'Conversion failed. Should not have raised an exception.')
class Api(object): def __init__(self): self.converter = Converter() @cherrypy.expose def index(self): return "<h1>Api Root</h1><p>Available API Functions:</p>.../api/list and .../api/convert_value" @cherrypy.expose @cherrypy.tools.json_out() def convert_value(self, de, para, valor): #TODO: MAKE CHECKING FOR CORRECT DATA TYPES WORK output = { 'errors': "Undefined", 'success': "Undefined", 'value': "Undefined" } #BUG: value comming in from ajax call is not int, float or str ?! # makes it impossible to check if de is None or not de or para is None or not para or valor is None or not valor: errors = [] output['success'] = False if not de: errors.append("Invalid FROM option was inputted!") if not para: errors.append("Invalid TO option was inputted!") if not valor: errors.append("Invalid value was inputted!") output['errors'] = errors else: output['errors'] = 'No errors' output['success'] = True output['value'] = self.converter.convert(de, para, valor) return output @cherrypy.expose @cherrypy.tools.json_out() def list(self): output = { 'errors': 'No errors', 'success': "Undefined", 'rate_list': "Undefined" } output['rate_list'] = self.converter.list() output['success'] = True return output
def test_correct_json_format_output_field(self): amount = 100.5 input_currency = 'CAD' output_currency = '$' converter = Converter(amount, input_currency, output_currency) try: result = converter.convert() self.assertListEqual( list(result.get('output').keys()), ['AUD', 'CAD', 'MXN', 'NZD', 'SGD', 'USD'], msg='Result json input field should contain keys: ' '"AUD", "CAD", "MXN", "NZD", "SGD", "USD"') except RatesNotAvailableError: self.assertTrue( False, 'Conversion failed. Should not have raised an exception.')
def test_failed_conversion(self): converter = Converter(ExchangeRateApi()) result = converter.convert("", "USD", "EUR") self.assertEqual(result, False)
class UI: def __init__(self, root): self._root = root self._amount = IntVar() self._ran = False self._root.bind('<Return>', self._run_convert) self.default_from_curr = StringVar() self.default_from_curr.set("EUR") self.default_to_curr = StringVar() self.default_to_curr.set("USD") self.font_style = font.Font(family="Futura", size=10) self.style = ttk.Style() self.style.configure('TButton', font=self.font_style) self.converter = Converter(ExchangeRateApi()) self.currencies = self.converter.currencies def start(self): image = Image.open("./src/images/background.jpg") self.background = ImageTk.PhotoImage(image) self.background_label = ttk.Label(master=self._root, image=self.background) self._from_curr_menu = ttk.Combobox( master=self._root, textvariable=self.default_from_curr, values=self.currencies) self._to_curr_menu = ttk.Combobox(master=self._root, textvariable=self.default_to_curr, values=self.currencies) self._swap_currencies_button = ttk.Button( master=self._root, text="<>", command=self._swap_currencies) self._amount = ttk.Entry(master=self._root) self._convert_button = ttk.Button(master=self._root, text="Convert", command=self._run_convert) self._from_curr_menu.configure(font=self.font_style) self._to_curr_menu.configure(font=self.font_style) self._swap_currencies_button.configure(style="TButton") self._convert_button.configure(style="TButton") self.background_label.place(x=0, y=0) self._from_curr_menu.grid(row=0, column=0, sticky=(constants.W), padx=20, pady=20) self._swap_currencies_button.grid(row=0, column=1, padx=20, pady=20) self._to_curr_menu.grid(row=0, column=2, sticky=(constants.E), padx=20, pady=20) self._amount.grid(row=1, column=1, pady=20) self._convert_button.grid(row=2, column=1, pady=20) self._root.grid_columnconfigure(1, weight=1, minsize=300) def _run_convert(self, event=None): count = self._amount.get() from_curr = self._from_curr_menu.get() to_curr = self._to_curr_menu.get() try: count = float(count) except: messagebox.showinfo( "Error", "Wrong input, format input like this: 12.5 (not 12,5 €)") return self.result = self.converter.convert(count, from_curr, to_curr) output = f"{self.result} {to_curr}" date = f"as of {self.converter.date()}" if self._ran: self.result_label.destroy() self.date_label.destroy() self._ran = True self.result_label = ttk.Label(master=self._root, text=output) self.date_label = ttk.Label(master=self._root, text=date) self.copy_button = ttk.Button(master=self._root, text="Copy", command=self._copy_to_clipboard) self.result_label.configure(font=self.font_style) self.date_label.configure(font=self.font_style) self.copy_button.configure(style="TButton") self.result_label.grid(row=3, column=1, pady=20) self.date_label.grid(row=4, column=1) self.copy_button.grid(row=5, column=1, pady=20) def _copy_to_clipboard(self): self._root.clipboard_clear() self._root.clipboard_append(self.result) messagebox.showinfo("", "Copied to clipboard!") def _swap_currencies(self): current_from = self._from_curr_menu.get() current_to = self._to_curr_menu.get() self.new_from = StringVar() self.new_from.set(current_to) self.new_to = StringVar() self.new_to.set(current_from) self._from_curr_menu.destroy() self._to_curr_menu.destroy() self._from_curr_menu = ttk.Combobox(master=self._root, textvariable=self.new_from, values=self.currencies) self._to_curr_menu = ttk.Combobox(master=self._root, textvariable=self.new_to, values=self.currencies) self._from_curr_menu.configure(font=self.font_style) self._to_curr_menu.configure(font=self.font_style) self._from_curr_menu.grid(row=0, column=0, sticky=(constants.W), padx=20, pady=20) self._to_curr_menu.grid(row=0, column=3, sticky=(constants.E), padx=20, pady=20)