Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,51 +1,55 @@
|
|
1 |
-
import
|
2 |
-
import
|
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 |
-
translated_text =
|
50 |
-
|
|
|
|
|
|
|
|
|
51 |
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer, pipeline
|
3 |
+
from pydub import AudioSegment
|
4 |
+
import torch
|
5 |
+
import torchaudio
|
6 |
+
from datetime import datetime, time
|
7 |
+
import pytz
|
8 |
+
|
9 |
+
app = Flask(__name__)
|
10 |
+
|
11 |
+
# Load speech recognition model and tokenizer
|
12 |
+
tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h")
|
13 |
+
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
|
14 |
+
|
15 |
+
# Load translation pipeline
|
16 |
+
translation_pipeline = pipeline("translation_en_to_hi")
|
17 |
+
|
18 |
+
# Function to preprocess audio
|
19 |
+
def preprocess_audio(audio_file):
|
20 |
+
audio = AudioSegment.from_file(audio_file)
|
21 |
+
audio = audio.set_frame_rate(16000)
|
22 |
+
audio.export("processed.wav", format="wav")
|
23 |
+
waveform, sample_rate = torchaudio.load("processed.wav")
|
24 |
+
return waveform
|
25 |
+
|
26 |
+
# Function to check if the current time is after 6 PM IST
|
27 |
+
def is_after_6pm_ist():
|
28 |
+
ist = pytz.timezone('Asia/Kolkata')
|
29 |
+
current_time = datetime.now(ist).time()
|
30 |
+
return current_time >= time(18, 0)
|
31 |
+
|
32 |
+
@app.route('/translate', methods=['POST'])
|
33 |
+
def translate():
|
34 |
+
if not is_after_6pm_ist():
|
35 |
+
return jsonify({"error": "Service is available only after 6 PM IST"}), 403
|
36 |
+
|
37 |
+
if 'audio' not in request.files:
|
38 |
+
return jsonify({"error": "No audio file provided"}), 400
|
39 |
+
|
40 |
+
audio_file = request.files['audio']
|
41 |
+
waveform = preprocess_audio(audio_file)
|
42 |
+
|
43 |
+
input_values = tokenizer(waveform.squeeze().numpy(), return_tensors="pt").input_values
|
44 |
+
logits = model(input_values).logits
|
45 |
+
predicted_ids = torch.argmax(logits, dim=-1)
|
46 |
+
transcription = tokenizer.batch_decode(predicted_ids)[0]
|
47 |
+
|
48 |
+
translation = translation_pipeline(transcription)
|
49 |
+
translated_text = translation[0]['translation_text']
|
50 |
+
|
51 |
+
return jsonify({"transcription": transcription, "translation": translated_text})
|
52 |
+
|
53 |
+
if __name__ == '__main__':
|
54 |
+
app.run(debug=True, host='0.0.0.0', port=8080)
|
55 |
|