Google text recognition python

Speech AI с Python & Google API

Совсем недавно пришла в голову идея сделать «говорилку» на русском языке. В голове была простенькая схема наподобие:

1) Распознать речь с микрофона
2) Придумать более — менее разумный ответ.
В этом пункте можно сделать много интересного.
Например реализовать управление чем — нибудь физическим и не очень.
3) Преобразовать этот самый ответ в речь и воспроизвести.

Самое интересное, что для всех этих пунктов нашлись библиотеки под Python, чем я и воспользовался.

В итоге получилась связка, практически не зависящая от выбранного в качестве разговорного языка.

Распознавание речи

SpeechRecognition

Эта библиотека представляет из себя обвертку над многими популярными сервисами / библиотеками распознавания речи.
Т.к. из всех представленных в списке библиотеки сервисов первым заработал Google Speech Recognition, им я и воспользовался в дальнейшем.

Обработка речи

ChatterBot

Библиотека использует методы машинного обучения. Обучение происходит на наборах данных в формате диалогов.

Процесс обучения в библиотеке chatterbot

В качестве источников данных для обучения могут выступать файлы такого простого формата
По сути они представляют из себя набор диалогов в виде:

Для английского языка там есть хороший набор обучающих классов, один из которых берет диалоги из Ubuntu Dialog Corpus, а другой из Twitter’a.

К сожалению, для русского языка я не нашел альтернатив Ubuntu Dialog Corpus (такого же объема). Хотя тот же TwitterTrainer должен работать.

В порядке эксперимента я попробовал использовать при обучении диалоги из первого тома Воины и Мира.

Получилось забавно, но малоправдоподобно, т.к. диалоги там зачастую направленные на определенных персонажей романа.

Так как без большого количества данных сложно получить из бота интересного собеседника, в данный момент поиск хорошей базы для диалогов продолжается.

Еще библиотека chatterbot предоставляет набор «Логических модулей» (LogicAdapter). При помощи которых можно например фильтровать ответ, научить бота считать или говорить текущее время.

Библиотека довольно гибкая, позволяет писать свои классы для обучения и логические модули.

Синтезирование и воспроизведение речи

Google Text to Speech

Эта библиотека умеет преобразовывать строку в mp3 файл с речью. Т.к. за этой библиотекой стоит Google, то на выбор имеется много языков, включая русский.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Vision API can be used for text recognition, face detection, object detection, etc. We’ll be using the ImageAnnotator Client to extract Text from Images with Python Programming Language.

ILAN-Solutions/Text-Recognition-using-Google-Cloud-Vision-API

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A Complete Guide to Text Recognition using Google Cloud Vision API

Vision AI is a cloud-based service offered by Google. It employs Machine Learning algorithms to analyze images. While users can make use of AutoML Vision to analyze images using custom datasets, in this article,we will be focussing on Vision API, which uses pre-trained ML models to analyze images. Vision API can be used for text recognition, face detection, object detection, etc. We’ll be using the ImageAnnotator Client to extract Text from Images with Python Programming Language.

To extract text from a single image, use the ‘Vision_API.py’ code. To extract text from multiple images in same folder, use the ‘Vision_API (For Multiple Images).py’ code.

Enabling Vision API and creating Credentials in Google Cloud console

Step 1: Open Google Cloud console

Upon Logging into Google Cloud Console, you would arrive at a similar screen. Your console acts as a homepage from where you can create projects, monitor your project activities, etc.

Step 2: Create a New Project

Click on the ‘Select a project’ drop-down option to show the list of all projects you’ve created. To create a new project, Click on the ‘New Project’ option.

Type in your project name and click on the ‘Create’ button to create your first project. For this article, I’ve given the name of the project as ‘VisionAPI’, but feel free to choose the project name as per your wish.

Once you’ve successfully created your project, click on the ‘Select a project’ drop-down button and click on your project. This would redirect you to a similar page

In the ‘Search products and resources’ box, type ‘Cloud Vision API’. Click on the ‘Enable’ option.

Step 4: Creating Credentials

In order to use Vision API, we have to create credentials which inturn would generate a key using which we can send requests to Vision API for processing.

Clicking on the ‘Create Credentials’ button would trigger a drop-down option. Click on ‘Service account’ when this happens.

Type your choice of ‘Service account name’ and ‘Service account description’ and click on the ‘Create’ button.

In this next step, under ‘Role’, select ‘Project -> Owner’ to obtain full access to all the resources. Proceed to the next section by clicking on ‘Continue’. Skip the next step as it is an optional step, and click on the ‘Done’ button to create the credentials.

Step 5: Adding a Key for the service

Under the ‘Service Accounts’ section, click on the name of your project, and that would take you to the next page where-in you can add a Key for the service.

Click on the ‘Add Key’ button, and then on the ‘Create New Key’ button. Choose the format as ‘JSON’, and click on ‘Create’.Save the file on your computer. This file is essential when we call the service.

Making Call Requests and Performing text recognition using Python language

Step 1: Installing required Python Libraries.

This particular Python code requires the following libraries which might require separate installations :

To install Google Cloud Vision library, open your Scripts folder inside your Python folder using Command Prompt. For ex. $ cd C:\Python27\Scripts

And then, type ‘ $ pip install google-cloud-vision ‘ to install the library.

Once this installation is completed, install Pandas library using the command ‘pip install Pandas’.

Step 2: Open the folder containing the Images and the Key file using your Python IDE of choice and Type in the following code:

In the line 5 of the code, add the name of your Key file in the ‘r»(. )’ region. For ex., the 5th line of code for my Key file looks like this

In the line 9 of the code, choose the path for your Image from which you would want to extract the Text. For ex., the 9th line of my code looks like this

Run the code, and You would have successfully extracted the Text from the fed Image.

About

Vision API can be used for text recognition, face detection, object detection, etc. We’ll be using the ImageAnnotator Client to extract Text from Images with Python Programming Language.

Источник

Читайте также:  Javascript function open iframe
Оцените статью