CoolFace
Apppublic

Coder19/interview_system

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
interview.py111 linesDownload Raw Back to routes
1from fastapi import APIRouter, WebSocket, HTTPException2from interview.app.services.interview import InterviewService3from typing import Dict, Any4from pydantic import BaseModel5import json6 7class AnswerRequest(BaseModel):8    answer: str9 10interview_router = APIRouter()11interview_service = InterviewService()  # No API key needed here anymore as it's handled in OpenAI service12 13# WebSocket endpoint for real-time voice communication14@interview_router.websocket("/ws")15async def websocket_endpoint(websocket: WebSocket):16    await websocket.accept()17    18    try:19        await interview_service.start_interview(websocket)20        21        # Main interview loop22        while True:23            try:24                message = await websocket.receive_text()25                data = json.loads(message)26                27                if data['type'] == 'user_response':28                    await interview_service.handle_user_response(data['text'])29                elif data['type'] == 'video_frame':30                    await interview_service.handle_video_frame(data['data'])31                elif data['type'] == 'audio_data':32                    await interview_service.handle_audio_data(data['data'])33                elif data['type'] == 'typing_data':34                    await interview_service.handle_typing_data(data['data'])35            except RuntimeError as e:36                # WebSocket was closed by the client37                print(f"WebSocket closed by client: {e}")38                break39            except Exception as e:40                print(f"Error processing message: {e}")41                try:42                    await websocket.send_json({43                        "type": "error",44                        "text": "An error occurred processing your message. Please try again."45                    })46                except:47                    break  # Exit if we can't communicate with the client48                49    except Exception as e:50        print(f"Error in websocket endpoint: {e}")51    finally:52        await interview_service.cleanup()53 54# REST API endpoints for non-WebSocket interactions55@interview_router.post("/start")56async def start_interview() -> Dict[str, Any]:57    """Start a new interview session"""58    try:59        return {"status": "success", "message": "Interview session started"}60    except Exception as e:61        raise HTTPException(status_code=500, detail=str(e))62 63@interview_router.post("/answer")64async def submit_answer(request: AnswerRequest) -> Dict[str, Any]:65    """Submit an answer to the current question"""66    try:67        response = await interview_service.handle_user_response(request.answer)68        return {69            "status": "success",70            "message": "Answer processed successfully",71            "next_question": response72        }73    except Exception as e:74        raise HTTPException(status_code=500, detail=str(e))75 76@interview_router.get("/status")77async def get_interview_status() -> Dict[str, Any]:78    """Get the current status of the interview"""79    try:80        # You might want to add interview status tracking in InterviewService81        return {82            "status": "success",83            "is_active": True,  # This should come from interview service84            "current_phase": "technical_questions"  # This should come from interview service85        }86    except Exception as e:87        raise HTTPException(status_code=500, detail=str(e))88 89@interview_router.post("/end")90async def end_interview() -> Dict[str, Any]:91    """End the current interview session"""92    try:93        await interview_service.cleanup()94        return {95            "status": "success",96            "message": "Interview session ended successfully"97        }98    except Exception as e:99        raise HTTPException(status_code=500, detail=str(e))100 101@interview_router.get("/feedback")102async def get_interview_feedback() -> Dict[str, Any]:103    """Get feedback for the completed interview"""104    try:105        feedback = await interview_service.analyze_interview()106        return {107            "status": "success",108            "feedback": feedback109        }110    except Exception as e:111        raise HTTPException(status_code=500, detail=str(e))