'TranscriptionConsumer' object has no attribute 'base_send' Websocket Django
I'm trying to do site that translates .wav audio into text in django. I've got a problem here. I'm using websocket to send translated text immediately. But when I try to send a text, this error occurs ('TranscriptionConsumer' object has no attribute 'base_send')
views.py
# this function recognites text and send it to Consumers's function
def get_large_audio_transcription(path,language, consumer ,minutes=2):
sound = AudioSegment.from_file(path)
chunk_length_ms = int(1000*60*minutes)
chunks = [sound[i:i + chunk_length_ms] for i in range(0, len(sound), chunk_length_ms)]
folder_name=str(settings.MEDIA_ROOT) + "/audio-chunks/"
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
whole_text = ""
for i, audio_chunk in enumerate(chunks,start=1):
chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
audio_chunk.export(chunk_filename, format="wav")
try:
text = transcribe_small_audio(chunk_filename, language=language)
except sr.UnknownValueError as e:
print("Error:", str(e))
else:
text = f"{text.capitalize()}."
print(text)
whole_text += text
json_transcribe = json.dumps({"message": text})
# Sending json text through WebSocket
consumer.send_json(json_transcribe)
# deleting chunk
try:
os.remove(chunk_filename)
except FileNotFoundError:
print("Error: file not found")
return whole_text
@login_required(login_url='login_user')
def index(request):
context = None
audio_form = UploadFileForm()
if request.method == "POST":
audio_form = UploadFileForm(request.POST, request.FILES)
if not audio_form.is_valid():
messages.success(request, ("Error!"))
return render(request, 'recognition/index.html', {"error": "Provide a valid file"})
try:
form = audio_form.save(commit=False)
form.name = request.user
form.save()
file = form.audio # get the audio
file_size = file.size
file_path = str(settings.MEDIA_ROOT) + '/' + str(file.name)
consumer = TranscriptionConsumer()
messages.success(request, ("File size is too big. We will give you a file with transcription..."))
text = get_large_audio_transcription(file_path,"en-US", consumer)
os.remove(file_path)
context = {
"text" :text,
"AudioForm":audio_form,
"size" : file_size
}
except Exception as ex:
context = {"error": str(ex)}
else:
context = {
"AudioForm" : audio_form
}
return render(request, "recognition/index.html", context )
My consumers.py
import json
from channels.generic.websocket import WebsocketConsumer
class TranscriptionConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def send_json(self, text_data):
self.connect()
text_data_json = json.loads(text_data)
text_message = text_data_json["message"]
self.send(text_data=json.dumps({
'message' : text_message
}))
index.html file
{% extends 'app/base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<h2>Upload file</h2>
<form method="post", enctype="multipart/form-data">
{% csrf_token %}
{{ AudioForm | crispy }}
<div class="d-grid gap-3 mt-3">
<button type="submit" class="btn btn-outline-success">Upload audio</button>
</div>
</form>
<p>Your file size :</p>
{{ size|filesizeformat }}
{{ size }}
<h2>Transcript</h2>
{% if error %}
<p id="error" style="color: red">{{ error }}</p>
{% endif %}
<p id="app">
{{ text }}
</p>
<script>
const socket = new WebSocket('ws://' + window.location.host + '/ws/somepath/');
socket.onmessage = function (event) {
const data = JSON.parse(event.data);
console.log(data.message);
document.querySelector('#app').innerText = data.message
};
</script>
{% endblock %}
I expect recognized text to appear on the page, instead I get an error.
Btw I'm new to django
I noticed a few things in your code that might be causing issues. For example, calling self.connect()
in send_json
isn't necessary—Django Channels automatically calls connect()
when a WebSocket connection is established, so you don’t need to call it again in send_json
.
Also, in send_json
, you can use self.send
directly to send JSON data to the WebSocket client.
Here’s an updated version of your TranscriptionConsumer
class and the get_large_audio_transcription
function that should work:
# consumers.py
import json
from channels.generic.websocket import WebsocketConsumer
class TranscriptionConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def send_json(self, text_data):
# Send text data as JSON to the WebSocket
self.send(text_data)
And for the get_large_audio_transcription
function:
# This function recognizes text and sends it to the Consumer's function
def get_large_audio_transcription(path, language, consumer, minutes=2):
sound = AudioSegment.from_file(path)
chunk_length_ms = int(1000 * 60 * minutes)
chunks = [sound[i:i + chunk_length_ms] for i in range(0, len(sound), chunk_length_ms)]
folder_name = str(settings.MEDIA_ROOT) + "/audio-chunks/"
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
whole_text = ""
for i, audio_chunk in enumerate(chunks, start=1):
chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
audio_chunk.export(chunk_filename, format="wav")
try:
text = transcribe_small_audio(chunk_filename, language=language)
except sr.UnknownValueError as e:
print("Error:", str(e))
else:
text = f"{text.capitalize()}."
print(text)
whole_text += text
json_transcribe = json.dumps({"message": text})
# Sending JSON text through WebSocket
consumer.send_json(json_transcribe)
# Deleting chunk
try:
os.remove(chunk_filename)
except FileNotFoundError:
print("Error: file not found")
return whole_text