def set_logger(): # Логи telebot.logger.setLevel(logging.INFO) fileh = logging.FileHandler(env.get('LOG_PATH'), 'a') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fileh.setFormatter(formatter) telebot.logger.addHandler(fileh)
def main(): bot = telebot.TeleBot(env.get('TELEGRAM_API_TOKEN')) set_logger() conn = sqlite3.connect(env.get('DATABASE_PATH'), check_same_thread=False, isolation_level=None) cursor: sqlite3.Cursor = conn.cursor() init_db(cursor) none_controller = NoneController(bot) receipt_controller = ReceiptController(bot, cursor) menu = [ receipt_controller.get_menu_btn() ] main_controller = MainController(bot, menu, cursor) bot.skip_pending = True bot.polling(none_stop=True, interval=0)
def _save_receipt(self, mime_type: str, file_id: str) -> Optional[str]: if str(mime_type).index("image") != -1: file_id = file_id file_info = self._bot.get_file(file_id) download_path = env.get('STORAGE_PATH') + '/receipts' downloaded_file = self._bot.download_file(file_info.file_path) download_path = f'{download_path}/{file_id}.jpg' with open(download_path, 'wb') as new_file: new_file.write(downloaded_file) return download_path return None
def parse_data( path: str ) -> Tuple[Optional[float], Optional[str], City, Union[datetime, str]]: client = vision.ImageAnnotatorClient() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.text_detection(image=image) texts = response.text_annotations amount = None weights = [] city_address = '' start_write_address = False count_addresses = 0 receipt_datetime: Optional[datetime] = None for idx, text in enumerate(texts): if text.description.find('-') != -1 and idx != 0: try: date = text.description date = str(date).replace('28', '20') receipt_datetime = datetime.strptime( f'{date} {texts[idx + 1].description}', '%d-%m-%Y %H:%M:%S') except ValueError: pass if text.description.upper() == 'CYMA' \ or text.description.upper() == 'СУМА' \ or text.description.upper() == 'СУНА' \ or text.description.upper() == 'КАРТКА': try: amount = float(texts[idx + 1].description.replace( ',', '.')) except ValueError: pass elif idx < 10: weights.append(is_shop_name(text.description)) if text.description.upper() == 'M.' or text.description.upper( ) == 'Н.': start_write_address = True elif count_addresses == 4: start_write_address = False if start_write_address: count_addresses += 1 city_address += text.description + ' ' max_weight = 0.0 shop_name = None for weight in weights: for name in weight: if weight[name] > max_weight: max_weight = weight[name] shop_name = name api_key = env.get('GOOGLE_MAPS_API_KEY') city = City() if len(city_address) > 0: response = requests.get( url= f'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={city_address}&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key={api_key}' ) if 200 <= response.status_code <= 299: resp_dict = response.json() if resp_dict['status'] == 'OK' and len( resp_dict['candidates']) > 0: city.address = resp_dict['candidates'][0][ 'formatted_address'] city.location.lat = resp_dict['candidates'][0][ 'geometry']['location']['lat'] city.location.lng = resp_dict['candidates'][0][ 'geometry']['location']['lng'] return amount, shop_name, city, receipt_datetime
import io import os import difflib import requests import math from datetime import datetime from models.receipt_model import City, Point, Receipt from views.receipt_view import ReceiptView as View from models.receipt_model import ReceiptModel as Model from repositories.exceptions import CantDetectReceipt from controllers.message_controller import MsgController as Msg os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = env.get( 'GOOGLE_APPLICATION_CREDENTIALS') class ReceiptController(BaseController): def callback_name(self, additive: str = '') -> str: return f'rc_{additive}' def get_menu_btn(self) -> InlineKeyboardButton: return InlineKeyboardButton(text="История заказов", callback_data=self.callback_name()) def _save_receipt(self, mime_type: str, file_id: str) -> Optional[str]: if str(mime_type).index("image") != -1: file_id = file_id file_info = self._bot.get_file(file_id) download_path = env.get('STORAGE_PATH') + '/receipts'