Coder19/interview_system
0
1import os2import wave3import pyaudio4import numpy as np5from scipy.io import wavfile6from faster_whisper import WhisperModel7import random8 9DEFAULT_MODEL_SIZE = "medium"10DEFAULT_CHUNK_LENGTH = 1011 12model_size = DEFAULT_MODEL_SIZE + ".en"13model = WhisperModel(model_size, device="cpu")14 15audio = pyaudio.PyAudio()16stream = audio.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)17 18PARAGRAPHS = [19 "The quick brown fox jumps over the lazy dog. This sentence is often used as a typing exercise because it contains every letter of the alphabet. Reading it aloud helps in pronunciation and fluency.",20 "Technology is evolving at a rapid pace, shaping the way we live and work. Artificial intelligence and machine learning are revolutionizing industries, making processes more efficient and innovative.",21 "A healthy lifestyle includes a balanced diet, regular exercise, and sufficient sleep. Small daily habits, like drinking water and taking short walks, can greatly impact overall well-being.",22 "Space exploration has always fascinated humankind. From the first moon landing to the latest Mars rover missions, every discovery brings us closer to understanding the universe.",23 "History teaches us valuable lessons. By learning from the past, we can make informed decisions for the future. Great leaders and civilizations have left behind knowledge that guides our progress."24]25 26SPEAKING_PACE_RANGES = {27 "too slow": (0, 1.5),28 "proper": (1.5, 3.0),29 "too fast": (3.0, float("inf"))30}31 32def get_random_paragraph():33 return random.choice(PARAGRAPHS)34 35def calculate_speaking_pace(transcription, chunk_length):36 words = transcription.split()37 num_words = len(words)38 return num_words / chunk_length39 40def evaluate_pace(pace):41 for label, (low, high) in SPEAKING_PACE_RANGES.items():42 if low <= pace < high:43 return label44 return "unknown"45 46def is_silence(data, max_amplitude_threshold=3000):47 max_amplitude = np.max(np.abs(data))48 return max_amplitude <= max_amplitude_threshold49 50def record_audio_chunk(chunk_length=DEFAULT_CHUNK_LENGTH):51 frames = []52 os.makedirs("Audio", exist_ok=True)53 temp_file_path = os.path.join("Audio", "temp_audio_chunk.wav")54 55 for _ in range(0, int(16000 / 1024 * chunk_length)):56 data = stream.read(1024, exception_on_overflow=False)57 frames.append(data)58 59 with wave.open(temp_file_path, 'wb') as wf:60 wf.setnchannels(1)61 wf.setsampwidth(audio.get_sample_size(pyaudio.paInt16))62 wf.setframerate(16000)63 wf.writeframes(b''.join(frames))64 65 try:66 samplerate, data = wavfile.read(temp_file_path)67 if is_silence(data):68 os.remove(temp_file_path)69 return False, None70 return True, temp_file_path71 except Exception as e:72 print(f"Error while reading audio file: {e}")73 return False, None74 75def transcribe_audio(file_path):76 segments, info = model.transcribe(file_path, beam_size=7)77 transcription = ' '.join(segment.text for segment in segments)78 return transcription79 80def calculate_accuracy(transcription, reference_text):81 transcribed_words = transcription.lower().split()82 reference_words = reference_text.lower().split()83 matched_words = sum(1 for tw, rw in zip(transcribed_words, reference_words) if tw == rw)84 return (matched_words / max(len(reference_words), 1)) * 10085 86def main():87 paragraph = get_random_paragraph()88 print("Please read the following paragraph:")89 print(paragraph)90 91 input("Press Enter to start recording...")92 success, file_path = record_audio_chunk()93 94 if success:95 transcription = transcribe_audio(file_path)96 os.remove(file_path)97 speaking_pace = calculate_speaking_pace(transcription, DEFAULT_CHUNK_LENGTH)98 accuracy = calculate_accuracy(transcription, paragraph)99 pace_feedback = evaluate_pace(speaking_pace)100 101 print("\nTranscription:", transcription)102 print(f"Speaking Pace: {speaking_pace:.2f} words per second ({pace_feedback})")103 print(f"Accuracy: {accuracy:.2f}%")104 105 if pace_feedback == "too slow":106 print("Try to speak a little faster for better fluency.")107 elif pace_feedback == "too fast":108 print("You are speaking too fast! Try to slow down for better clarity.")109 else:110 print("Your speaking pace is proper. Keep it up!")111 else:112 print("Silence detected, please try again.")113 114if __name__ == "__main__":115 main()116 