Beispiel #1
0
def store_bot_data(tg_id, image_link, latitude, longitude):
    md_from_coordinates = MetaDataFromCoordinates(latitude, longitude)
    company_name = md_from_coordinates.get_name()
    address = md_from_coordinates.get_address()

    session = session_maker()
    stored_data = db_store_start(session, tg_id, image_link, company_name, address)

    recognized_info = digit_to_price(image_link).split(',')
    is_recognized=recognized_info[0]
    if is_recognized:
        rec_fuel_type = recognized_info[1]
        is_premium = TMP_IS_PREMIUM
        fuel = db_get_fuel(session, rec_fuel_type, is_premium)
        if fuel is None:
            return "There isn't a fuel {} in database".format(rec_fuel_type)

        if recognized_info[2].replace('.', '', 1).isdigit():
            rec_price = float(recognized_info[2])
            recognition_result = namedtuple('rec_result', ['is_recognized', 'fuel_type', 'price'])
            rr = recognition_result(is_recognized, rec_fuel_type, rec_price)

            location_result = namedtuple('loc_result', ['gas_station', 'is_from_metadata'])
            lr = location_result(stored_data['gas_station'].id, TMP_IS_FROM_METADATA)
            db_store_recognized(session, stored_data['image'], rr, lr)
        else:
            return "{} is not a float number".format(recognized_info[2])
    else:
        return 'photo is not recognized'
    session.close()
    return 'Ok'
Beispiel #2
0
def store_bot_data(telegram_id, image_link, company_name, address, lat, lng):
    # TODO maybe refactor with 1 argument - dict?
    # TODO put in database GPS coordinates

    is_recognized, rec_fuel_type, price = digit_to_price(image_link)

    session = session_maker()
    stored_data = db_store_start(session, telegram_id, image_link,
                                 company_name, address)

    if is_recognized:
        is_premium = TMP_IS_PREMIUM
        fuel = db_get_fuel(session, rec_fuel_type, is_premium)
        if fuel is None:
            return "There isn't a fuel {} in database".format(rec_fuel_type)

        if price.replace('.', '', 1).isdigit():
            rec_price = float(price)
            recognition_result = namedtuple(
                'rec_result', ['is_recognized', 'fuel_type', 'price'])
            rr = recognition_result(is_recognized, rec_fuel_type, rec_price)

            location_result = namedtuple('loc_result',
                                         ['gas_station', 'is_from_metadata'])
            lr = location_result(stored_data['gas_station'],
                                 TMP_IS_FROM_METADATA)
            update_image(session, stored_data['image'], rr, lr)
        else:
            return "{} is not a float number".format(price)
    else:
        return 'photo is not recognized'
    session.close()
    return f'Ok! \nA{rec_fuel_type}: {price} грн'
Beispiel #3
0
def sign_up():
    username = request.form['username']
    password = request.form['password']
    new_session = session_maker()
    error = None

    if not (username or password):
        error = "You need to fill all of required fields."
    if get_or_none(new_session, User, username) is not None:
        error = f"User with a name '{username}' already exists."
    else:
        new_user = User(username=username, password_hash=generate_password_hash(password))
        try:
            new_session.add(new_user)
            new_session.commit()
        except:
            new_session.rollback()
            error = "Sorry, an error occurred during the transaction of user's information to the database. " \
                    "Please, try again."
        finally:
            new_session.close()
        return redirect(url_for('api.sign_in'))

    flash(error)
    return render_template('sign_up.html')
Beispiel #4
0
def data_from_db(bot, update, user_data):
    bot.answer_callback_query(callback_query_id=update.callback_query.id)
    bot.edit_message_text(chat_id=update.effective_message.chat_id,
                          message_id=user_data['start_msg_id'],
                          text="processing...")
    session = session_maker()
    response = query_all_price_period(session)
    session.close()
    user_data['db_output'] = query_to_list(response)
    user_data['gas_per_msg'] = 2
    user_data['position'] = 0
    return pagination(bot, update, user_data)
Beispiel #5
0
def sign_up():
    if current_user.is_authenticated:
        return redirect(url_for('ui.prices'))
    form = SignUpForm(meta={'csrf': False})
    if form.validate_on_submit():
        user = User(username=form.username.data)
        user.set_password(form.password.data)
        session = session_maker()
        session.add(user)
        session.commit()
        session.close()
        flash("Registration successful. Please, sign in now.")
        return redirect(url_for('auth.sign_in'))
    return render_template('auth/register.html', form=form)
Beispiel #6
0
def filters_change(bot, update, user_data):
    bot.answer_callback_query(callback_query_id=update.callback_query.id)
    query = update.callback_query

    if query.data == 'date':
        keyboard = [[InlineKeyboardButton(text='Specific Date', callback_data='spec_date')],
                    [InlineKeyboardButton(text='Date range', callback_data='date_range')]]
        bot.edit_message_text(chat_id=update.effective_message.chat_id,
                              message_id=user_data['start_msg_id'],
                              text="One day or range?",
                              reply_markup=InlineKeyboardMarkup(keyboard))
        return DATE_OR_RANGE
    elif query.data == 'selected_companies':
        session = session_maker()
        response = list_fuel_company_names(session)
        session.close()
        response = list(set(response))
        user_data['response'] = response
        return selector(bot, update, user_data, response, query.data)
    elif query.data == 'selected_fuels':
        session = session_maker()
        response = list_fuels(session)
        session.close()
        response = list(set(response))
        user_data['response'] = response
        return selector(bot, update, user_data, response, query.data)
    elif query.data == 'stat_func':
        keyboard = [[InlineKeyboardButton(text='Max', callback_data='max')],
                    [InlineKeyboardButton(text='Average', callback_data='avg')],
                    [InlineKeyboardButton(text='Min', callback_data='min')],
                    ]
        bot.edit_message_text(chat_id=update.effective_message.chat_id,
                              message_id=user_data['start_msg_id'],
                              text="Choose statistic function:",
                              reply_markup=InlineKeyboardMarkup(keyboard))
        return STAT_FUNCTION
Beispiel #7
0
def sign_in(username, password):
    username = request.form['username']
    password = request.form['password']
    new_session = session_maker()
    error = None
    user = new_session.query(User.username, User.password_hash).filter(User.username == username).first()

    if user is None:
        error = "User doesn't exist."
    elif not(check_password_hash(user['password_hash'], password)):
        error = "Incorrect password."
    else:
        return redirect(url_for('homepage'))

    flash(error)
    return render_template('sign_in.html')
Beispiel #8
0
def fake():
    """ create fake instances in database """
    import random
    from itertools import chain
    from faker import Faker
    from database.queries import get_or_create
    from database.db_connection import session_maker
    from database.models import (User, FuelCompany, Fuel, GasStation, Images,
                                 Price)

    fake = Faker()
    session = session_maker()

    tg_uids = random.sample(list(range(10_000)), 5)
    users = [get_or_create(session, User, tg_id=uid) for uid in tg_uids]

    fuel_company_names = [fake.company() for _ in range(3)]
    companies = [get_or_create(session, FuelCompany, fuel_company_name=n)
                 for n in fuel_company_names]

    fuel_marks = ['92', '98', '95', '80']
    fuels = [get_or_create(session, Fuel, fuel_type=f, is_premium=False)
             for f in fuel_marks]

    addresses = [fake.address() for _ in range(10)]
    gas_stations = [get_or_create(session, GasStation, address=a,
                                  fuel_company_id=random.choice(companies).id)
                    for a in addresses]

    links = [fake.image_url(width=500, height=400) for _ in range(10)]
    recognized = [fake.pybool() for _ in range(10)]
    metadata = [fake.pybool() for _ in range(10)]
    images = [get_or_create(session, Images, link=l, is_recognized=r,
                            is_from_metadata=m)
              for l, r, m in zip(links, recognized, metadata)]

    prices = [get_or_create(session, Price, price=random.uniform(0, 99),
                            gas_station_id=random.choice(gas_stations).id,
                            fuel_id=random.choice(fuels).id,
                            images_id=i.id)
              for i in images]

    for entity in chain(users, companies, fuels, gas_stations, images, prices):
        session.add(entity)

    session.commit()
Beispiel #9
0
def sign_in():
    if current_user.is_authenticated:
        return redirect(url_for('ui.prices'))
    form = SignInForm(meta={'csrf': False})
    if form.validate_on_submit():
        session = session_maker()
        user = session.query(User).filter(
            User.username == form.username.data).first()
        session.close()
        if user is None or not user.check_password(form.password.data):
            flash("Invalid username and/or password")
            return redirect(url_for('auth.sign_in'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('ui.prices')
        return redirect(next_page)
    return render_template('auth/login.html', form=form)
Beispiel #10
0
def store_bot_data(telegram_id, image_link, image_path, company_name, address):
    # TODO maybe refactor with 1 argument - dict?
    # TODO put in database GPS coordinates
    session = session_maker()
    stored_data = db_store_start(session, telegram_id, image_path,
                                 company_name, address)
    recognition_tuple = get_recognition_tuple(company_name, image_link)
    if isinstance(recognition_tuple[0], bool):
        count_tuple = 1
    else:
        count_tuple = len(recognition_tuple)

    res_str = ''
    recognition_result = namedtuple('rec_result',
                                    ['is_recognized', 'fuel_type', 'price'])
    location_result = namedtuple('loc_result',
                                 ['gas_station', 'is_from_metadata'])
    for row in range(count_tuple):
        if count_tuple == 1:
            is_recognized, rec_fuel_type, price = recognition_tuple
        else:
            is_recognized, rec_fuel_type, price = recognition_tuple[row]
        if is_recognized:
            if price.replace('.', '', 1).isdigit():
                rec_price = float(price)
                rr = recognition_result(is_recognized, rec_fuel_type,
                                        rec_price)
                lr = location_result(stored_data['gas_station'],
                                     TMP_IS_FROM_METADATA)
                try:
                    update_image(session, stored_data['image'], rr, lr)
                except RuntimeError:
                    res_str = res_str + f"there isn't a fuel {rec_fuel_type} \n"
                else:
                    res_str = res_str + f'{rec_fuel_type}: {price} uah \n'
            else:
                res_str = res_str + f'{price} is not a float number \n'
        else:
            res_str = res_str + 'string is not recognized \n'
    session.close()
    return res_str
Beispiel #11
0
from flask_restplus import Api, Resource, reqparse

from database.db_connection import session_maker
from database.db_query_bot import (query_by_station_min_price,
                                   query_by_station_current_date,
                                   query_avg_all_stations,
                                   query_all_price_period,
                                   query_avg_price_period)
from processor.imageMetadata.coordinates_metadata import gasStationInfo
from services.service_data import upload_image_to_dbx
from stella_api import helpers

restful = Blueprint('restful', __name__, url_prefix='/restful')
api = Api(restful, doc='/docs')

session = session_maker()


def get_date_param(cur_request, name):
    date_param = cur_request.args.get(name, None)
    if date_param:
        date_param = datetime.strptime(date_param, '%d-%m-%Y').date()
    return date_param


def make_response_json(cur_dict):
    json_data = json.dumps(cur_dict,
                           default=helpers.to_serializable,
                           ensure_ascii=False)
    resp = make_response(json_data)
    resp.mimetype = 'application/json'
Beispiel #12
0
 def validate_username(self, username):
     session = session_maker()
     user = session.query(User).filter(
         User.username == username.data).first()
     if user is not None:
         raise ValidationError('User with such name already exists.')