Spaces:
Sleeping
Sleeping
File size: 3,439 Bytes
ff7b177 | 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 | import uuid
import json
import logging
from datetime import datetime, timezone
from dataclasses import asdict
from fastapi import APIRouter, UploadFile, File, HTTPException
from app.services import storage, file_parser
from app.models.schemas import CandidateBatchResponse, BatchListItem
router = APIRouter(prefix="/api/v1/candidates", tags=["candidates"])
logger = logging.getLogger(__name__)
def _candidate_to_dict(c) -> dict:
"""Serialize CandidateData to JSON-safe dict."""
return {
"id": c.id,
"name": c.name,
"current_position": c.current_position,
"current_title": c.current_title,
"years_of_experience": c.years_of_experience,
"engineer_type": c.engineer_type,
"gen_ai_experience": c.gen_ai_experience,
"parsed_skills": c.parsed_skills,
"parsed_summary": c.parsed_summary,
"parsed_work_experience_raw": c.parsed_work_experience_raw,
"parsed_work_experience_text": c.parsed_work_experience_text,
"work_experiences": [
{
"company": we.company,
"role": we.role,
"duration": we.duration,
"description": we.description,
}
for we in c.work_experiences
],
"most_recent_company": c.most_recent_company,
"notice_period": c.notice_period,
"is_actively_looking": c.is_actively_looking,
"flags": c.flags,
"penalties": c.penalties,
}
@router.post("/upload", response_model=CandidateBatchResponse)
async def upload_candidates(file: UploadFile = File(...)):
if not file.filename or not file.filename.lower().endswith(".xlsx"):
raise HTTPException(400, "Only XLSX files accepted for candidates")
content = await file.read()
if len(content) > 50 * 1024 * 1024:
raise HTTPException(413, "File too large (max 50 MB)")
try:
candidates, dist = file_parser.parse_xlsx(content)
except ValueError as e:
raise HTTPException(400, str(e))
if not candidates:
raise HTTPException(400, "No valid candidates found in file")
batch_id = str(uuid.uuid4())[:8]
now = datetime.now(timezone.utc).isoformat()
metadata = {
"batch_id": batch_id,
"total_count": len(candidates),
"engineer_type_distribution": json.dumps(dist),
"uploaded_at": now,
"filename": file.filename,
}
candidates_json = json.dumps([_candidate_to_dict(c) for c in candidates])
storage.save_batch(batch_id, metadata, candidates_json)
logger.info(f"Batch uploaded: {batch_id}, {len(candidates)} candidates, dist={dist}")
return CandidateBatchResponse(
batch_id=batch_id,
total_count=len(candidates),
engineer_type_distribution=dist,
uploaded_at=now,
)
@router.get("/", response_model=list[BatchListItem])
def list_batches():
items = storage.list_batches()
result = []
for d in items:
dist = d.get("engineer_type_distribution", {})
if isinstance(dist, str):
try:
dist = json.loads(dist)
except Exception:
dist = {}
result.append(BatchListItem(
batch_id=d.get("batch_id", ""),
total_count=int(d.get("total_count", 0)),
engineer_type_distribution=dist,
uploaded_at=d.get("uploaded_at", ""),
))
return result
|