forked from Mrinank-Bhowmick/python-beginner-projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranscription.py
More file actions
67 lines (50 loc) · 1.8 KB
/
transcription.py
File metadata and controls
67 lines (50 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from flask import Flask, request, jsonify, send_file
from werkzeug.utils import secure_filename
from datetime import timedelta
import os
import whisper
app = Flask(__name__)
@app.route("/transcribe", methods=["POST"])
def transcribe():
# check if the post request has the file part
if "audio" not in request.files:
return jsonify({"error": "No audio file found."}), 400
file = request.files["audio"]
if file.filename == "":
return jsonify({"error": "No audio file selected."}), 400
if not allowed_file(file.filename):
return (
jsonify({"error": "Only WAV, MP3, and OGG audio files are allowed."}),
400,
)
filename = secure_filename(file.filename)
file.save(filename)
model = whisper.load_model("small") # Change this to your desired model
print("Whisper model loaded.")
transcribe = model.transcribe(audio=filename)
segments = transcribe["segments"]
srt_file = open("subtitles.vtt", "w", encoding="utf-8")
srt_file.write("WEBVTT\n\n")
for segment in segments:
startTime = str(0) + str(timedelta(seconds=int(segment["start"]))) + ".000"
endTime = str(0) + str(timedelta(seconds=int(segment["end"]))) + ".000"
text = segment["text"]
segmentId = segment["id"] + 1
segment = f"{segmentId}\n{startTime} --> {endTime}\n{text[1:] if text[0] == ' ' else text}\n\n"
srt_file.write(segment)
srt_file.close()
os.remove(filename)
return send_file(
"subtitles.vtt",
as_attachment=True,
download_name="subtitles.vtt",
mimetype="text/vtt",
)
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in [
"wav",
"mp3",
"ogg",
]
if __name__ == "__main__":
app.run()