0

I want to incorporate a Python file using speech recognition in the backend of a React project.

Here I have the piece of Python code using Speech Recognition:

import speech_recognition as sr

r = sr.Recognizer()


def recognize(audio):
    try:
        return r.recognize_google(audio)
    except LookupError:
        print("There was an error")
        return ''

def transciption():
    with sr.Microphone() as source:
        print('speak now')
        r.adjust_for_ambient_noise(source)
        audio = r.listen(source)
        return recognize(audio)

I tried to import the file in my react component like this:

import SpeechRec from 'SpeechRec.py';

Here I tried to link my button to the function in my Python file:

<button onClick={SpeechRec.transcription()}>SR</button>

I received the message that it failed to compile along with the following:

./src/components/container/Container.jsx
Module not found: Can't resolve 'SpeechRec.py' in '......\collaborative-whiteboard-SR\ui\src\components\container'

What can I do to make this work?

KantSpel
  • 81
  • 5
  • 3
    You cannot import python files in react, you need to make a back-end server and make requests or something like that. – programandoconro May 16 '21 at 11:46
  • Flask and FastAPI are popular, small-ish backend frameworks you can use to create a small web service to make your Python functions available as services in the background. Make sure to consider if you need authentication and authorization if you plan to expose these servers on the internet. – MatsLindh May 16 '21 at 11:57
  • You want to use **Django** framework to achieve this functionality. [Python Django](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django) – Ayush May 16 '21 at 12:00
  • Django + Vue is much easier to setup than django+react. If framework is not a problem, you should try that combo. – Vishesh Mangla May 16 '21 at 20:34

1 Answers1

2

You can implement your own speech recongition module with javascript and nodejs. Check out some projects like sonus, and this response in stackoverflow.

If you still want to use python as a backend language, you have to implement your own API (using some library like flask) to be able to interactuate with your javascript code. From your react application, you should make HTTP requests that will be received to your custom Python API that will respond to the app.

fernandezr
  • 660
  • 6
  • 19
  • 1
    I recommend to use django and not flask, especially django Rest framework is a common framework for creating custom APIs. – alexrogo May 16 '21 at 12:49