Team Ai
Apppublic

Coder19/interview_system

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
stt_tts.py78 linesDownload Raw Back to api
1from fastapi import APIRouter, File, UploadFile2from interview_prep.speech import (3    get_random_paragraph,4    transcribe_audio,5    calculate_speaking_pace,6    evaluate_pace,7    calculate_accuracy,8    DEFAULT_CHUNK_LENGTH9)10import os11import tempfile12 13router = APIRouter()14 15@router.post("/voice-process")16async def evaluate_voice(audio: UploadFile = None):17    # If no audio file is provided, return a random paragraph18    if not audio:19        paragraph = get_random_paragraph()20        return {21            "success": True,22            "paragraph": paragraph,23            "message": "Please read this paragraph aloud."24        }25    26    try:27        # Save the uploaded audio to a temporary file28        temp_dir = tempfile.mkdtemp()29        temp_path = os.path.join(temp_dir, "recording.wav")30        31        with open(temp_path, "wb") as f:32            content = await audio.read()33            f.write(content)34        35        # Get the paragraph that was read36        paragraph = get_random_paragraph()  # In a real app, you'd store this with the session37        38        # Transcribe the audio39        transcription = transcribe_audio(temp_path)40        41        # Clean up42        os.remove(temp_path)43        os.rmdir(temp_dir)44        45        if transcription:46            # Calculate metrics47            pace = calculate_speaking_pace(transcription, DEFAULT_CHUNK_LENGTH)48            pace_label = evaluate_pace(pace)49            accuracy = calculate_accuracy(transcription, paragraph)50            51            # Generate feedback52            if pace_label == "too slow":53                feedback = "Try to speak a little faster for better fluency."54            elif pace_label == "too fast":55                feedback = "You are speaking too fast! Try to slow down for better clarity."56            else:57                feedback = "Your speaking pace is proper. Keep it up!"58            59            return {60                "success": True,61                "paragraph": paragraph,62                "transcription": transcription,63                "speaking_pace": f"{pace:.2f} words/sec",64                "pace_feedback": pace_label,65                "accuracy": f"{accuracy:.2f}%",66                "feedback": feedback67            }68        else:69            return {70                "success": False,71                "message": "Could not transcribe audio. Please try again."72            }73            74    except Exception as e:75        return {76            "success": False,77            "message": f"Error processing audio: {str(e)}"78        }