7

Пишу телеграмм бота, который распознаёт текст с картинки. Тестировал его на Windows, всё работает отлично. Но при переходе на Linux, tesseract выдаёт исключение.

Код самого бота:

from telebot import types
from googlesearch import search
from PIL import Image
import pytesseract
import cv2
import os
import numpy as np
import telebot
import config
 
from telebot import types
 
bot = telebot.TeleBot(config.token)

@bot.message_handler(content_types= ["photo"])

def answer_to_photo(message):
    statuss = ['creator', 'administrator', 'member']
    user_status = str(bot.get_chat_member(chat_id='(Здесь всё хорошо)', user_id=message.from_user.id).status)    
    if user_status in statuss:
        pytesseract.pytesseract.tesseract_cmd = r'/home/shalor/.local/bin/pytesseract'

        file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        src = r'photo' + message.photo[1].file_id
        with open(src, 'wb') as new_file:
            new_file.write(downloaded_file)
        bot.reply_to(message, 'Над вашим фото происходит колдовство...')

        image = src

        preprocess = "thresh"

        image = cv2.imread(image)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        if preprocess == "tresh":
            gray = cv2.threshold(gray, 0, 255,
                cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

        elif preprocess == "blur":
            gray = cv2.median.Blur(gray, 3)

        filename = "{}.png".format(os.getpid())
        cv2.imwrite(filename, gray)

        text = pytesseract.image_to_string(Image.open(filename), lang = 'rus')
        os.remove(filename)
        os.remove(src)

        for j in search(text, tld="co.in", num=10, stop=1, pause=2):
                needed_url = j
        if len(text) > 0:
            keyboard = types.InlineKeyboardMarkup()
            first_url_button = types.InlineKeyboardButton(text="Перейти на сайт", url=needed_url)
            search_url_button = types.InlineKeyboardButton(text="Перейти на запрос в поисковике", url='https://yandex.ru/search/?text=' + text)
            keyboard.add(first_url_button, search_url_button)
            bot.send_message(message.chat.id, "Вот ваши ссылки:", reply_markup=keyboard)

Исключение:

2020-11-14 21:15:16,752 (util.py:68 WorkerThread1) ERROR - TeleBot: "TesseractError occurred, args=(2, 'Usage: pytesseract [-l lang] input_file')
Traceback (most recent call last):
  File "/home/shalor/.local/lib/python3.8/site-packages/telebot/util.py", line 62, in run
    task(*args, **kwargs)
  File "main_bot_for_server.py", line 69, in answer_to_photo
    text = pytesseract.image_to_string(Image.open(filename), lang = 'rus')
  File "/home/shalor/.local/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 356, in image_to_string
    return {
  File "/home/shalor/.local/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 359, in <lambda>
    Output.STRING: lambda: run_and_get_output(*args),
  File "/home/shalor/.local/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 270, in run_and_get_output
    run_tesseract(**kwargs)
  File "/home/shalor/.local/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 246, in run_tesseract
    raise TesseractError(proc.returncode, get_errors(error_string))
pytesseract.pytesseract.TesseractError: (2, 'Usage: pytesseract [-l lang] input_file')
"

1 ответ 1

8
+50

Похоже вы забыли установить бинарники самого tesseract-ocr в директорию /home/shalor/.local/bin.

Питоновский модуль pytesseract является не более чем оберткой для удобного вызова пакета Tesseract OCR, который должен быть установлен в системе для полноценной работы pytesseract. Другими словами pytesseract не может сам распознавать текст если в системе (OS) не установлен пакет софта Tesseract OCR.

pytesseract.pytesseract.tesseract_cmd - полный путь, который должен указывать на исполняемый (бинарный) файл пакета Tesseract OCR, а не на питоновский модуль-обертку pytesseract.

2
  • 1
    Спасибо вам огромное, я работал над этим проектом полгода, и благодаря вам он наконец завершён, действительно, огромное вам спасибо
    – shalor1k
    24 ноя 2020 в 11:07
  • 1
    @shalor1k, всегда рад помочь :) 24 ноя 2020 в 11:09

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.