-
Notifications
You must be signed in to change notification settings - Fork 2
tesseract_integration #656
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
HadronCollider
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Влейте сюда изменения по комментариям из #647
| while time.time() - start_time < self.max_wait_time: | ||
| task_result = AsyncResult(task_id) | ||
| if task_result.state == 'SUCCESS': | ||
| recognized_text = task_result.result | ||
| recognized_text = re.sub(r'\s+', ' ', recognized_text) | ||
| image.text = recognized_text | ||
| add_image_text(task_id, recognized_text) | ||
| return recognized_text.strip() | ||
| time.sleep(1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
кажется, подобный подход ожидания не самый лучший (мы по факту блокируем всю проверку / очередь) - можно ли сделать "заглушку" (по типу фидбека "проверяется" в этой проверке), а в celery-задаче с тессерактом после распознавания и обработки - обновлять данные в БД проверки? но стоит добавить какую-то проверку, не слишком ли долго тессеракт обрабатывает картинку или вообще её не выполнил (чтобы обновить фидбек/результат критерия в соответствии со сложившейся ситуацией)
app/routes/tasks.py
Outdated
| 'is_failed': False, | ||
| 'params_for_passback': current_user.params_for_passback | ||
| 'params_for_passback': current_user.params_for_passback, | ||
| 'tesseract_result': -1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Чтобы не "обременять" модель проверки результатом тессеракта (он вероятно может быть большим и конкретно к проверке может не относиться - это больше характеристика файла) - вынесите в отдельную коллекцию - в неё же будет писать celery-задача и смотреть задачи по проверке - так же уйдут заполнения поля -1 и получением данных из бд на этапе формирования check
связь по check id
app/tesseract_tasks.py
Outdated
| } | ||
|
|
||
| @celery.task(name="tesseract_recognize", queue='tesseract-queue', bind=True, max_retries=MAX_RETRIES, soft_time_limit=TASK_SOFT_TIME_LIMIT) | ||
| def tesseract_recognize(self, check_id): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
при подобном запуске теряется возможность устанавливать параметры из критерия - остаются только захардкоженые from main.checks.report_checks.image_text_check import SYMBOLS_SET, MAX_SYMBOLS_PERCENTAGE, MAX_TEXT_DENSITY
может быть можно запускать эту задачу из критерия, а не при извлечении изображений / загрузке файла, либо собирать только информацию по анализу изображений, а формировать полноценный фидбек в самом критерии?
(при втором варианте появляется зависимость от скорости работы тессеракта - "успеет ли он обработать изображения до начала проверки по критерию" плюс не совместим с текущим асинхронным подходом к обработке тессеракта -- поэтому насчет него не уверен)
| if self.laplacian_score < self.min_laplacian: | ||
| deny_list.append(f"Изображение с подписью '{img.caption}' имеет низкий показатель лапласиана: {self.laplacian_score} (минимум {self.min_laplacian}).<br>") | ||
|
|
||
| if self.entropy_score < self.min_entropy: | ||
| deny_list.append(f"Изображение с подписью '{img.caption}' имеет низкую энтропию: {self.entropy_score} (минимум {self.min_entropy}).<br>") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
HadronCollider
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Пока оставил комментарии только по модели - остальной код по мере обновлений / необходимости
Одна из мыслей - расширить данные о файле (сейчас она почти не используется и поверхностная), добавив туда агрегированные данные по всем изображениям в нем ()
| is_failed = none_to_false(self.is_failed) # None for old checks => False, True->True, False->False | ||
| return {'is_ended': is_ended, 'is_failed': is_failed} | ||
|
|
||
| class Image(PackableWithId): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мы планируем уйти от PackableWithId в сторону "нормальной" mongo document model (с указанием типов полей и прочего), поэтому предлагаю новые модели делать с помощью них (поддержав нужны операции)
| def __init__(self, dictionary=None): | ||
| super().__init__(dictionary) | ||
| dictionary = dictionary or {} | ||
| self.check_id = dictionary.get('check_id') # Привязка к check_id |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Возможно тут стоит сохранять и id документа - 99% уверенности, что у него сейчас ID одинаковый с проверкой, но в будущем возможны изменения (и тогда документ будет, например, один, а проверок с ним несколько), сохранить изображения хватит один раз именно для документа
| dictionary = dictionary or {} | ||
| self.check_id = dictionary.get('check_id') # Привязка к check_id | ||
| self.caption = dictionary.get('caption', '') # Подпись к изображению | ||
| self.image_data = dictionary.get('image_data') # Файл изображения в формате bindata |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Полезный момент на будущее - добавить checksum на случай дубликатов (чтобы одна одинаковая фотка в 100 отправок / отчетах нам не занимала лишнее место и ресурсы на обработку)
| self.caption = dictionary.get('caption', '') # Подпись к изображению | ||
| self.image_data = dictionary.get('image_data') # Файл изображения в формате bindata | ||
| self.image_size = dictionary.get('image_size') # Размер изображения в сантимерах | ||
| self.text = dictionary.get('text', None) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Возможно, обсуждали это ранее - есть мысли, что требующиеся нам метрики изображений (читаемость, плотность текста, пр) стоит сделать сразу при распознавании и хранить либо в документе изображения (как и сам полученный текст), либо в отдельной коллекции

No description provided.