Add a button for transcription to a Django form
I am building a website and have views with Django forms. I want to add a transcription button to each field in the Django form
class PostForm(StylishForm):
class Meta:
model = Post
fields = ["title", "body", "upload"]
widgets = {
"owner": forms.HiddenInput(),
}
and give the user the option either to fill the form by typing or pressing the button to transcribe then filling the field.
# add new
def add(request):
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.owner = request.user
post.save()
return HttpResponseRedirect(reverse("view_posts"))
else:
form = PostForm()
return render(
request,
"posts/index.html",
{
"form": form,
},
)
I have prepared the function to use whisper api for transcription.
def record_audio(request):
RATE = 16000
CHUNK = 1024
recordings = os.path.join(settings.MEDIA_ROOT, 'recordings')
# Ensure the folder exists
if not os.path.exists(recordings):
os.makedirs('recordings')
# Define the path to save the audio file
file_path = os.path.join(recordings, 'output.wav')
# def callback(data_input, frame_count, time_info, status):
# wav_file.writeframes(data_input)
# return None, pyaudio.paContinue
with wave.open(file_path, "wb") as wav_file:
wav_file.setnchannels(1) # Mono channel
wav_file.setsampwidth(2) # 16-bit samples
wav_file.setframerate(16000) # 16kHz sample rate
audio = pyaudio.PyAudio()
stream = audio.open(
format=pyaudio.paInt16,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
)
for _ in range(0, RATE // CHUNK):
wav_file.writeframes(stream.read(CHUNK))
stream.stop_stream()
stream.close()
audio.terminate()
audio_file= open(file_path, "rb")
transcription = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
print(transcription.text)
return HttpResponseRedirect(reverse("view_posts"))
But, I cannot get my head around to send the text to the form field.
My html template looks like this:
<div class="tab-pane fade show active" id="post-tab-pane" role="tabpanel" aria-labelledby="post-tab"
tabindex="0">
<form enctype="multipart/form-data" action="{% url 'add' %}" method="POST">
{% csrf_token %}
{% for field in post_form %}
<div class="form-group">
<div class="form-labels">{{ field.label }}</div>
{{ form.media }}
<div class="form-fields">{{ field }}</div>
</div>
{% endfor %}
<button class="btn btn-primary" type="submit">Save</button>
</form>
</div>
My issue I cannot think of a way to use text from transcription and populate the fields of the form selectively to toggle between both methods. I tried to find any examples on the internet but could not find any resource.