Spaces:
Runtime error
Runtime error
File size: 4,319 Bytes
f7e7003 9c0cf44 | 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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | from fastapi import APIRouter, File, UploadFile, Form, HTTPException, Response, status
import os
import urllib.parse
from pydantic import BaseModel
from typing import Optional, Dict, Any
from api.models import ResumeAnalysisResponse
from services.resume_service import analyze_resume_document
from api.models import AudioAnalysisResponse
from services.voice_service import AudioAnalyzer
router = APIRouter()
# Initialize services
audio_analyzer = AudioAnalyzer()
class StorageStatus(BaseModel):
stored: bool
id: Optional[str] = None
error: Optional[str] = None
class ExtendedResumeAnalysisResponse(ResumeAnalysisResponse):
id: Optional[str] = None
stored_in_db: bool = False
db_error: Optional[str] = None
@router.post("/analyze-resume", response_model=ExtendedResumeAnalysisResponse)
async def analyze_resume(
resume_file: UploadFile = File(...),
job_role: str = Form(...)
):
filename = urllib.parse.unquote(resume_file.filename)
_, file_extension = os.path.splitext(filename)
file_extension = file_extension.lower()
allowed_extensions = ['.pdf', '.docx']
if file_extension not in allowed_extensions:
raise HTTPException(
status_code=400,
detail=f"Only PDF and DOCX files are supported. Got: {file_extension}"
)
try:
file_bytes = await resume_file.read()
os.environ["STORE_ANALYSIS_RESULT"] = "true"
result = await analyze_resume_document(file_bytes, job_role, file_extension)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing resume: {str(e)}")
@router.get("/candidate/{candidate_id}", response_model=ExtendedResumeAnalysisResponse)
async def get_candidate(candidate_id: str):
try:
from services.db_service import get_supabase_client
clean_id = urllib.parse.unquote(candidate_id).strip('"')
supabase = get_supabase_client()
response = supabase.table("candidates").select("*").eq("id", clean_id).execute()
if not response.data or len(response.data) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Candidate with ID {clean_id} not found"
)
candidate_data = response.data[0]
candidate_data["stored_in_db"] = True
return candidate_data
except Exception as e:
if isinstance(e, HTTPException):
raise e
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error retrieving candidate: {str(e)}"
)
@router.post("/analyze/audio", response_model=AudioAnalysisResponse)
async def analyze_audio_recording(
file: UploadFile = File(...),
job_role: Optional[str] = Form(None)
):
"""
Analyze an audio recording of a candidate's introduction.
Args:
file (UploadFile): The audio file to analyze. Supported formats: WAV, MP3, M4A
job_role (str, optional): The job role the candidate is applying for. Used for role-specific analysis.
Returns:
AudioAnalysisResponse: Comprehensive analysis of the audio recording including fluency,
grammar, confidence scores, and other metrics.
"""
try:
# Validate file type
allowed_extensions = {'.wav', '.mp3', '.m4a'}
file_ext = '.' + file.filename.split('.')[-1].lower()
if file_ext not in allowed_extensions:
raise HTTPException(
status_code=400,
detail=f"Invalid file type. Supported formats: {', '.join(allowed_extensions)}"
)
# Read file content
file_content = await file.read()
# Analyze the audio with job role
analysis_result = audio_analyzer.analyze_audio(file_content, job_role=job_role)
return AudioAnalysisResponse(**analysis_result)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Error analyzing audio: {str(e)}"
) |