Spaces:
Running
Running
EvalBot platform: accounts, mock interviews for 30 tracks, hiring interviews, human-calibrated scores, React web app
Browse files- .dockerignore +3 -0
- .gitattributes +1 -0
- .gitignore +6 -3
- Dockerfile +10 -0
- README.md +81 -70
- app.py +29 -3
- assets/models/calibrated_scores.joblib +3 -0
- calibration.py +209 -0
- frontend/index.html +17 -0
- frontend/package-lock.json +0 -0
- frontend/package.json +29 -0
- frontend/public/favicon.svg +1 -0
- frontend/src/components/Shell.tsx +113 -0
- frontend/src/components/ui.tsx +199 -0
- frontend/src/index.css +57 -0
- frontend/src/lib/api.ts +177 -0
- frontend/src/lib/auth.tsx +158 -0
- frontend/src/lib/i18n.tsx +273 -0
- frontend/src/lib/media.ts +227 -0
- frontend/src/main.tsx +66 -0
- frontend/src/pages/Apply.tsx +65 -0
- frontend/src/pages/Auth.tsx +102 -0
- frontend/src/pages/Dashboard.tsx +97 -0
- frontend/src/pages/History.tsx +66 -0
- frontend/src/pages/InterviewRoom.tsx +229 -0
- frontend/src/pages/JobDetail.tsx +93 -0
- frontend/src/pages/JobEditor.tsx +117 -0
- frontend/src/pages/Jobs.tsx +66 -0
- frontend/src/pages/Landing.tsx +153 -0
- frontend/src/pages/NewInterview.tsx +129 -0
- frontend/src/pages/Onboarding.tsx +72 -0
- frontend/src/pages/Report.tsx +275 -0
- frontend/src/pages/Settings.tsx +84 -0
- frontend/tsconfig.json +17 -0
- frontend/tsconfig.tsbuildinfo +1 -0
- frontend/vite.config.ts +9 -0
- gitattributes +35 -0
- platform_app/__init__.py +0 -0
- platform_app/ai.py +275 -0
- platform_app/core.py +184 -0
- platform_app/routes.py +500 -0
- platform_app/schema.sql +88 -0
- process_interview.py +29 -0
- requirements.txt +3 -0
- research/README.md +10 -0
- research/benchmark.py +52 -0
- research/diarize.py +62 -0
- research/text_features.py +43 -0
- research/train_calibration.py +139 -0
.dockerignore
CHANGED
|
@@ -4,3 +4,6 @@ processed_audio
|
|
| 4 |
temp_files
|
| 5 |
static/outputs
|
| 6 |
models
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
temp_files
|
| 5 |
static/outputs
|
| 6 |
models
|
| 7 |
+
frontend/node_modules
|
| 8 |
+
frontend/dist
|
| 9 |
+
platform_storage
|
.gitattributes
CHANGED
|
@@ -2,3 +2,4 @@ assets/fonts/Amiri-Bold.ttf filter=lfs diff=lfs merge=lfs -text
|
|
| 2 |
assets/fonts/Amiri-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
| 3 |
assets/sample_interview.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 4 |
assets/models/role_classifier.joblib filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 2 |
assets/fonts/Amiri-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
| 3 |
assets/sample_interview.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 4 |
assets/models/role_classifier.joblib filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
assets/models/calibrated_scores.joblib filter=lfs diff=lfs merge=lfs -text
|
.gitignore
CHANGED
|
@@ -1,9 +1,12 @@
|
|
| 1 |
__pycache__/
|
| 2 |
*.pyc
|
| 3 |
static/outputs/
|
| 4 |
-
processed_audio/
|
| 5 |
-
temp_files/
|
| 6 |
-
models/
|
| 7 |
.env
|
| 8 |
interview_transcripts_by_turkers.csv
|
| 9 |
*.avi
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
__pycache__/
|
| 2 |
*.pyc
|
| 3 |
static/outputs/
|
| 4 |
+
/processed_audio/
|
| 5 |
+
/temp_files/
|
| 6 |
+
/models/
|
| 7 |
.env
|
| 8 |
interview_transcripts_by_turkers.csv
|
| 9 |
*.avi
|
| 10 |
+
frontend/node_modules/
|
| 11 |
+
frontend/dist/
|
| 12 |
+
platform_storage/
|
Dockerfile
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
FROM python:3.10-slim
|
| 2 |
|
| 3 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
@@ -24,6 +33,7 @@ RUN pip install --user --upgrade pip \
|
|
| 24 |
&& pip install --user -r requirements.txt
|
| 25 |
|
| 26 |
COPY --chown=appuser:appuser . .
|
|
|
|
| 27 |
|
| 28 |
# Train the role classifier and download the speaker model at build time,
|
| 29 |
# so the Space is ready as soon as it starts
|
|
|
|
| 1 |
+
# ---- 1. build the web app -------------------------------------------------------------
|
| 2 |
+
FROM node:22-slim AS web
|
| 3 |
+
WORKDIR /web
|
| 4 |
+
COPY frontend/package.json frontend/package-lock.json ./
|
| 5 |
+
RUN npm ci --no-audit --no-fund
|
| 6 |
+
COPY frontend/ ./
|
| 7 |
+
RUN npm run build
|
| 8 |
+
|
| 9 |
+
# ---- 2. Python service ------------------------------------------------------------------
|
| 10 |
FROM python:3.10-slim
|
| 11 |
|
| 12 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
|
|
| 33 |
&& pip install --user -r requirements.txt
|
| 34 |
|
| 35 |
COPY --chown=appuser:appuser . .
|
| 36 |
+
COPY --from=web --chown=appuser:appuser /web/dist ./frontend/dist
|
| 37 |
|
| 38 |
# Train the role classifier and download the speaker model at build time,
|
| 39 |
# so the Space is ready as soon as it starts
|
README.md
CHANGED
|
@@ -1,100 +1,111 @@
|
|
| 1 |
---
|
| 2 |
-
title: EvalBot - Interview
|
| 3 |
emoji: 🎤
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
app_port: 7860
|
| 8 |
-
pinned:
|
| 9 |
-
short_description: AI
|
| 10 |
---
|
| 11 |
|
| 12 |
-
# EvalBot
|
| 13 |
|
| 14 |
-
|
| 15 |
|
| 16 |
-
|
| 17 |
-
- **Practice mode:** pick a question (or generate questions for any job title), listen to it, record your answer with the microphone, and get instant feedback: a score, what went well, what to improve, a delivery tip, and a stronger version of your answer.
|
| 18 |
|
| 19 |
-
|
| 20 |
|
| 21 |
-
|
| 22 |
|
| 23 |
-
##
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
| 6. Voice analysis | Speaking rate, filler words, repetition, pitch, jitter/shimmer, and confidence, anxiety and hesitation scores | librosa, NumPy |
|
| 33 |
-
| 7. Question pairing | Groups the transcript into question/answer pairs | Python |
|
| 34 |
-
| 8. Evaluation | Structured assessment: per-question score, what went well, what to improve and a stronger answer; summary, strengths with evidence, development areas, role fit, recommendations, next steps, content score. In English or Arabic | Gemini (JSON schema output) |
|
| 35 |
-
| 9. Report | Multi-page PDF (English, or right-to-left Arabic) with tables, charts, per-question feedback and an annotated transcript, plus a JSON export | ReportLab, Matplotlib, arabic-reshaper, python-bidi |
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
|
| 41 |
-
##
|
| 42 |
-
Form fields: `user_id`, either `file` (upload) or `file_url`, and optionally `lang` (`en` or `ar`).
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
{
|
| 52 |
-
"user_id": "candidate_42",
|
| 53 |
-
"suitability_score": 81.3,
|
| 54 |
-
"verdict": "Outstanding candidate, recommended for advancement.",
|
| 55 |
-
"summary": "...",
|
| 56 |
-
"pdf_url": "https://evalbot-audio-evalbot.hf.space/static/outputs/pdf/candidate_42_..._report.pdf",
|
| 57 |
-
"json_url": "https://evalbot-audio-evalbot.hf.space/static/outputs/json/candidate_42_..._analysis.json"
|
| 58 |
-
}
|
| 59 |
-
```
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
- `GET /practice/questions`: built-in question bank (General, Behavioral, Data Engineering, Software Engineering, AI / Machine Learning)
|
| 67 |
-
- `POST /practice/generate` (form field `role`): five AI-generated questions for a job title
|
| 68 |
-
- `POST /practice` (form fields `question`, `file`, optional `lang` and `role`): evaluates one recorded answer and returns the transcript, voice metrics and feedback, usually in 10-20 seconds
|
| 69 |
|
| 70 |
-
|
| 71 |
-
Shows which external services are configured.
|
| 72 |
|
| 73 |
-
|
| 74 |
|
| 75 |
-
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
Optional
|
| 84 |
|
| 85 |
-
## Run locally
|
| 86 |
|
| 87 |
```bash
|
| 88 |
-
docker build -t evalbot
|
| 89 |
-
docker run -p 7860:7860 -
|
| 90 |
-
# open http://localhost:7860
|
| 91 |
```
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
- Interviews and practice answers should be in English (the feedback and report can be in Arabic).
|
| 97 |
-
- Interviews with two speakers work best.
|
| 98 |
-
- The sample interview was generated with text-to-speech (Piper voices) for demonstration.
|
| 99 |
-
- The confidence, anxiety and hesitation scores are heuristics computed from the voice signal. They support a human reviewer and are not a hiring decision.
|
| 100 |
-
- The Space runs on free CPU hardware and sleeps when idle; the first request after a pause takes a minute to wake it up.
|
|
|
|
| 1 |
---
|
| 2 |
+
title: EvalBot - AI Interview Practice and Hiring
|
| 3 |
emoji: 🎤
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: docker
|
| 7 |
app_port: 7860
|
| 8 |
+
pinned: true
|
| 9 |
+
short_description: AI mock interviews and hiring for every career track
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# EvalBot
|
| 13 |
|
| 14 |
+
**Practice the interview before the interview.** EvalBot runs spoken mock interviews for 30 career tracks, listens to how you answer, and tells you exactly what to fix. Companies use the same engine to run one-link hiring interviews and get a ranked shortlist with reasons.
|
| 15 |
|
| 16 |
+
Its delivery scores are **calibrated on human judgment**: trained on 138 real mock interviews, each rated by nine people (MIT Interview Dataset).
|
|
|
|
| 17 |
|
| 18 |
+
English and Arabic throughout, including right-to-left PDF reports.
|
| 19 |
|
| 20 |
+
---
|
| 21 |
|
| 22 |
+
## What it does
|
| 23 |
|
| 24 |
+
### For job seekers
|
| 25 |
+
- **Any track, any level.** Data, backend, frontend, mobile, AI/ML, DevOps, security, design, product, marketing, sales, HR, finance and more, from internship to lead. Paste a job description or your CV and the questions are tailored to them.
|
| 26 |
+
- **A real conversation.** Questions are read aloud, you answer out loud, and EvalBot asks follow-up questions when an answer leaves something open.
|
| 27 |
+
- **Feedback you can act on.** Each answer gets a 0-10 score, what went well, what to improve, a delivery tip, and a stronger version of your answer built from your own facts.
|
| 28 |
+
- **Human-calibrated delivery scores** for 13 traits (overall impression, hiring recommendation, enthusiasm, engaging tone, structure, filler words, calmness and more), shown as your position among the 138 rated interviews.
|
| 29 |
+
- **Optional camera presence** (eye contact, smiling, face in frame), computed on-device with MediaPipe. Only the numbers leave the browser, never the video.
|
| 30 |
+
- **Progress tracking:** score history, skill breakdown, and a learning plan for your track.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
### For hiring teams
|
| 33 |
+
- Create a job with your own questions or AI-suggested ones and share **one link**.
|
| 34 |
+
- Every applicant answers the **same questions with the same time limit**, whenever it suits them.
|
| 35 |
+
- A **ranked candidate list** with scores, a hiring signal, the written assessment, recordings and transcripts.
|
| 36 |
+
- Shortlist, reject, rate and add notes. **People make the decision**; EvalBot informs it.
|
| 37 |
|
| 38 |
+
---
|
| 39 |
|
| 40 |
+
## The science
|
|
|
|
| 41 |
|
| 42 |
+
| Trait | EvalBot (r) | A single human rater (r) |
|
| 43 |
+
|---|---|---|
|
| 44 |
+
| Few filler words | **0.61** | 0.52 |
|
| 45 |
+
| Good use of pauses | **0.55** | 0.15 |
|
| 46 |
+
| Structured answers | **0.47** | 0.37 |
|
| 47 |
+
| Calmness | **0.42** | 0.34 |
|
| 48 |
+
| Enthusiasm | 0.55 | 0.56 |
|
| 49 |
+
| Engaging tone | 0.54 | 0.62 |
|
| 50 |
+
| Hiring recommendation | 0.46 | 0.50 |
|
| 51 |
+
| Overall impression | 0.40 | 0.50 |
|
| 52 |
|
| 53 |
+
*Pearson correlation with the panel's average rating. EvalBot: 10-fold cross-validation grouped by participant, so the model is always tested on people it never saw (each participant was interviewed twice). Human rater: each Mechanical Turk rater's correlation with the average of the other raters.*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
How the models were built:
|
| 56 |
+
1. The 138 recordings were diarized locally (energy VAD, NVIDIA TitaNet speaker embeddings, agglomerative clustering) to isolate the candidate's speech.
|
| 57 |
+
2. The **same feature extractor the app uses at runtime** (`calibration.py`) computed 30 voice and language features per interview: pitch variation, loudness dynamics, pauses, speaking rate, filler-word rate, vocabulary, sentence length, and more.
|
| 58 |
+
3. Per-trait Ridge or Extra-Trees models were selected by cross-validation; only traits with r ≥ 0.35 are shown in the app. Inputs are clipped to the training range to avoid extrapolation.
|
| 59 |
|
| 60 |
+
A research benchmark that also used the dataset's facial and PRAAT features reached r = 0.52 for both overall impression and hiring recommendation, and r ≈ 0.70 for enthusiasm, smiling and friendliness. Video features are not used in the deployed model yet.
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
The dataset itself is **not** included in this repository, as its license does not allow redistribution. Only trained models are shipped.
|
|
|
|
| 63 |
|
| 64 |
+
---
|
| 65 |
|
| 66 |
+
## Architecture
|
| 67 |
|
| 68 |
+
```
|
| 69 |
+
Browser (React + TypeScript + Tailwind, EN/AR, dark mode)
|
| 70 |
+
├─ interview room: speech synthesis, MediaRecorder, live waveform, MediaPipe face metrics
|
| 71 |
+
└─ Supabase Auth (email/password, Google)
|
| 72 |
+
│
|
| 73 |
+
FastAPI (this Space, Docker)
|
| 74 |
+
├─ /api/... platform API: sessions, answers, reports, jobs, reviews
|
| 75 |
+
├─ pipeline AssemblyAI transcription · librosa voice analysis · calibrated trait models
|
| 76 |
+
│ Gemini (structured JSON) for questions, per-answer feedback and summaries
|
| 77 |
+
│ ReportLab PDF (English / right-to-left Arabic)
|
| 78 |
+
└─ /demo standalone analyzer for a full recorded interview + single-question practice
|
| 79 |
+
│
|
| 80 |
+
Supabase Postgres (data) + Supabase Storage (recordings, PDFs)
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
### Configuration (Space secrets)
|
| 84 |
+
|
| 85 |
+
| Secret | Purpose |
|
| 86 |
+
|---|---|
|
| 87 |
+
| `ASSEMBLYAI_API_KEY` | Speech-to-text and diarization |
|
| 88 |
+
| `GEMINI_API_KEY` | Questions, feedback and summaries |
|
| 89 |
+
| `DATABASE_URL` | Supabase Postgres connection string (transaction pooler) |
|
| 90 |
+
| `SUPABASE_URL`, `SUPABASE_ANON_KEY` | Authentication (public values) |
|
| 91 |
+
| `SUPABASE_SERVICE_ROLE_KEY` | Server-side storage access |
|
| 92 |
+
| `PINECONE_API_KEY` | Optional; a built-in vector index is used otherwise |
|
| 93 |
|
| 94 |
+
Optional: `GEMINI_MODEL` (default `gemini-3.5-flash-lite`, with automatic fallback to other Flash models), `STORAGE_BUCKET`.
|
| 95 |
|
| 96 |
+
### Run locally
|
| 97 |
|
| 98 |
```bash
|
| 99 |
+
docker build -t evalbot .
|
| 100 |
+
docker run -p 7860:7860 --env-file .env evalbot # open http://localhost:7860
|
|
|
|
| 101 |
```
|
| 102 |
|
| 103 |
+
For frontend development: `cd frontend && npm install && npm run dev` (proxies `/api` to the backend on port 7870).
|
| 104 |
+
|
| 105 |
+
---
|
| 106 |
+
|
| 107 |
+
## Credits
|
| 108 |
+
|
| 109 |
+
EvalBot began as a graduation project at the Faculty of Computers and Artificial Intelligence, Benha University (2025), and was continued as an open platform by Nourhan Saber.
|
| 110 |
|
| 111 |
+
Dataset: I. Naim, M. I. Tanveer, D. Gildea, M. E. Hoque, *Automated Analysis and Prediction of Job Interview Performance*, IEEE Transactions on Affective Computing. Arabic PDF font: Amiri (SIL Open Font License).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -27,6 +27,8 @@ from fastapi.responses import FileResponse, HTMLResponse
|
|
| 27 |
from pydantic import BaseModel
|
| 28 |
|
| 29 |
import process_interview as pipeline
|
|
|
|
|
|
|
| 30 |
|
| 31 |
logger = logging.getLogger("evalbot.app")
|
| 32 |
|
|
@@ -41,7 +43,8 @@ BASE_URL = os.getenv("BASE_URL", "https://evalbot-audio-evalbot.hf.space").rstri
|
|
| 41 |
MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "100"))
|
| 42 |
ALLOWED_EXT = {".wav", ".mp3", ".m4a", ".flac", ".ogg", ".webm", ".mp4", ".aac", ".opus"}
|
| 43 |
|
| 44 |
-
app = FastAPI(title="EvalBot
|
|
|
|
| 45 |
_jobs: Dict[str, Dict] = {}
|
| 46 |
_job_lock = threading.Lock()
|
| 47 |
_pipeline_lock = threading.Semaphore(int(os.getenv("MAX_CONCURRENT_JOBS", "1")))
|
|
@@ -50,6 +53,12 @@ _pipeline_lock = threading.Semaphore(int(os.getenv("MAX_CONCURRENT_JOBS", "1")))
|
|
| 50 |
@app.on_event("startup")
|
| 51 |
def warm_up():
|
| 52 |
threading.Thread(target=pipeline.load_models, daemon=True).start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
|
| 55 |
SAMPLE_AUDIO = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "sample_interview.mp3")
|
|
@@ -247,7 +256,24 @@ def get_output(kind: str, filename: str):
|
|
| 247 |
filename=safe)
|
| 248 |
|
| 249 |
|
| 250 |
-
@app.get("/", response_class=HTMLResponse)
|
| 251 |
-
def
|
| 252 |
with open(os.path.join(os.path.dirname(__file__), "static_ui.html"), encoding="utf-8") as f:
|
| 253 |
return f.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
from pydantic import BaseModel
|
| 28 |
|
| 29 |
import process_interview as pipeline
|
| 30 |
+
from platform_app import core as platform_core
|
| 31 |
+
from platform_app import routes as platform_routes
|
| 32 |
|
| 33 |
logger = logging.getLogger("evalbot.app")
|
| 34 |
|
|
|
|
| 43 |
MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "100"))
|
| 44 |
ALLOWED_EXT = {".wav", ".mp3", ".m4a", ".flac", ".ogg", ".webm", ".mp4", ".aac", ".opus"}
|
| 45 |
|
| 46 |
+
app = FastAPI(title="EvalBot", version="3.0")
|
| 47 |
+
app.include_router(platform_routes.router)
|
| 48 |
_jobs: Dict[str, Dict] = {}
|
| 49 |
_job_lock = threading.Lock()
|
| 50 |
_pipeline_lock = threading.Semaphore(int(os.getenv("MAX_CONCURRENT_JOBS", "1")))
|
|
|
|
| 53 |
@app.on_event("startup")
|
| 54 |
def warm_up():
|
| 55 |
threading.Thread(target=pipeline.load_models, daemon=True).start()
|
| 56 |
+
try:
|
| 57 |
+
platform_core.init_db()
|
| 58 |
+
if platform_core.enabled():
|
| 59 |
+
platform_core.ensure_bucket()
|
| 60 |
+
except Exception:
|
| 61 |
+
logger.exception("Platform initialisation failed")
|
| 62 |
|
| 63 |
|
| 64 |
SAMPLE_AUDIO = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "sample_interview.mp3")
|
|
|
|
| 256 |
filename=safe)
|
| 257 |
|
| 258 |
|
| 259 |
+
@app.get("/demo", response_class=HTMLResponse)
|
| 260 |
+
def demo():
|
| 261 |
with open(os.path.join(os.path.dirname(__file__), "static_ui.html"), encoding="utf-8") as f:
|
| 262 |
return f.read()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# ---- Single-page web app (built from ./frontend into ./frontend/dist) ----------------------
|
| 266 |
+
DIST = os.path.join(os.path.dirname(os.path.abspath(__file__)), "frontend", "dist")
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
@app.get("/{full_path:path}", include_in_schema=False)
|
| 270 |
+
def spa(full_path: str):
|
| 271 |
+
if full_path.startswith(("api/", "static/", "jobs/", "practice/")):
|
| 272 |
+
raise HTTPException(404)
|
| 273 |
+
candidate = os.path.normpath(os.path.join(DIST, full_path))
|
| 274 |
+
if full_path and candidate.startswith(DIST) and os.path.isfile(candidate):
|
| 275 |
+
return FileResponse(candidate)
|
| 276 |
+
index_html = os.path.join(DIST, "index.html")
|
| 277 |
+
if os.path.isfile(index_html):
|
| 278 |
+
return FileResponse(index_html, headers={"Cache-Control": "no-cache"})
|
| 279 |
+
return demo()
|
assets/models/calibrated_scores.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d3992befc5a2a4c6204b6ab3272fc5854106735a973902895baf65cb9931e726
|
| 3 |
+
size 6338464
|
calibration.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Human-calibrated interview scores.
|
| 2 |
+
|
| 3 |
+
Models trained to predict the ratings that panels of human raters gave to 138 real mock
|
| 4 |
+
interviews (MIT Interview Dataset, ~9 raters per interview). The same feature extractor
|
| 5 |
+
is used for training and at runtime, so the model sees identical inputs in both places.
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
from typing import Dict, List, Optional
|
| 10 |
+
|
| 11 |
+
import joblib
|
| 12 |
+
import librosa
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 16 |
+
MODEL_PATH = os.path.join(HERE, "assets", "models", "calibrated_scores.joblib")
|
| 17 |
+
|
| 18 |
+
# ---------------------------------------------------------------------------------------
|
| 19 |
+
# Text features (from the candidate's words)
|
| 20 |
+
# ---------------------------------------------------------------------------------------
|
| 21 |
+
FILLERS = re.compile(r"\b(um+|uh+|uhm+|er+|ah+|hmm+|like|you know|i mean|kind of|sort of|basically|actually)\b")
|
| 22 |
+
POS = set("good great love enjoy excited happy interesting passion passionate fun amazing excellent best success "
|
| 23 |
+
"successful proud glad".split())
|
| 24 |
+
NEG = set("bad hard difficult problem problems stress stressed worried hate fail failed failure wrong sorry "
|
| 25 |
+
"unfortunately".split())
|
| 26 |
+
TENTATIVE = set("maybe perhaps guess probably possibly somewhat seems".split())
|
| 27 |
+
WE = {"we", "us", "our", "team", "together"}
|
| 28 |
+
I_WORDS = {"i", "me", "my", "i'm", "i've", "myself"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def text_features(turns: List[str]) -> Dict[str, float]:
|
| 32 |
+
text = " ".join(turns).lower()
|
| 33 |
+
words = re.findall(r"[a-z']+", text)
|
| 34 |
+
n = max(len(words), 1)
|
| 35 |
+
sents = [s for s in re.split(r"[.!?]+", text) if s.strip()]
|
| 36 |
+
return {
|
| 37 |
+
"txt_words": len(words),
|
| 38 |
+
"txt_words_per_turn": len(words) / max(len(turns), 1),
|
| 39 |
+
"txt_type_token": len(set(words)) / n,
|
| 40 |
+
"txt_filler_rate": len(FILLERS.findall(text)) / n,
|
| 41 |
+
"txt_i_rate": sum(w in I_WORDS for w in words) / n,
|
| 42 |
+
"txt_we_rate": sum(w in WE for w in words) / n,
|
| 43 |
+
"txt_pos_rate": sum(w in POS for w in words) / n,
|
| 44 |
+
"txt_neg_rate": sum(w in NEG for w in words) / n,
|
| 45 |
+
"txt_tentative_rate": sum(w in TENTATIVE for w in words) / n,
|
| 46 |
+
"txt_number_rate": len(re.findall(r"\b\d+\b|\b(one|two|three|four|five|ten|hundred|percent)\b", text)) / n,
|
| 47 |
+
"txt_avg_word_len": float(np.mean([len(w) for w in words])) if words else 0.0,
|
| 48 |
+
"txt_avg_sentence_len": len(words) / max(len(sents), 1),
|
| 49 |
+
"txt_long_word_rate": sum(len(w) >= 7 for w in words) / n,
|
| 50 |
+
"txt_because_rate": len(re.findall(r"\b(because|so that|therefore|which meant|as a result)\b", text)) / n,
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ---------------------------------------------------------------------------------------
|
| 55 |
+
# Voice features (from the candidate's audio segments)
|
| 56 |
+
# ---------------------------------------------------------------------------------------
|
| 57 |
+
def _sample_segments(segments: List[np.ndarray], sr: int, max_seconds: float = 90.0) -> List[np.ndarray]:
|
| 58 |
+
"""Evenly sample segments so pitch tracking stays fast on long interviews."""
|
| 59 |
+
total = sum(len(s) for s in segments) / sr
|
| 60 |
+
if total <= max_seconds:
|
| 61 |
+
return segments
|
| 62 |
+
step = total / max_seconds
|
| 63 |
+
out, acc, nxt = [], 0.0, 0.0
|
| 64 |
+
for s in segments:
|
| 65 |
+
if acc >= nxt:
|
| 66 |
+
out.append(s)
|
| 67 |
+
nxt += step * len(s) / sr
|
| 68 |
+
acc += len(s) / sr
|
| 69 |
+
return out
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def voice_features(y: np.ndarray, sr: int, utterances: List[Dict]) -> Dict[str, float]:
|
| 73 |
+
cand = [u for u in utterances if u["role"] == "Interviewee"]
|
| 74 |
+
other = [u for u in utterances if u["role"] != "Interviewee"]
|
| 75 |
+
seg = lambda u: y[int(u["start"] * sr / 1000): int(u["end"] * sr / 1000)]
|
| 76 |
+
segs = [s for s in (seg(u) for u in cand) if len(s) > sr // 5]
|
| 77 |
+
cand_time = sum((u["end"] - u["start"]) / 1000 for u in cand)
|
| 78 |
+
other_time = sum((u["end"] - u["start"]) / 1000 for u in other)
|
| 79 |
+
f = {
|
| 80 |
+
"voc_talk_share": cand_time / max(cand_time + other_time, 1e-6),
|
| 81 |
+
"voc_turn_len_mean": cand_time / max(len(cand), 1),
|
| 82 |
+
"voc_turns_per_min": len(cand) / max((cand_time + other_time) / 60, 1e-6),
|
| 83 |
+
}
|
| 84 |
+
if not segs:
|
| 85 |
+
return f
|
| 86 |
+
|
| 87 |
+
# pauses inside the candidate's speech
|
| 88 |
+
speech, pauses = 0.0, []
|
| 89 |
+
for s in segs:
|
| 90 |
+
iv = librosa.effects.split(s, top_db=32, frame_length=1024, hop_length=256)
|
| 91 |
+
speech += sum(e - b for b, e in iv) / sr
|
| 92 |
+
pauses += [(b2 - e1) / sr for (_, e1), (b2, _) in zip(iv[:-1], iv[1:]) if (b2 - e1) / sr >= 0.25]
|
| 93 |
+
f.update({
|
| 94 |
+
"voc_speech_ratio": speech / max(cand_time, 1e-6),
|
| 95 |
+
"voc_pauses_per_min": len(pauses) / max(cand_time / 60, 1e-6),
|
| 96 |
+
"voc_pause_mean": float(np.mean(pauses)) if pauses else 0.0,
|
| 97 |
+
"voc_long_pause_rate": sum(p >= 1.0 for p in pauses) / max(cand_time / 60, 1e-6),
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
# loudness dynamics
|
| 101 |
+
rms = np.concatenate([librosa.feature.rms(y=s, frame_length=1024, hop_length=256)[0] for s in segs])
|
| 102 |
+
rms_db = 20 * np.log10(rms + 1e-5)
|
| 103 |
+
voiced_db = rms_db[rms_db > np.percentile(rms_db, 30)]
|
| 104 |
+
f.update({
|
| 105 |
+
"voc_loud_std_db": float(voiced_db.std()),
|
| 106 |
+
"voc_loud_range_db": float(np.percentile(voiced_db, 95) - np.percentile(voiced_db, 10)),
|
| 107 |
+
"voc_shimmer": float(np.mean(np.abs(np.diff(rms))) / (rms.mean() + 1e-9)),
|
| 108 |
+
})
|
| 109 |
+
|
| 110 |
+
# spectral brightness
|
| 111 |
+
cent = np.concatenate([librosa.feature.spectral_centroid(y=s, sr=sr, n_fft=1024, hop_length=512)[0] for s in segs])
|
| 112 |
+
f["voc_centroid_mean"] = float(cent.mean())
|
| 113 |
+
f["voc_centroid_std"] = float(cent.std())
|
| 114 |
+
|
| 115 |
+
# pitch (pYIN on an even sample of up to 90 s)
|
| 116 |
+
pitches = []
|
| 117 |
+
for s in _sample_segments(segs, sr):
|
| 118 |
+
f0, voiced, _ = librosa.pyin(s, fmin=70, fmax=400, sr=sr, frame_length=1024, hop_length=256)
|
| 119 |
+
pitches.append(f0[voiced & ~np.isnan(f0)])
|
| 120 |
+
p = np.concatenate(pitches) if pitches else np.array([])
|
| 121 |
+
if len(p) > 10:
|
| 122 |
+
semis = 12 * np.log2(p / np.median(p))
|
| 123 |
+
f.update({
|
| 124 |
+
"voc_pitch_median": float(np.median(p)),
|
| 125 |
+
"voc_pitch_semitone_std": float(semis.std()),
|
| 126 |
+
"voc_pitch_range_semis": float(np.percentile(semis, 95) - np.percentile(semis, 5)),
|
| 127 |
+
"voc_jitter": float(np.mean(np.abs(np.diff(p))) / p.mean()),
|
| 128 |
+
"voc_voiced_ratio": len(p) / max(sum(len(s) for s in _sample_segments(segs, sr)) / 256, 1),
|
| 129 |
+
})
|
| 130 |
+
return f
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def extract_features(y: np.ndarray, sr: int, utterances: List[Dict], candidate_texts: List[str]) -> Dict[str, float]:
|
| 134 |
+
f = voice_features(y, sr, utterances)
|
| 135 |
+
t = text_features(candidate_texts)
|
| 136 |
+
cand_time = sum((u["end"] - u["start"]) / 1000 for u in utterances if u["role"] == "Interviewee")
|
| 137 |
+
f["voc_speaking_rate"] = t["txt_words"] / max(cand_time, 1e-6)
|
| 138 |
+
f.update(t)
|
| 139 |
+
return f
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ---------------------------------------------------------------------------------------
|
| 143 |
+
# Prediction
|
| 144 |
+
# ---------------------------------------------------------------------------------------
|
| 145 |
+
TRAIT_LABELS = {
|
| 146 |
+
"en": {"Overall": "Overall impression", "RecommendHiring": "Hiring recommendation", "Excited": "Enthusiasm",
|
| 147 |
+
"EngagingTone": "Engaging tone", "Friendly": "Friendliness", "NoFillers": "Few filler words",
|
| 148 |
+
"StructuredAnswers": "Structured answers", "Calm": "Calmness", "Focused": "Focus",
|
| 149 |
+
"Engaged": "Engagement", "Paused": "Good use of pauses", "NotAwkward": "Ease / not awkward",
|
| 150 |
+
"Colleague": "Would be a good colleague", "Authentic": "Authenticity", "NotStressed": "Not stressed",
|
| 151 |
+
"Smiled": "Smiling (heard in the voice)", "EyeContact": "Eye contact", "SpeakingRate": "Speaking pace"},
|
| 152 |
+
"ar": {"Overall": "الانطباع العام", "RecommendHiring": "التوصية بالتعيين", "Excited": "الحماس",
|
| 153 |
+
"EngagingTone": "نبرة جذابة", "Friendly": "الود", "NoFillers": "قلة كلمات الحشو",
|
| 154 |
+
"StructuredAnswers": "تنظيم الإجابات", "Calm": "الهدوء", "Focused": "التركيز",
|
| 155 |
+
"Engaged": "التفاعل", "Paused": "حسن استخدام التوقف", "NotAwkward": "الأريحية",
|
| 156 |
+
"Colleague": "زميل عمل جيد", "Authentic": "المصداقية", "NotStressed": "عدم التوتر",
|
| 157 |
+
"Smiled": "الابتسام (من نبرة الصوت)", "EyeContact": "التواصل البصري", "SpeakingRate": "سرعة الكلام"},
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
_bundle = None
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _load():
|
| 164 |
+
global _bundle
|
| 165 |
+
if _bundle is None and os.path.exists(MODEL_PATH):
|
| 166 |
+
_bundle = joblib.load(MODEL_PATH)
|
| 167 |
+
return _bundle
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def available() -> bool:
|
| 171 |
+
return _load() is not None
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def predict(features: Dict[str, float], lang: str = "en") -> Optional[Dict]:
|
| 175 |
+
"""Predict human-panel ratings (1-7 scale) and place them against the 138 reference interviews."""
|
| 176 |
+
b = _load()
|
| 177 |
+
if b is None:
|
| 178 |
+
return None
|
| 179 |
+
from math import erf, sqrt
|
| 180 |
+
|
| 181 |
+
x = np.array([[features.get(c, np.nan) for c in b["feature_names"]]], dtype=float)
|
| 182 |
+
if "feature_bounds" in b: # keep inputs inside the range seen in training (no wild extrapolation)
|
| 183 |
+
lo, hi = np.array(b["feature_bounds"][0]), np.array(b["feature_bounds"][1])
|
| 184 |
+
x = np.where(np.isnan(x), x, np.clip(x, lo, hi))
|
| 185 |
+
labels = TRAIT_LABELS.get(lang, TRAIT_LABELS["en"])
|
| 186 |
+
traits = []
|
| 187 |
+
for name, m in b["models"].items():
|
| 188 |
+
pred = float(np.clip(m["model"].predict(x)[0], 1, 7))
|
| 189 |
+
z = (pred - m["ref_mean"]) / (m["ref_std"] + 1e-9)
|
| 190 |
+
pct = 50 * (1 + erf(z / sqrt(2)))
|
| 191 |
+
traits.append({"trait": name, "label": labels.get(name, name), "score_1_7": round(pred, 2),
|
| 192 |
+
"percentile": int(round(pct)), "model_r": round(m["cv_r"], 2),
|
| 193 |
+
"human_r": round(m.get("human_r", float("nan")), 2)})
|
| 194 |
+
order = b.get("display_order", [t["trait"] for t in traits])
|
| 195 |
+
traits.sort(key=lambda t: order.index(t["trait"]) if t["trait"] in order else 99)
|
| 196 |
+
return {"traits": traits, "reference": b["reference"], "version": b["version"]}
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def model_card(lang: str = "en") -> Optional[Dict]:
|
| 200 |
+
"""Validation results of the shipped models, for the public 'science' section."""
|
| 201 |
+
b = _load()
|
| 202 |
+
if b is None:
|
| 203 |
+
return None
|
| 204 |
+
labels = TRAIT_LABELS.get(lang, TRAIT_LABELS["en"])
|
| 205 |
+
order = b.get("display_order", list(b["models"]))
|
| 206 |
+
traits = sorted(b["models"].items(), key=lambda kv: order.index(kv[0]) if kv[0] in order else 99)
|
| 207 |
+
return {"reference": b["reference"], "version": b["version"],
|
| 208 |
+
"traits": [{"trait": k, "label": labels.get(k, k), "model_r": round(m["cv_r"], 2),
|
| 209 |
+
"human_r": round(m.get("human_r", 0), 2)} for k, m in traits]}
|
frontend/index.html
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en" dir="ltr">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
+
<meta name="description" content="EvalBot: AI mock interviews and hiring interviews for every career track, with feedback calibrated on real human raters." />
|
| 7 |
+
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
| 9 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
| 10 |
+
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600&family=Readex+Pro:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
| 11 |
+
<title>EvalBot: AI interview practice and hiring</title>
|
| 12 |
+
</head>
|
| 13 |
+
<body>
|
| 14 |
+
<div id="root"></div>
|
| 15 |
+
<script type="module" src="/src/main.tsx"></script>
|
| 16 |
+
</body>
|
| 17 |
+
</html>
|
frontend/package-lock.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
frontend/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "evalbot-web",
|
| 3 |
+
"private": true,
|
| 4 |
+
"version": "1.0.0",
|
| 5 |
+
"type": "module",
|
| 6 |
+
"scripts": {
|
| 7 |
+
"dev": "vite",
|
| 8 |
+
"build": "tsc -b && vite build",
|
| 9 |
+
"preview": "vite preview"
|
| 10 |
+
},
|
| 11 |
+
"dependencies": {
|
| 12 |
+
"@mediapipe/tasks-vision": "0.10.21",
|
| 13 |
+
"@supabase/supabase-js": "2.118.0",
|
| 14 |
+
"lucide-react": "0.511.0",
|
| 15 |
+
"react": "19.1.0",
|
| 16 |
+
"react-dom": "19.1.0",
|
| 17 |
+
"react-router-dom": "7.6.0",
|
| 18 |
+
"recharts": "2.15.3"
|
| 19 |
+
},
|
| 20 |
+
"devDependencies": {
|
| 21 |
+
"@tailwindcss/vite": "4.1.7",
|
| 22 |
+
"@types/react": "19.1.4",
|
| 23 |
+
"@types/react-dom": "19.1.5",
|
| 24 |
+
"@vitejs/plugin-react": "4.4.1",
|
| 25 |
+
"tailwindcss": "4.1.7",
|
| 26 |
+
"typescript": "5.8.3",
|
| 27 |
+
"vite": "6.3.5"
|
| 28 |
+
}
|
| 29 |
+
}
|
frontend/public/favicon.svg
ADDED
|
|
frontend/src/components/Shell.tsx
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Briefcase, History, LayoutDashboard, LogOut, Menu, Moon, Plus, Settings, Sun, UploadCloud, X } from "lucide-react";
|
| 2 |
+
import { useState, type ReactNode } from "react";
|
| 3 |
+
import { Link, NavLink, useNavigate } from "react-router-dom";
|
| 4 |
+
import { useAuth } from "../lib/auth";
|
| 5 |
+
import { useI18n } from "../lib/i18n";
|
| 6 |
+
import { Logo, useTheme } from "./ui";
|
| 7 |
+
|
| 8 |
+
export function LangSwitch() {
|
| 9 |
+
const { lang, setLang } = useI18n();
|
| 10 |
+
return (
|
| 11 |
+
<button onClick={() => setLang(lang === "ar" ? "en" : "ar")} className="rounded-lg px-2.5 py-1.5 text-sm font-medium text-muted hover:bg-sunken hover:text-ink"
|
| 12 |
+
aria-label="Change language">
|
| 13 |
+
{lang === "ar" ? "English" : "العربية"}
|
| 14 |
+
</button>
|
| 15 |
+
);
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
export function ThemeSwitch() {
|
| 19 |
+
const [dark, toggle] = useTheme();
|
| 20 |
+
const { t } = useI18n();
|
| 21 |
+
return (
|
| 22 |
+
<button onClick={toggle} className="rounded-lg p-2 text-muted hover:bg-sunken hover:text-ink" aria-label={dark ? t("theme_light") : t("theme_dark")}>
|
| 23 |
+
{dark ? <Sun size={18} /> : <Moon size={18} />}
|
| 24 |
+
</button>
|
| 25 |
+
);
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
export function PublicHeader() {
|
| 29 |
+
const { profile } = useAuth();
|
| 30 |
+
const { t } = useI18n();
|
| 31 |
+
return (
|
| 32 |
+
<header className="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-5 sm:px-6">
|
| 33 |
+
<Link to="/" aria-label="EvalBot home"><Logo /></Link>
|
| 34 |
+
<nav className="flex items-center gap-1 sm:gap-2">
|
| 35 |
+
<LangSwitch />
|
| 36 |
+
<ThemeSwitch />
|
| 37 |
+
{profile ? (
|
| 38 |
+
<Link to="/app" className="rounded-xl bg-nile px-4 py-2 text-sm font-medium text-white dark:text-paper">{t("nav_dashboard")}</Link>
|
| 39 |
+
) : (
|
| 40 |
+
<>
|
| 41 |
+
<Link to="/login" className="hidden rounded-xl px-3 py-2 text-sm font-medium text-ink hover:bg-sunken sm:inline-block">{t("sign_in")}</Link>
|
| 42 |
+
<Link to="/signup" className="rounded-xl bg-nile px-4 py-2 text-sm font-medium text-white dark:text-paper">{t("get_started")}</Link>
|
| 43 |
+
</>
|
| 44 |
+
)}
|
| 45 |
+
</nav>
|
| 46 |
+
</header>
|
| 47 |
+
);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export function AppShell({ children }: { children: ReactNode }) {
|
| 51 |
+
const { profile, signOut } = useAuth();
|
| 52 |
+
const { t } = useI18n();
|
| 53 |
+
const nav = useNavigate();
|
| 54 |
+
const [open, setOpen] = useState(false);
|
| 55 |
+
const isRecruiter = profile?.role === "recruiter";
|
| 56 |
+
const links = isRecruiter
|
| 57 |
+
? [
|
| 58 |
+
{ to: "/app/jobs", icon: Briefcase, label: t("nav_jobs") },
|
| 59 |
+
{ to: "/app", icon: LayoutDashboard, label: t("nav_dashboard"), end: true },
|
| 60 |
+
{ to: "/app/new", icon: Plus, label: t("nav_new") },
|
| 61 |
+
{ to: "/app/history", icon: History, label: t("nav_history") },
|
| 62 |
+
]
|
| 63 |
+
: [
|
| 64 |
+
{ to: "/app", icon: LayoutDashboard, label: t("nav_dashboard"), end: true },
|
| 65 |
+
{ to: "/app/new", icon: Plus, label: t("nav_new") },
|
| 66 |
+
{ to: "/app/history", icon: History, label: t("nav_history") },
|
| 67 |
+
];
|
| 68 |
+
const item = "flex items-center gap-3 rounded-xl px-3 py-2.5 text-[15px] font-medium transition-colors";
|
| 69 |
+
const sidebar = (
|
| 70 |
+
<div className="flex h-full flex-col gap-1 p-4">
|
| 71 |
+
<Link to="/" className="mb-6 px-2" onClick={() => setOpen(false)}><Logo /></Link>
|
| 72 |
+
{links.map((l) => (
|
| 73 |
+
<NavLink key={l.to} to={l.to} end={l.end} onClick={() => setOpen(false)}
|
| 74 |
+
className={({ isActive }) => `${item} ${isActive ? "bg-nile-soft text-nile-deep" : "text-muted hover:bg-sunken hover:text-ink"}`}>
|
| 75 |
+
<l.icon size={18} /> {l.label}
|
| 76 |
+
</NavLink>
|
| 77 |
+
))}
|
| 78 |
+
<a href="/demo" className={`${item} text-muted hover:bg-sunken hover:text-ink`}><UploadCloud size={18} /> {t("nav_quick")}</a>
|
| 79 |
+
<div className="mt-auto flex flex-col gap-1 border-t border-line pt-3">
|
| 80 |
+
<NavLink to="/app/settings" onClick={() => setOpen(false)}
|
| 81 |
+
className={({ isActive }) => `${item} ${isActive ? "bg-nile-soft text-nile-deep" : "text-muted hover:bg-sunken hover:text-ink"}`}>
|
| 82 |
+
<Settings size={18} /> {t("nav_settings")}
|
| 83 |
+
</NavLink>
|
| 84 |
+
<button className={`${item} text-muted hover:bg-sunken hover:text-ink`} onClick={async () => { await signOut(); nav("/"); }}>
|
| 85 |
+
<LogOut size={18} className="rtl:rotate-180" /> {t("sign_out")}
|
| 86 |
+
</button>
|
| 87 |
+
<div className="flex items-center gap-1 px-1 pt-2"><LangSwitch /><ThemeSwitch /></div>
|
| 88 |
+
{profile && <p className="truncate px-3 pt-1 text-xs text-muted">{profile.full_name || profile.email}{profile.company ? `, ${profile.company.name}` : ""}</p>}
|
| 89 |
+
</div>
|
| 90 |
+
</div>
|
| 91 |
+
);
|
| 92 |
+
return (
|
| 93 |
+
<div className="min-h-screen lg:flex">
|
| 94 |
+
<aside className="sticky top-0 hidden h-screen w-64 flex-none border-e border-line bg-surface lg:block">{sidebar}</aside>
|
| 95 |
+
<div className="flex items-center justify-between border-b border-line bg-surface px-4 py-3 lg:hidden">
|
| 96 |
+
<Link to="/app"><Logo size={24} /></Link>
|
| 97 |
+
<button onClick={() => setOpen(true)} className="rounded-lg p-2 text-ink hover:bg-sunken" aria-label="Menu"><Menu size={22} /></button>
|
| 98 |
+
</div>
|
| 99 |
+
{open && (
|
| 100 |
+
<div className="fixed inset-0 z-40 lg:hidden" role="dialog" aria-modal="true">
|
| 101 |
+
<div className="absolute inset-0 bg-ink/40" onClick={() => setOpen(false)} />
|
| 102 |
+
<div className="absolute inset-y-0 start-0 w-72 bg-surface shadow-xl">
|
| 103 |
+
<button onClick={() => setOpen(false)} className="absolute end-3 top-4 rounded-lg p-2 text-muted hover:bg-sunken" aria-label="Close"><X size={20} /></button>
|
| 104 |
+
{sidebar}
|
| 105 |
+
</div>
|
| 106 |
+
</div>
|
| 107 |
+
)}
|
| 108 |
+
<main className="min-w-0 flex-1 px-4 py-6 sm:px-8 sm:py-8">
|
| 109 |
+
<div className="mx-auto max-w-5xl">{children}</div>
|
| 110 |
+
</main>
|
| 111 |
+
</div>
|
| 112 |
+
);
|
| 113 |
+
}
|
frontend/src/components/ui.tsx
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Loader2 } from "lucide-react";
|
| 2 |
+
import { useEffect, useState, type ButtonHTMLAttributes, type InputHTMLAttributes, type ReactNode, type TextareaHTMLAttributes } from "react";
|
| 3 |
+
import { api, type Catalog } from "../lib/api";
|
| 4 |
+
import { useI18n } from "../lib/i18n";
|
| 5 |
+
|
| 6 |
+
/* ---------- brand ---------- */
|
| 7 |
+
export function Logo({ size = 28 }: { size?: number }) {
|
| 8 |
+
return (
|
| 9 |
+
<span className="inline-flex items-center gap-2 font-display text-lg font-semibold text-ink">
|
| 10 |
+
<svg width={size} height={size} viewBox="0 0 32 32" aria-hidden="true">
|
| 11 |
+
<rect width="32" height="32" rx="8" fill="var(--color-nile)" />
|
| 12 |
+
<g fill="var(--color-amber)">
|
| 13 |
+
<rect x="6" y="13" width="3" height="6" rx="1.5" />
|
| 14 |
+
<rect x="11" y="9" width="3" height="14" rx="1.5" />
|
| 15 |
+
<rect x="16" y="6" width="3" height="20" rx="1.5" />
|
| 16 |
+
<rect x="21" y="11" width="3" height="10" rx="1.5" />
|
| 17 |
+
</g>
|
| 18 |
+
</svg>
|
| 19 |
+
EvalBot
|
| 20 |
+
</span>
|
| 21 |
+
);
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
/* ---------- waveform: the visual signature (voice) ---------- */
|
| 25 |
+
export function Waveform({ levels, bars = 28, animated = false, className = "", color = "var(--color-amber)" }:
|
| 26 |
+
{ levels?: number[]; bars?: number; animated?: boolean; className?: string; color?: string }) {
|
| 27 |
+
const values = levels ?? Array.from({ length: bars }, (_, i) => 0.35 + 0.65 * Math.abs(Math.sin(i * 1.7) * Math.cos(i * 0.6)));
|
| 28 |
+
return (
|
| 29 |
+
<div className={`flex h-full items-center gap-[3px] ${className}`} aria-hidden="true">
|
| 30 |
+
{values.map((v, i) => (
|
| 31 |
+
<span
|
| 32 |
+
key={i}
|
| 33 |
+
className={`block w-[4px] rounded-full ${animated ? "wave-bar" : ""}`}
|
| 34 |
+
style={{
|
| 35 |
+
height: `${Math.max(8, Math.min(1, v) * 100)}%`,
|
| 36 |
+
background: color,
|
| 37 |
+
animationDelay: animated ? `${(i % 9) * 0.11}s` : undefined,
|
| 38 |
+
transition: levels ? "height 80ms linear" : undefined,
|
| 39 |
+
}}
|
| 40 |
+
/>
|
| 41 |
+
))}
|
| 42 |
+
</div>
|
| 43 |
+
);
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
/* ---------- buttons & fields ---------- */
|
| 47 |
+
type BtnProps = ButtonHTMLAttributes<HTMLButtonElement> & { variant?: "primary" | "quiet" | "outline" | "danger"; busy?: boolean; size?: "md" | "lg" };
|
| 48 |
+
export function Button({ variant = "primary", busy, size = "md", className = "", children, disabled, ...rest }: BtnProps) {
|
| 49 |
+
const base = "inline-flex items-center justify-center gap-2 rounded-xl font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed";
|
| 50 |
+
const sizes = size === "lg" ? "px-6 py-3.5 text-base" : "px-4 py-2.5 text-[15px]";
|
| 51 |
+
const styles = {
|
| 52 |
+
primary: "bg-nile text-white hover:bg-nile-deep dark:text-paper",
|
| 53 |
+
quiet: "text-ink hover:bg-sunken",
|
| 54 |
+
outline: "border border-line bg-surface text-ink hover:border-nile hover:text-nile",
|
| 55 |
+
danger: "bg-danger text-white hover:opacity-90",
|
| 56 |
+
}[variant];
|
| 57 |
+
return (
|
| 58 |
+
<button className={`${base} ${sizes} ${styles} ${className}`} disabled={disabled || busy} {...rest}>
|
| 59 |
+
{busy && <Loader2 size={16} className="animate-spin" />}
|
| 60 |
+
{children}
|
| 61 |
+
</button>
|
| 62 |
+
);
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
export function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
|
| 66 |
+
return (
|
| 67 |
+
<label className="block">
|
| 68 |
+
<span className="mb-1.5 block text-sm font-medium text-ink">{label}</span>
|
| 69 |
+
{children}
|
| 70 |
+
{hint && <span className="mt-1 block text-xs text-muted">{hint}</span>}
|
| 71 |
+
</label>
|
| 72 |
+
);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
const inputCls = "w-full rounded-xl border border-line bg-surface px-3.5 py-2.5 text-[15px] text-ink placeholder:text-muted/70 focus:border-nile focus:outline-none";
|
| 76 |
+
export const Input = (p: InputHTMLAttributes<HTMLInputElement>) => <input {...p} className={`${inputCls} ${p.className ?? ""}`} />;
|
| 77 |
+
export const Textarea = (p: TextareaHTMLAttributes<HTMLTextAreaElement>) => <textarea {...p} className={`${inputCls} min-h-28 ${p.className ?? ""}`} />;
|
| 78 |
+
export function Select({ value, onChange, options, className = "" }: { value: string; onChange: (v: string) => void; options: { value: string; label: string }[]; className?: string }) {
|
| 79 |
+
return (
|
| 80 |
+
<select value={value} onChange={(e) => onChange(e.target.value)} className={`${inputCls} ${className}`}>
|
| 81 |
+
{options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
|
| 82 |
+
</select>
|
| 83 |
+
);
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
export function Panel({ children, className = "", title, action }: { children: ReactNode; className?: string; title?: ReactNode; action?: ReactNode }) {
|
| 87 |
+
return (
|
| 88 |
+
<section className={`rounded-2xl border border-line bg-surface p-5 sm:p-6 ${className}`}>
|
| 89 |
+
{(title || action) && (
|
| 90 |
+
<div className="mb-4 flex items-center justify-between gap-3">
|
| 91 |
+
{title && <h2 className="text-lg font-semibold text-ink">{title}</h2>}
|
| 92 |
+
{action}
|
| 93 |
+
</div>
|
| 94 |
+
)}
|
| 95 |
+
{children}
|
| 96 |
+
</section>
|
| 97 |
+
);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
export function Spinner({ label }: { label?: string }) {
|
| 101 |
+
return (
|
| 102 |
+
<div className="flex items-center justify-center gap-3 py-16 text-muted">
|
| 103 |
+
<Loader2 className="animate-spin" size={20} /> {label}
|
| 104 |
+
</div>
|
| 105 |
+
);
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
export function ErrorNote({ children }: { children: ReactNode }) {
|
| 109 |
+
return <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger" role="alert">{children}</p>;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
/* ---------- score visuals ---------- */
|
| 113 |
+
export function scoreColor(v: number | null | undefined, max = 100) {
|
| 114 |
+
if (v == null) return "var(--color-muted)";
|
| 115 |
+
const r = v / max;
|
| 116 |
+
return r >= 0.7 ? "var(--color-nile)" : r >= 0.5 ? "var(--color-amber)" : "var(--color-danger)";
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
export function ScoreRing({ value, size = 120, max = 100, label }: { value: number | null; size?: number; max?: number; label?: string }) {
|
| 120 |
+
const r = size / 2 - 9;
|
| 121 |
+
const c = 2 * Math.PI * r;
|
| 122 |
+
const v = value == null ? 0 : Math.max(0, Math.min(max, value)) / max;
|
| 123 |
+
return (
|
| 124 |
+
<div className="relative inline-flex flex-none items-center justify-center" style={{ width: size, height: size }} role="img" aria-label={`${label ?? ""} ${value ?? "–"}`}>
|
| 125 |
+
<svg width={size} height={size}>
|
| 126 |
+
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--color-sunken)" strokeWidth="9" />
|
| 127 |
+
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={scoreColor(value, max)} strokeWidth="9" strokeLinecap="round"
|
| 128 |
+
strokeDasharray={`${c * v} ${c}`} transform={`rotate(-90 ${size / 2} ${size / 2})`} />
|
| 129 |
+
</svg>
|
| 130 |
+
<span className="absolute font-display font-semibold tabular text-ink" style={{ fontSize: size * 0.28 }}>
|
| 131 |
+
{value == null ? "–" : Math.round(value)}
|
| 132 |
+
</span>
|
| 133 |
+
</div>
|
| 134 |
+
);
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
export function Meter({ value, max = 100, color }: { value: number; max?: number; color?: string }) {
|
| 138 |
+
return (
|
| 139 |
+
<div className="h-2 w-full overflow-hidden rounded-full bg-sunken">
|
| 140 |
+
<div className="h-full rounded-full" style={{ width: `${Math.max(2, Math.min(100, (value / max) * 100))}%`, background: color ?? scoreColor(value, max) }} />
|
| 141 |
+
</div>
|
| 142 |
+
);
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
export function Badge({ children, tone = "neutral" }: { children: ReactNode; tone?: "neutral" | "good" | "warn" | "bad" | "info" }) {
|
| 146 |
+
const t = {
|
| 147 |
+
neutral: "bg-sunken text-muted",
|
| 148 |
+
good: "bg-nile-soft text-nile-deep",
|
| 149 |
+
warn: "bg-amber-soft text-ink",
|
| 150 |
+
bad: "bg-danger-soft text-danger",
|
| 151 |
+
info: "bg-nile-soft text-nile",
|
| 152 |
+
}[tone];
|
| 153 |
+
return <span className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${t}`}>{children}</span>;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
export function StatusBadge({ status }: { status: string }) {
|
| 157 |
+
const { t } = useI18n();
|
| 158 |
+
const map: Record<string, [string, "neutral" | "good" | "warn" | "bad" | "info"]> = {
|
| 159 |
+
in_progress: [t("st_in_progress"), "warn"], processing: [t("st_processing"), "info"],
|
| 160 |
+
completed: [t("st_completed"), "good"], failed: [t("st_failed"), "bad"],
|
| 161 |
+
};
|
| 162 |
+
const [label, tone] = map[status] ?? [status, "neutral"];
|
| 163 |
+
return <Badge tone={tone}>{label}</Badge>;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
/* ---------- data hooks ---------- */
|
| 167 |
+
let catalogCache: Catalog | null = null;
|
| 168 |
+
export function useCatalog(): Catalog | null {
|
| 169 |
+
const [c, setC] = useState<Catalog | null>(catalogCache);
|
| 170 |
+
useEffect(() => {
|
| 171 |
+
if (!catalogCache) api.get<Catalog>("/catalog").then((x) => { catalogCache = x; setC(x); }).catch(() => undefined);
|
| 172 |
+
}, []);
|
| 173 |
+
return c;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
export function useTheme(): [boolean, () => void] {
|
| 177 |
+
const [dark, setDark] = useState(() => {
|
| 178 |
+
try {
|
| 179 |
+
const s = localStorage.getItem("evalbot_theme");
|
| 180 |
+
if (s) return s === "dark";
|
| 181 |
+
} catch {
|
| 182 |
+
/* ignore */
|
| 183 |
+
}
|
| 184 |
+
return window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false;
|
| 185 |
+
});
|
| 186 |
+
useEffect(() => {
|
| 187 |
+
document.documentElement.classList.toggle("dark", dark);
|
| 188 |
+
try {
|
| 189 |
+
localStorage.setItem("evalbot_theme", dark ? "dark" : "light");
|
| 190 |
+
} catch {
|
| 191 |
+
/* ignore */
|
| 192 |
+
}
|
| 193 |
+
}, [dark]);
|
| 194 |
+
return [dark, () => setDark((d) => !d)];
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
export function fmtDate(iso: string, lang: string) {
|
| 198 |
+
return new Date(iso).toLocaleDateString(lang === "ar" ? "ar-EG" : "en-GB", { day: "numeric", month: "short", year: "numeric" });
|
| 199 |
+
}
|
frontend/src/index.css
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@import "tailwindcss";
|
| 2 |
+
|
| 3 |
+
@custom-variant dark (&:where(.dark, .dark *));
|
| 4 |
+
|
| 5 |
+
@theme {
|
| 6 |
+
--font-sans: "IBM Plex Sans Arabic", system-ui, sans-serif;
|
| 7 |
+
--font-display: "Readex Pro", "IBM Plex Sans Arabic", system-ui, sans-serif;
|
| 8 |
+
|
| 9 |
+
--color-paper: #f3f6f5;
|
| 10 |
+
--color-surface: #ffffff;
|
| 11 |
+
--color-sunken: #e8eeec;
|
| 12 |
+
--color-line: #d5dfdc;
|
| 13 |
+
--color-ink: #102a2c;
|
| 14 |
+
--color-muted: #557173;
|
| 15 |
+
--color-nile: #0e7c66;
|
| 16 |
+
--color-nile-deep: #0a5c4c;
|
| 17 |
+
--color-nile-soft: #dcefe9;
|
| 18 |
+
--color-amber: #f2a93b;
|
| 19 |
+
--color-amber-soft: #fcefd9;
|
| 20 |
+
--color-danger: #c8463d;
|
| 21 |
+
--color-danger-soft: #f8e3e1;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
/* dark theme: same token names, different values */
|
| 25 |
+
.dark {
|
| 26 |
+
--color-paper: #0b1a1b;
|
| 27 |
+
--color-surface: #11292a;
|
| 28 |
+
--color-sunken: #0e2223;
|
| 29 |
+
--color-line: #21403f;
|
| 30 |
+
--color-ink: #e4efec;
|
| 31 |
+
--color-muted: #8fb0ad;
|
| 32 |
+
--color-nile: #2fb393;
|
| 33 |
+
--color-nile-deep: #5fd0b2;
|
| 34 |
+
--color-nile-soft: #133a33;
|
| 35 |
+
--color-amber: #f5b553;
|
| 36 |
+
--color-amber-soft: #3a2c12;
|
| 37 |
+
--color-danger: #ef6b61;
|
| 38 |
+
--color-danger-soft: #3b1c1a;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
html { background: var(--color-paper); color: var(--color-ink); }
|
| 42 |
+
body { font-family: var(--font-sans); font-size: 16px; line-height: 1.6; -webkit-font-smoothing: antialiased; }
|
| 43 |
+
h1, h2, h3, h4 { font-family: var(--font-display); line-height: 1.2; letter-spacing: -0.01em; }
|
| 44 |
+
[dir="rtl"] h1, [dir="rtl"] h2, [dir="rtl"] h3 { letter-spacing: 0; line-height: 1.35; }
|
| 45 |
+
:focus-visible { outline: 2px solid var(--color-nile); outline-offset: 2px; border-radius: 6px; }
|
| 46 |
+
.ltr { direction: ltr; unicode-bidi: isolate; }
|
| 47 |
+
.tabular { font-variant-numeric: tabular-nums; }
|
| 48 |
+
|
| 49 |
+
@keyframes wave { 0%, 100% { transform: scaleY(0.35); } 50% { transform: scaleY(1); } }
|
| 50 |
+
.wave-bar { transform-origin: center; animation: wave 1.1s ease-in-out infinite; }
|
| 51 |
+
@keyframes rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
|
| 52 |
+
.rise { animation: rise 0.5s ease-out both; }
|
| 53 |
+
@keyframes pulse-dot { 50% { opacity: 0.35; } }
|
| 54 |
+
.pulse-dot { animation: pulse-dot 1s ease-in-out infinite; }
|
| 55 |
+
@media (prefers-reduced-motion: reduce) {
|
| 56 |
+
.wave-bar, .rise, .pulse-dot { animation: none !important; }
|
| 57 |
+
}
|
frontend/src/lib/api.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { getAccessToken } from "./auth";
|
| 2 |
+
|
| 3 |
+
export class ApiError extends Error {
|
| 4 |
+
status: number;
|
| 5 |
+
constructor(status: number, message: string) {
|
| 6 |
+
super(message);
|
| 7 |
+
this.status = status;
|
| 8 |
+
}
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
async function request<T>(method: string, path: string, body?: unknown, form?: FormData): Promise<T> {
|
| 12 |
+
const token = await getAccessToken();
|
| 13 |
+
const headers: Record<string, string> = {};
|
| 14 |
+
if (token) headers.Authorization = `Bearer ${token}`;
|
| 15 |
+
if (body !== undefined && !form) headers["Content-Type"] = "application/json";
|
| 16 |
+
const res = await fetch(`/api${path}`, {
|
| 17 |
+
method,
|
| 18 |
+
headers,
|
| 19 |
+
body: form ?? (body !== undefined ? JSON.stringify(body) : undefined),
|
| 20 |
+
});
|
| 21 |
+
if (!res.ok) {
|
| 22 |
+
let msg = res.statusText;
|
| 23 |
+
try {
|
| 24 |
+
const j = await res.json();
|
| 25 |
+
msg = typeof j.detail === "string" ? j.detail : JSON.stringify(j.detail ?? j);
|
| 26 |
+
} catch {
|
| 27 |
+
/* not JSON */
|
| 28 |
+
}
|
| 29 |
+
throw new ApiError(res.status, msg);
|
| 30 |
+
}
|
| 31 |
+
const type = res.headers.get("content-type") || "";
|
| 32 |
+
return (type.includes("application/json") ? res.json() : res.blob()) as Promise<T>;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
export const api = {
|
| 36 |
+
get: <T>(p: string) => request<T>("GET", p),
|
| 37 |
+
post: <T>(p: string, body?: unknown) => request<T>("POST", p, body ?? {}),
|
| 38 |
+
put: <T>(p: string, body?: unknown) => request<T>("PUT", p, body ?? {}),
|
| 39 |
+
patch: <T>(p: string, body?: unknown) => request<T>("PATCH", p, body ?? {}),
|
| 40 |
+
del: <T>(p: string) => request<T>("DELETE", p),
|
| 41 |
+
upload: <T>(p: string, form: FormData) => request<T>("POST", p, undefined, form),
|
| 42 |
+
blob: (p: string) => request<Blob>("GET", p),
|
| 43 |
+
};
|
| 44 |
+
|
| 45 |
+
/* ---------- shared types ---------- */
|
| 46 |
+
export type Profile = {
|
| 47 |
+
id: string;
|
| 48 |
+
email: string | null;
|
| 49 |
+
full_name: string | null;
|
| 50 |
+
role: "candidate" | "recruiter";
|
| 51 |
+
company_id: string | null;
|
| 52 |
+
headline: string | null;
|
| 53 |
+
target_track: string | null;
|
| 54 |
+
locale: string;
|
| 55 |
+
company?: { id: string; name: string; website?: string | null } | null;
|
| 56 |
+
};
|
| 57 |
+
|
| 58 |
+
export type Track = { id: string; en: string; ar: string; group: string };
|
| 59 |
+
export type Catalog = { tracks: Track[]; levels: string[]; types: string[] };
|
| 60 |
+
|
| 61 |
+
export type PlanQuestion = { text: string; kind?: string; skill?: string; rubric?: string; is_followup?: boolean };
|
| 62 |
+
|
| 63 |
+
export type Feedback = {
|
| 64 |
+
score: number | null;
|
| 65 |
+
relevance?: string | null;
|
| 66 |
+
summary?: string;
|
| 67 |
+
strengths?: string[];
|
| 68 |
+
improvements?: string[];
|
| 69 |
+
delivery_tip?: string;
|
| 70 |
+
improved_answer?: string;
|
| 71 |
+
followup_question?: string;
|
| 72 |
+
skill?: string;
|
| 73 |
+
error?: string;
|
| 74 |
+
};
|
| 75 |
+
|
| 76 |
+
export type Answer = {
|
| 77 |
+
id: string;
|
| 78 |
+
idx: number;
|
| 79 |
+
question: string;
|
| 80 |
+
kind: string | null;
|
| 81 |
+
is_followup: boolean;
|
| 82 |
+
duration_s: number | null;
|
| 83 |
+
transcript: string | null;
|
| 84 |
+
voice: Record<string, any> | null;
|
| 85 |
+
presence: Record<string, number> | null;
|
| 86 |
+
feedback: Feedback | null;
|
| 87 |
+
score: number | null;
|
| 88 |
+
has_audio: boolean;
|
| 89 |
+
};
|
| 90 |
+
|
| 91 |
+
export type Trait = { trait: string; label: string; score_1_7: number; percentile: number; model_r: number; human_r: number };
|
| 92 |
+
|
| 93 |
+
export type Report = {
|
| 94 |
+
overall: number | null;
|
| 95 |
+
content_score: number | null;
|
| 96 |
+
delivery_score: number | null;
|
| 97 |
+
duration_s?: number;
|
| 98 |
+
voice: Record<string, any>;
|
| 99 |
+
calibrated: { traits: Trait[]; reference: { interviews: number; raters_per_interview: number } } | null;
|
| 100 |
+
summary: {
|
| 101 |
+
headline?: string;
|
| 102 |
+
executive_summary?: string[];
|
| 103 |
+
strengths?: { competency: string; explanation: string; evidence: string }[];
|
| 104 |
+
weaknesses?: { area: string; feedback: string }[];
|
| 105 |
+
role_fit?: string[];
|
| 106 |
+
recommendations?: { category: string; recommendation: string; how_to: string }[];
|
| 107 |
+
learning_plan?: { topic: string; why: string; how: string }[];
|
| 108 |
+
next_steps?: string[];
|
| 109 |
+
hiring_signal?: "strong_yes" | "yes" | "maybe" | "no";
|
| 110 |
+
};
|
| 111 |
+
};
|
| 112 |
+
|
| 113 |
+
export type Session = {
|
| 114 |
+
id: string;
|
| 115 |
+
user_id: string;
|
| 116 |
+
job_id: string | null;
|
| 117 |
+
mode: "mock" | "job" | "upload";
|
| 118 |
+
track: string | null;
|
| 119 |
+
level: string | null;
|
| 120 |
+
interview_type: string | null;
|
| 121 |
+
language: "en" | "ar";
|
| 122 |
+
status: "in_progress" | "processing" | "completed" | "failed";
|
| 123 |
+
context: { plan: PlanQuestion[]; role?: string; answer_seconds?: number; job_title?: string };
|
| 124 |
+
overall_score: number | null;
|
| 125 |
+
report: Report | null;
|
| 126 |
+
error: string | null;
|
| 127 |
+
created_at: string;
|
| 128 |
+
completed_at: string | null;
|
| 129 |
+
answers?: Answer[];
|
| 130 |
+
job?: { title: string; company: string } | null;
|
| 131 |
+
candidate?: { full_name: string | null; email: string | null; headline: string | null };
|
| 132 |
+
};
|
| 133 |
+
|
| 134 |
+
export type SessionRow = {
|
| 135 |
+
id: string;
|
| 136 |
+
mode: string;
|
| 137 |
+
track: string | null;
|
| 138 |
+
level: string | null;
|
| 139 |
+
status: Session["status"];
|
| 140 |
+
overall_score: number | null;
|
| 141 |
+
created_at: string;
|
| 142 |
+
role: string | null;
|
| 143 |
+
job_title: string | null;
|
| 144 |
+
answered: number;
|
| 145 |
+
planned: number;
|
| 146 |
+
};
|
| 147 |
+
|
| 148 |
+
export type Job = {
|
| 149 |
+
id: string;
|
| 150 |
+
title: string;
|
| 151 |
+
track: string;
|
| 152 |
+
level: string;
|
| 153 |
+
description: string | null;
|
| 154 |
+
questions: PlanQuestion[];
|
| 155 |
+
answer_seconds: number;
|
| 156 |
+
status: "draft" | "open" | "closed";
|
| 157 |
+
share_token: string;
|
| 158 |
+
created_at: string;
|
| 159 |
+
applicants?: number;
|
| 160 |
+
completed?: number;
|
| 161 |
+
};
|
| 162 |
+
|
| 163 |
+
export type CandidateRow = {
|
| 164 |
+
id: string;
|
| 165 |
+
status: Session["status"];
|
| 166 |
+
overall_score: number | null;
|
| 167 |
+
created_at: string;
|
| 168 |
+
content_score: string | null;
|
| 169 |
+
delivery_score: string | null;
|
| 170 |
+
hiring_signal: string | null;
|
| 171 |
+
headline: string | null;
|
| 172 |
+
full_name: string | null;
|
| 173 |
+
email: string | null;
|
| 174 |
+
review_status: "new" | "shortlisted" | "rejected" | "hired";
|
| 175 |
+
rating: number | null;
|
| 176 |
+
notes: string | null;
|
| 177 |
+
};
|
frontend/src/lib/auth.tsx
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createClient, type SupabaseClient } from "@supabase/supabase-js";
|
| 2 |
+
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react";
|
| 3 |
+
import { api, type Profile } from "./api";
|
| 4 |
+
|
| 5 |
+
type Config = { enabled: boolean; supabase_url: string; supabase_anon_key: string; dev_auth: boolean; calibrated_model: boolean };
|
| 6 |
+
|
| 7 |
+
let supabase: SupabaseClient | null = null;
|
| 8 |
+
let config: Config | null = null;
|
| 9 |
+
const DEV_KEY = "evalbot_dev_token";
|
| 10 |
+
|
| 11 |
+
export async function loadConfig(): Promise<Config> {
|
| 12 |
+
if (config) return config;
|
| 13 |
+
const res = await fetch("/api/config");
|
| 14 |
+
config = (await res.json()) as Config;
|
| 15 |
+
if (config.supabase_url && config.supabase_anon_key) {
|
| 16 |
+
supabase = createClient(config.supabase_url, config.supabase_anon_key, {
|
| 17 |
+
auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true },
|
| 18 |
+
});
|
| 19 |
+
}
|
| 20 |
+
return config;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
export async function getAccessToken(): Promise<string | null> {
|
| 24 |
+
if (supabase) {
|
| 25 |
+
const { data } = await supabase.auth.getSession();
|
| 26 |
+
if (data.session) return data.session.access_token;
|
| 27 |
+
}
|
| 28 |
+
try {
|
| 29 |
+
return localStorage.getItem(DEV_KEY);
|
| 30 |
+
} catch {
|
| 31 |
+
return null;
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
type AuthState = {
|
| 36 |
+
ready: boolean;
|
| 37 |
+
config: Config | null;
|
| 38 |
+
profile: Profile | null;
|
| 39 |
+
refresh: () => Promise<void>;
|
| 40 |
+
signIn: (email: string, password: string) => Promise<void>;
|
| 41 |
+
signUp: (email: string, password: string, name: string) => Promise<{ needsConfirmation: boolean }>;
|
| 42 |
+
signInWithGoogle: () => Promise<void>;
|
| 43 |
+
resetPassword: (email: string) => Promise<void>;
|
| 44 |
+
signOut: () => Promise<void>;
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
const Ctx = createContext<AuthState | null>(null);
|
| 48 |
+
|
| 49 |
+
export function AuthProvider({ children }: { children: ReactNode }) {
|
| 50 |
+
const [ready, setReady] = useState(false);
|
| 51 |
+
const [cfg, setCfg] = useState<Config | null>(null);
|
| 52 |
+
const [profile, setProfile] = useState<Profile | null>(null);
|
| 53 |
+
|
| 54 |
+
const refresh = useCallback(async () => {
|
| 55 |
+
const token = await getAccessToken();
|
| 56 |
+
if (!token) {
|
| 57 |
+
setProfile(null);
|
| 58 |
+
return;
|
| 59 |
+
}
|
| 60 |
+
try {
|
| 61 |
+
setProfile(await api.get<Profile>("/me"));
|
| 62 |
+
} catch {
|
| 63 |
+
setProfile(null);
|
| 64 |
+
}
|
| 65 |
+
}, []);
|
| 66 |
+
|
| 67 |
+
useEffect(() => {
|
| 68 |
+
let unsub: (() => void) | undefined;
|
| 69 |
+
loadConfig()
|
| 70 |
+
.then(async (c) => {
|
| 71 |
+
setCfg(c);
|
| 72 |
+
if (supabase) {
|
| 73 |
+
const { data } = supabase.auth.onAuthStateChange(() => {
|
| 74 |
+
refresh();
|
| 75 |
+
});
|
| 76 |
+
unsub = () => data.subscription.unsubscribe();
|
| 77 |
+
}
|
| 78 |
+
await refresh();
|
| 79 |
+
})
|
| 80 |
+
.finally(() => setReady(true));
|
| 81 |
+
return () => unsub?.();
|
| 82 |
+
}, [refresh]);
|
| 83 |
+
|
| 84 |
+
const signIn = async (email: string, password: string) => {
|
| 85 |
+
if (supabase) {
|
| 86 |
+
const { error } = await supabase.auth.signInWithPassword({ email, password });
|
| 87 |
+
if (error) throw error;
|
| 88 |
+
} else if (cfg?.dev_auth) {
|
| 89 |
+
localStorage.setItem(DEV_KEY, `dev:${await devId(email)}:${email}`);
|
| 90 |
+
}
|
| 91 |
+
await refresh();
|
| 92 |
+
};
|
| 93 |
+
|
| 94 |
+
const signUp = async (email: string, password: string, name: string) => {
|
| 95 |
+
if (supabase) {
|
| 96 |
+
const { data, error } = await supabase.auth.signUp({
|
| 97 |
+
email,
|
| 98 |
+
password,
|
| 99 |
+
options: { data: { full_name: name }, emailRedirectTo: `${location.origin}/app` },
|
| 100 |
+
});
|
| 101 |
+
if (error) throw error;
|
| 102 |
+
if (!data.session) return { needsConfirmation: true };
|
| 103 |
+
} else if (cfg?.dev_auth) {
|
| 104 |
+
localStorage.setItem(DEV_KEY, `dev:${await devId(email)}:${email}`);
|
| 105 |
+
}
|
| 106 |
+
await refresh();
|
| 107 |
+
if (name) await api.patch("/me", { full_name: name }).catch(() => undefined);
|
| 108 |
+
await refresh();
|
| 109 |
+
return { needsConfirmation: false };
|
| 110 |
+
};
|
| 111 |
+
|
| 112 |
+
const signInWithGoogle = async () => {
|
| 113 |
+
if (!supabase) return;
|
| 114 |
+
const { error } = await supabase.auth.signInWithOAuth({ provider: "google", options: { redirectTo: `${location.origin}/app` } });
|
| 115 |
+
if (error) throw error;
|
| 116 |
+
};
|
| 117 |
+
|
| 118 |
+
const resetPassword = async (email: string) => {
|
| 119 |
+
if (!supabase) return;
|
| 120 |
+
const { error } = await supabase.auth.resetPasswordForEmail(email, { redirectTo: `${location.origin}/app/settings` });
|
| 121 |
+
if (error) throw error;
|
| 122 |
+
};
|
| 123 |
+
|
| 124 |
+
const signOut = async () => {
|
| 125 |
+
if (supabase) await supabase.auth.signOut();
|
| 126 |
+
try {
|
| 127 |
+
localStorage.removeItem(DEV_KEY);
|
| 128 |
+
} catch {
|
| 129 |
+
/* ignore */
|
| 130 |
+
}
|
| 131 |
+
setProfile(null);
|
| 132 |
+
};
|
| 133 |
+
|
| 134 |
+
return (
|
| 135 |
+
<Ctx.Provider value={{ ready, config: cfg, profile, refresh, signIn, signUp, signInWithGoogle, resetPassword, signOut }}>
|
| 136 |
+
{children}
|
| 137 |
+
</Ctx.Provider>
|
| 138 |
+
);
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
export function useAuth(): AuthState {
|
| 142 |
+
const v = useContext(Ctx);
|
| 143 |
+
if (!v) throw new Error("useAuth outside AuthProvider");
|
| 144 |
+
return v;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
export async function updatePassword(password: string) {
|
| 148 |
+
if (!supabase) return;
|
| 149 |
+
const { error } = await supabase.auth.updateUser({ password });
|
| 150 |
+
if (error) throw error;
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
/* stable pseudo-uuid from an email, for local development sign-in only */
|
| 154 |
+
async function devId(email: string): Promise<string> {
|
| 155 |
+
const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(email.toLowerCase()));
|
| 156 |
+
const h = [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
| 157 |
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
| 158 |
+
}
|
frontend/src/lib/i18n.tsx
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
|
| 2 |
+
|
| 3 |
+
const en = {
|
| 4 |
+
brand: "EvalBot",
|
| 5 |
+
nav_dashboard: "Dashboard", nav_new: "New interview", nav_history: "My interviews", nav_jobs: "Jobs",
|
| 6 |
+
nav_settings: "Settings", nav_quick: "Analyze a recording", sign_out: "Sign out", sign_in: "Sign in", sign_up: "Create account",
|
| 7 |
+
get_started: "Get started", loading: "Loading…", save: "Save", saved: "Saved", cancel: "Cancel", delete: "Delete",
|
| 8 |
+
edit: "Edit", back: "Back", continue: "Continue", retry: "Try again", copy: "Copy", copied: "Copied", theme_dark: "Dark theme",
|
| 9 |
+
theme_light: "Light theme", language: "Language", min: "min", sec: "sec", of: "of", or: "or", optional: "optional",
|
| 10 |
+
error_generic: "Something went wrong. Try again in a moment.",
|
| 11 |
+
|
| 12 |
+
hero_title: "Practice the interview before the interview.",
|
| 13 |
+
hero_sub: "EvalBot asks you real questions for your track, listens to how you answer, and shows you exactly what to fix. Its delivery scores are trained on how panels of human interviewers judged 138 real interviews.",
|
| 14 |
+
cta_candidate: "Start a practice interview", cta_company: "Hire with EvalBot",
|
| 15 |
+
demo_asking: "EvalBot is asking", demo_question: "Tell me about a data pipeline you built, and what broke first.",
|
| 16 |
+
demo_listening: "Listening", demo_you: "You", demo_answer: "We ingested sensor data through Kafka. The first thing that broke was…",
|
| 17 |
+
demo_content: "Content", demo_delivery: "Delivery", demo_structure: "Structure",
|
| 18 |
+
for_candidates: "For job seekers", for_companies: "For hiring teams",
|
| 19 |
+
c1_t: "Any track, any level", c1_d: "Data, backend, design, sales, HR and 25 more tracks, from internship to lead. Paste a job description or your CV and the questions follow it.",
|
| 20 |
+
c2_t: "A real conversation", c2_d: "Questions are read aloud and you answer out loud. When an answer leaves something open, EvalBot asks a follow-up, like a real interviewer would.",
|
| 21 |
+
c3_t: "Feedback you can act on", c3_d: "Every answer gets a score, what worked, what to improve, and a stronger version of what you said, built from your own facts.",
|
| 22 |
+
c4_t: "See yourself improve", c4_d: "Your scores, speaking pace and filler words are tracked across interviews, with a learning plan for your track.",
|
| 23 |
+
r1_t: "Send one link", r1_d: "Create a job with your own questions or AI-suggested ones, and share a single link with applicants.",
|
| 24 |
+
r2_t: "Same interview for everyone", r2_d: "Every applicant answers the same questions with the same time limit, whenever it suits them.",
|
| 25 |
+
r3_t: "A ranked shortlist with reasons", r3_d: "Candidates are ordered by score, each with a written assessment, the recordings and the transcript.",
|
| 26 |
+
r4_t: "Your team decides", r4_d: "Shortlist, reject, rate and leave notes. EvalBot informs the decision; people make it.",
|
| 27 |
+
science_title: "Scored like a panel of interviewers",
|
| 28 |
+
science_text: "We trained EvalBot's delivery scores on the MIT Interview Dataset: 138 recorded mock interviews, each rated by nine people. Tested on people it never saw, EvalBot matches or beats a single human rater on filler words, structure, calmness and pauses, and comes close on enthusiasm and the hiring recommendation.",
|
| 29 |
+
science_model: "EvalBot", science_human: "A single human rater",
|
| 30 |
+
science_note: "Correlation with the panel average, person-grouped cross-validation.",
|
| 31 |
+
how_title: "How a practice interview works",
|
| 32 |
+
how_1: "Pick your track, level and interview style.", how_2: "Answer each question out loud, with your camera on or off.",
|
| 33 |
+
how_3: "Get a full report a minute later, in English or Arabic.",
|
| 34 |
+
tracks_title: "30 career tracks",
|
| 35 |
+
footer_text: "EvalBot started as a graduation project at the Faculty of Computers and Artificial Intelligence, Benha University.",
|
| 36 |
+
footer_privacy: "Your recordings are only visible to you and, for job interviews, to the company you applied to.",
|
| 37 |
+
|
| 38 |
+
auth_signin_title: "Welcome back", auth_signup_title: "Create your account", email: "Email", password: "Password",
|
| 39 |
+
full_name: "Full name", forgot: "Forgot your password?", reset_sent: "We sent a password reset link to your email.",
|
| 40 |
+
google: "Continue with Google", have_account: "Already have an account?", no_account: "New to EvalBot?",
|
| 41 |
+
check_email: "Check your email and click the confirmation link, then sign in.",
|
| 42 |
+
password_hint: "At least 8 characters.",
|
| 43 |
+
accounts_soon: "Accounts are being set up. In the meantime you can analyze a recorded interview or practice single questions.",
|
| 44 |
+
open_demo: "Open the analyzer",
|
| 45 |
+
|
| 46 |
+
onboard_title: "How will you use EvalBot?", onboard_candidate: "Practice interviews",
|
| 47 |
+
onboard_candidate_d: "Prepare for jobs in your track and track your progress.", onboard_recruiter: "Hire for my company",
|
| 48 |
+
onboard_recruiter_d: "Create job interviews and review candidates.", company_name: "Company name", website: "Website",
|
| 49 |
+
|
| 50 |
+
hello: "Hi {name}", dash_sub: "Ready for your next interview?", stat_interviews: "Interviews", stat_average: "Average score",
|
| 51 |
+
stat_best: "Best score", stat_minutes: "Minutes spoken", progress_title: "Your scores over time", skills_title: "Strongest and weakest skills",
|
| 52 |
+
recent: "Recent interviews", empty_dash: "You haven't done an interview yet. Your first one takes about ten minutes.",
|
| 53 |
+
st_in_progress: "Not finished", st_processing: "Building report", st_completed: "Done", st_failed: "Failed",
|
| 54 |
+
resume: "Continue", view_report: "View report", answered_n: "{a} of {b} answered", mock: "Practice", job: "Job interview",
|
| 55 |
+
delete_confirm: "Delete this interview and its recordings?",
|
| 56 |
+
|
| 57 |
+
new_title: "New practice interview", track: "Track", search_tracks: "Search tracks", level: "Level",
|
| 58 |
+
lv_intern: "Internship", lv_junior: "Junior", lv_mid: "Mid-level", lv_senior: "Senior", lv_lead: "Lead / Manager",
|
| 59 |
+
style: "Interview style", ty_mixed: "Mixed", ty_mixed_d: "Technical, behavioral and motivation questions.",
|
| 60 |
+
ty_technical: "Technical", ty_technical_d: "Role knowledge, tools and trade-offs.", ty_behavioral: "Behavioral",
|
| 61 |
+
ty_behavioral_d: "Past experiences, teamwork and conflict.", ty_hr: "HR / Fit", ty_hr_d: "Motivation, goals and culture fit.",
|
| 62 |
+
ty_case: "Problem solving", ty_case_d: "Scenarios you reason through out loud.",
|
| 63 |
+
count: "Number of questions", feedback_lang: "Feedback language", custom_role: "Specific job title",
|
| 64 |
+
custom_role_ph: "e.g. Junior Data Engineer at a fintech", cv: "Your CV", cv_ph: "Paste your CV text so questions can refer to your experience.",
|
| 65 |
+
jd: "Job description", jd_ph: "Paste a job posting to get questions tailored to it.", start: "Start interview",
|
| 66 |
+
preparing: "Preparing your questions…", g_tech: "Technology", g_design: "Design", g_business: "Business", g_other: "Other",
|
| 67 |
+
english: "English", arabic: "العربية",
|
| 68 |
+
|
| 69 |
+
q_of: "Question {n} of {total}", followup: "Follow-up", listen_again: "Listen again", start_answer: "Start answering",
|
| 70 |
+
stop_answer: "I'm done answering", recording: "Recording", time_left: "{t} left", uploading: "Saving your answer…",
|
| 71 |
+
finish_now: "Finish and get my report", camera: "Camera", camera_on: "Turn camera on", camera_off: "Turn camera off",
|
| 72 |
+
camera_hint: "Optional. Only numbers such as eye contact and smiling leave your device, never the video.",
|
| 73 |
+
mic_error: "EvalBot needs your microphone. Allow microphone access in your browser, then try again.",
|
| 74 |
+
get_ready: "Take a breath. Start answering when you're ready.", answers_saved: "{n} answers saved",
|
| 75 |
+
building_title: "Building your report", building_sub: "EvalBot is listening back to your answers, scoring each one and writing your feedback. This takes about a minute.",
|
| 76 |
+
interview_done: "That was the last question.", answer_recorded: "Answer saved", too_short: "That recording was very short. Record your answer again?",
|
| 77 |
+
record_again: "Record again", use_it: "Keep it",
|
| 78 |
+
|
| 79 |
+
overall: "Overall", content: "Content", delivery: "Delivery", calibrated_title: "How a panel of interviewers would likely rate you",
|
| 80 |
+
calibrated_sub: "Your position among 138 real interviews, each rated by nine people. Reliability shows how closely EvalBot matched that panel on people it never saw; a single human rater scores about {h}.",
|
| 81 |
+
reliability: "Reliability", pct: "Better than {p}% of interviews", per_question: "Question by question", your_answer: "Your answer",
|
| 82 |
+
went_well: "What went well", improve: "What to improve", stronger: "A stronger answer", delivery_tip: "Delivery tip",
|
| 83 |
+
summary: "Summary", strengths: "Strengths", weaknesses: "Areas to develop", learning_plan: "What to study next",
|
| 84 |
+
next_steps: "Next steps", role_fit: "Role fit", download_pdf: "Download PDF report", presence: "Camera presence",
|
| 85 |
+
eye_contact: "Looking at the camera", smile: "Smiling", face_visible: "Face in frame", not_answered: "Not answered",
|
| 86 |
+
report_failed: "We couldn't build this report.", voice_title: "Your voice", speaking_rate: "Speaking pace",
|
| 87 |
+
wps: "words per second", fillers: "Filler words", fluency: "Fluency", confidence: "Confidence", anxiety: "Nervousness",
|
| 88 |
+
sig_strong_yes: "Strong hire", sig_yes: "Hire", sig_maybe: "Maybe", sig_no: "Not now", hiring_signal: "Hiring signal",
|
| 89 |
+
practice_again: "Practice this track again", evidence: "Evidence",
|
| 90 |
+
lv: { high: "High", moderate: "Moderate", low: "Low", fluent: "Fluent", disfluent: "Hesitant" } as Record<string, string>,
|
| 91 |
+
|
| 92 |
+
jobs_title: "Jobs", new_job: "New job", empty_jobs: "Create your first job to get an interview link to share with applicants.",
|
| 93 |
+
applicants: "Applicants", completed_n: "Completed", copy_link: "Copy interview link", link_copied: "Link copied",
|
| 94 |
+
jst_open: "Open", jst_draft: "Draft", jst_closed: "Closed", job_title: "Job title", job_desc: "Description",
|
| 95 |
+
answer_time: "Time per answer", questions: "Questions", add_question: "Add question", suggest: "Suggest questions with AI",
|
| 96 |
+
suggesting: "Writing questions…", save_job: "Save job", job_status: "Status", question_ph: "Write a question",
|
| 97 |
+
candidates_title: "Candidates, highest score first", empty_candidates: "No one has interviewed yet. Share the interview link with applicants.",
|
| 98 |
+
c_name: "Candidate", c_score: "Score", c_signal: "EvalBot signal", c_status: "Your decision", c_date: "Date",
|
| 99 |
+
rv_new: "New", rv_shortlisted: "Shortlisted", rv_rejected: "Rejected", rv_hired: "Hired", all: "All",
|
| 100 |
+
decision: "Decision", rating: "Your rating", notes: "Notes for your team", save_review: "Save decision",
|
| 101 |
+
fairness: "Scores support your judgment; they don't replace it. Listen to the answers before deciding.",
|
| 102 |
+
share_hint: "Anyone with this link can take the interview after signing in.",
|
| 103 |
+
|
| 104 |
+
apply_title: "{company} invited you to interview", apply_for: "for {title}", apply_q: "{n} questions",
|
| 105 |
+
apply_time: "Up to {m} minutes per answer", apply_how: "You'll answer each question out loud. Find a quiet place and allow microphone access.",
|
| 106 |
+
apply_start: "Start the interview", apply_signin: "Sign in to start", apply_closed: "This job isn't accepting interviews any more.",
|
| 107 |
+
apply_done: "You've completed this interview. The hiring team will review it.",
|
| 108 |
+
|
| 109 |
+
settings_title: "Settings", profile: "Profile", headline: "Headline", headline_ph: "e.g. Data engineering graduate",
|
| 110 |
+
target_track: "Target track", new_password: "New password", change_password: "Change password", password_changed: "Password changed",
|
| 111 |
+
company: "Company",
|
| 112 |
+
};
|
| 113 |
+
|
| 114 |
+
type Dict = typeof en;
|
| 115 |
+
|
| 116 |
+
const ar: Dict = {
|
| 117 |
+
brand: "EvalBot",
|
| 118 |
+
nav_dashboard: "الرئيسية", nav_new: "مقابلة جديدة", nav_history: "مقابلاتي", nav_jobs: "الوظائف",
|
| 119 |
+
nav_settings: "الإعدادات", nav_quick: "تحليل تسجيل", sign_out: "تسجيل الخروج", sign_in: "تسجيل الدخول", sign_up: "إنشاء حساب",
|
| 120 |
+
get_started: "ابدأ الآن", loading: "جارٍ التحميل…", save: "حفظ", saved: "تم الحفظ", cancel: "إلغاء", delete: "حذف",
|
| 121 |
+
edit: "تعديل", back: "رجوع", continue: "متابعة", retry: "حاول مرة أخرى", copy: "نسخ", copied: "تم النسخ", theme_dark: "الوضع الداكن",
|
| 122 |
+
theme_light: "الوضع الفاتح", language: "اللغة", min: "دقيقة", sec: "ثانية", of: "من", or: "أو", optional: "اختياري",
|
| 123 |
+
error_generic: "حدث خطأ. حاول مرة أخرى بعد قليل.",
|
| 124 |
+
|
| 125 |
+
hero_title: "تدرّب على المقابلة قبل المقابلة.",
|
| 126 |
+
hero_sub: "يسألك EvalBot أسئلة حقيقية في مجالك، ويستمع إلى طريقة إجابتك، ويوضح لك بالضبط ما تحتاج إلى تحسينه. درجات الأداء فيه مدرّبة على تقييم لجان من المقيّمين لـ 138 مقابلة حقيقية.",
|
| 127 |
+
cta_candidate: "ابدأ مقابلة تدريبية", cta_company: "وظّف باستخدام EvalBot",
|
| 128 |
+
demo_asking: "EvalBot يسأل", demo_question: "Tell me about a data pipeline you built, and what broke first.",
|
| 129 |
+
demo_listening: "يستمع", demo_you: "أنت", demo_answer: "We ingested sensor data through Kafka. The first thing that broke was…",
|
| 130 |
+
demo_content: "المحتوى", demo_delivery: "الأداء", demo_structure: "التنظيم",
|
| 131 |
+
for_candidates: "للباحثين عن عمل", for_companies: "لفرق التوظيف",
|
| 132 |
+
c1_t: "أي مجال وأي مستوى", c1_d: "البيانات، والـ Backend، والتصميم، والمبيعات، والموارد البشرية و25 مجالاً آخر، من التدريب إلى القيادة. الصق وصف وظيفة أو سيرتك الذاتية وستُبنى الأسئلة عليها.",
|
| 133 |
+
c2_t: "محادثة حقيقية", c2_d: "تُقرأ الأسئلة بصوت عالٍ وتجيب بصوتك. وإذا تركت إجابتك نقطة مفتوحة، يسألك EvalBot سؤال متابعة كما يفعل المحاوِر الحقيقي.",
|
| 134 |
+
c3_t: "ملاحظات قابلة للتطبيق", c3_d: "كل إجابة تحصل على درجة، وما كان جيداً، وما يحتاج إلى تحسين، ونسخة أقوى من إجابتك مبنية على معلوماتك أنت.",
|
| 135 |
+
c4_t: "شاهد تطوّرك", c4_d: "تُتابَع درجاتك وسرعة كلامك وكلمات الحشو عبر المقابلات، مع خطة تعلّم لمجالك.",
|
| 136 |
+
r1_t: "رابط واحد", r1_d: "أنشئ وظيفة بأسئلتك أو بأسئلة يقترحها الذكاء الاصطناعي، وشارك رابطاً واحداً مع المتقدمين.",
|
| 137 |
+
r2_t: "المقابلة نفسها للجميع", r2_d: "يجيب كل متقدم عن الأسئلة نفسها وبالوقت نفسه، في الوقت الذي يناسبه.",
|
| 138 |
+
r3_t: "قائمة مرتّبة بالأسباب", r3_d: "يُرتَّب المرشحون حسب الدرجة، ومع كل منهم تقييم مكتوب والتسجيلات ونص المقابلة.",
|
| 139 |
+
r4_t: "القرار لفريقك", r4_d: "رشّح أو ارفض، وقيّم، واترك ملاحظات. EvalBot يساعد في القرار، والقرار للبشر.",
|
| 140 |
+
science_title: "تقييم يشبه لجنة من المحاورين",
|
| 141 |
+
science_text: "درّبنا درجات الأداء في EvalBot على بيانات MIT Interview Dataset: 138 مقابلة تدريبية مسج��لة، قيّم كلاً منها تسعة أشخاص. وعند اختباره على أشخاص لم يرهم، يساوي EvalBot مقيّماً بشرياً واحداً أو يتفوق عليه في كلمات الحشو وتنظيم الإجابات والهدوء واستخدام التوقف، ويقترب منه في الحماس والتوصية بالتعيين.",
|
| 142 |
+
science_model: "EvalBot", science_human: "مقيّم بشري واحد",
|
| 143 |
+
science_note: "معامل الارتباط مع متوسط اللجنة، باختبار على أشخاص لم يرهم النموذج.",
|
| 144 |
+
how_title: "كيف تتم المقابلة التدريبية",
|
| 145 |
+
how_1: "اختر مجالك ومستواك ونوع المقابلة.", how_2: "أجب عن كل سؤال بصوتك، مع الكاميرا أو بدونها.",
|
| 146 |
+
how_3: "احصل على تقرير كامل بعد دقيقة، بالعربية أو الإنجليزية.",
|
| 147 |
+
tracks_title: "30 مجالاً مهنياً",
|
| 148 |
+
footer_text: "بدأ EvalBot مشروعَ تخرج في كلية الحاسبات والذكاء الاصطناعي، جامعة بنها.",
|
| 149 |
+
footer_privacy: "تسجيلاتك لا يراها غيرك، وفي مقابلات الوظائف تراها الشركة التي تقدمت إليها فقط.",
|
| 150 |
+
|
| 151 |
+
auth_signin_title: "أهلاً بعودتك", auth_signup_title: "أنشئ حسابك", email: "البريد الإلكتروني", password: "كلمة المرور",
|
| 152 |
+
full_name: "الاسم الكامل", forgot: "نسيت كلمة المرور؟", reset_sent: "أرسلنا رابط إعادة تعيين كلمة المرور إلى بريدك.",
|
| 153 |
+
google: "المتابعة بحساب Google", have_account: "لديك حساب بالفعل؟", no_account: "جديد على EvalBot؟",
|
| 154 |
+
check_email: "افتح بريدك واضغط رابط التأكيد، ثم سجّل الدخول.",
|
| 155 |
+
password_hint: "8 أحرف على الأقل.",
|
| 156 |
+
accounts_soon: "يتم تجهيز الحسابات حالياً. وفي الأثناء يمكنك تحليل مقابلة مسجّلة أو التدرّب على أسئلة منفردة.",
|
| 157 |
+
open_demo: "افتح أداة التحليل",
|
| 158 |
+
|
| 159 |
+
onboard_title: "كيف ستستخدم EvalBot؟", onboard_candidate: "أتدرّب على المقابلات",
|
| 160 |
+
onboard_candidate_d: "استعد للوظائف في مجالك وتابع تطوّرك.", onboard_recruiter: "أوظّف لشركتي",
|
| 161 |
+
onboard_recruiter_d: "أنشئ مقابلات للوظائف وراجع المرشحين.", company_name: "اسم الشركة", website: "الموقع الإلكتروني",
|
| 162 |
+
|
| 163 |
+
hello: "أهلاً {name}", dash_sub: "جاهز لمقابلتك القادمة؟", stat_interviews: "المقابلات", stat_average: "متوسط الدرجة",
|
| 164 |
+
stat_best: "أعلى درجة", stat_minutes: "دقائق الكلام", progress_title: "درجاتك عبر الوقت", skills_title: "أقوى مهاراتك وأضعفها",
|
| 165 |
+
recent: "آخر المقابلات", empty_dash: "لم تُجرِ أي مقابلة بعد. أول مقابلة تستغرق نحو عشر دقائق.",
|
| 166 |
+
st_in_progress: "لم تكتمل", st_processing: "جارٍ إعداد التقرير", st_completed: "مكتملة", st_failed: "فشلت",
|
| 167 |
+
resume: "متابعة", view_report: "عرض التقرير", answered_n: "أُجيب عن {a} من {b}", mock: "تدريب", job: "مقابلة وظيفة",
|
| 168 |
+
delete_confirm: "حذف هذه المقابلة وتسجيلاتها؟",
|
| 169 |
+
|
| 170 |
+
new_title: "مقابلة تدريبية جديدة", track: "المجال", search_tracks: "ابحث عن مجال", level: "المستوى",
|
| 171 |
+
lv_intern: "تدريب", lv_junior: "مبتدئ", lv_mid: "متوسط الخبرة", lv_senior: "خبير", lv_lead: "قائد فريق / مدير",
|
| 172 |
+
style: "نوع المقابلة", ty_mixed: "متنوعة", ty_mixed_d: "أسئلة تقنية وسلوكية وعن الدافع.",
|
| 173 |
+
ty_technical: "تقنية", ty_technical_d: "معرفة الدور والأدوات والمفاضلات.", ty_behavioral: "سلوكية",
|
| 174 |
+
ty_behavioral_d: "تجاربك السابقة والعمل الجماعي والخلافات.", ty_hr: "موارد بشرية / ملاءمة", ty_hr_d: "الدافع والأهداف والملاءمة لثقافة الشركة.",
|
| 175 |
+
ty_case: "حل مشكلات", ty_case_d: "مواقف تفكّر فيها بصوت عالٍ.",
|
| 176 |
+
count: "عدد الأسئلة", feedback_lang: "لغة التقييم", custom_role: "مسمى وظيفي محدد",
|
| 177 |
+
custom_role_ph: "مثال: Junior Data Engineer في شركة fintech", cv: "سيرتك الذاتية", cv_ph: "الصق نص سيرتك الذاتية لتشير الأسئلة إلى خبرتك.",
|
| 178 |
+
jd: "وصف الوظيفة", jd_ph: "الصق إعلان وظيفة لتحصل على أسئلة مخصصة له.", start: "ابدأ المقابلة",
|
| 179 |
+
preparing: "جارٍ إعداد أسئلتك…", g_tech: "التكنولوجيا", g_design: "التصميم", g_business: "الأعمال", g_other: "أخرى",
|
| 180 |
+
english: "English", arabic: "العربية",
|
| 181 |
+
|
| 182 |
+
q_of: "السؤال {n} من {total}", followup: "سؤال متابعة", listen_again: "استمع مرة أخرى", start_answer: "ابدأ الإجابة",
|
| 183 |
+
stop_answer: "انتهيت من الإجابة", recording: "يسجّل", time_left: "متبقٍ {t}", uploading: "جارٍ حفظ إجابتك…",
|
| 184 |
+
finish_now: "إنهاء والحصول على التقرير", camera: "الكاميرا", camera_on: "تشغيل الكاميرا", camera_off: "إيقاف الكاميرا",
|
| 185 |
+
camera_hint: "اختياري. لا يخرج من جهازك إلا أرقام مثل التواصل البصري والابتسام، وليس الفيديو أبداً.",
|
| 186 |
+
mic_error: "يحتاج EvalBot إلى الميكروفون. اسمح باستخدامه من المتصفح ثم حاول مرة أخرى.",
|
| 187 |
+
get_ready: "خذ نفساً. ابدأ الإجابة عندما تكون جاهزاً.", answers_saved: "تم حفظ {n} إجابات",
|
| 188 |
+
building_title: "جارٍ إعداد تقريرك", building_sub: "يستمع EvalBot إلى إجاباتك ويقيّم كل واحدة ويكتب ملاحظاتك. يستغرق هذا نحو دقيقة.",
|
| 189 |
+
interview_done: "كان هذا آخر سؤال.", answer_recorded: "تم حفظ الإجابة", too_short: "التسجيل قصير جداً. هل تريد إعادة تسجيل إجابتك؟",
|
| 190 |
+
record_again: "سجّل مرة أخرى", use_it: "احتفظ به",
|
| 191 |
+
|
| 192 |
+
overall: "الإجمالي", content: "المحتوى", delivery: "الأداء", calibrated_title: "كيف ستقيّمك على الأرجح لجنة من المحاورين",
|
| 193 |
+
calibrated_sub: "موقعك بين 138 مقابلة حقيقية قيّم كلاً منها تسعة أشخاص. ويوضح مقياس الموثوقية مدى اتفاق EvalBot مع اللجنة على أشخاص لم يرهم من قبل، ومقيّم بشري واحد يحقق نحو {h}.",
|
| 194 |
+
reliability: "الموثوقية", pct: "أفضل من {p}% من المقابلات", per_question: "تقييم كل سؤال", your_answer: "إجابتك",
|
| 195 |
+
went_well: "ما كان جيداً", improve: "ما يحتاج إلى تحسين", stronger: "إجابة أقوى", delivery_tip: "نصيحة للأداء",
|
| 196 |
+
summary: "الملخص", strengths: "نقاط القوة", weaknesses: "مجالات التطوير", learning_plan: "ماذا تذاكر بعد ذلك",
|
| 197 |
+
next_steps: "الخطوات التالية", role_fit: "الملاءمة للدور", download_pdf: "تحميل تقرير PDF", presence: "الحضور أمام الكاميرا",
|
| 198 |
+
eye_contact: "النظر إلى الكاميرا", smile: "الابتسام", face_visible: "ظهور الوجه", not_answered: "لم تتم الإجابة",
|
| 199 |
+
report_failed: "تعذّر إعداد هذا التقرير.", voice_title: "صوتك", speaking_rate: "سرعة الكلام",
|
| 200 |
+
wps: "كلمة في الثانية", fillers: "كلمات الحشو", fluency: "الطلاقة", confidence: "الثقة", anxiety: "التوتر",
|
| 201 |
+
sig_strong_yes: "تعيين بقوة", sig_yes: "تعيين", sig_maybe: "ربما", sig_no: "ليس الآن", hiring_signal: "مؤشر التوظيف",
|
| 202 |
+
practice_again: "تدرّب على هذا المجال مرة أخرى", evidence: "الدليل",
|
| 203 |
+
lv: { high: "مرتفع", moderate: "متوسط", low: "منخفض", fluent: "طليق", disfluent: "متردد" },
|
| 204 |
+
|
| 205 |
+
jobs_title: "الوظائف", new_job: "وظيفة جديدة", empty_jobs: "أنشئ أول وظيفة لتحصل على رابط مقابلة تشاركه مع المتقدمين.",
|
| 206 |
+
applicants: "المتقدمون", completed_n: "أكملوا", copy_link: "نسخ رابط المقابلة", link_copied: "تم نسخ الرابط",
|
| 207 |
+
jst_open: "مفتوحة", jst_draft: "مسودة", jst_closed: "مغلقة", job_title: "المسمى الوظيفي", job_desc: "الوصف",
|
| 208 |
+
answer_time: "الوقت المتاح لكل إجابة", questions: "الأسئلة", add_question: "إضافة سؤال", suggest: "اقترح أسئلة بالذكاء الاصطناعي",
|
| 209 |
+
suggesting: "جارٍ كتابة الأسئلة…", save_job: "حفظ الوظيفة", job_status: "الحالة", question_ph: "اكتب سؤالاً",
|
| 210 |
+
candidates_title: "المرشحون، الأعلى درجة أولاً", empty_candidates: "لم يُجرِ أحد المقابلة بعد. شارك رابط المقابلة مع المتقدمين.",
|
| 211 |
+
c_name: "المرشح", c_score: "الدرجة", c_signal: "مؤشر EvalBot", c_status: "قرارك", c_date: "التاريخ",
|
| 212 |
+
rv_new: "جديد", rv_shortlisted: "مرشّح", rv_rejected: "مرفوض", rv_hired: "تم تعيينه", all: "الكل",
|
| 213 |
+
decision: "القرار", rating: "تقييمك", notes: "ملاحظات لفريقك", save_review: "حفظ القرار",
|
| 214 |
+
fairness: "الدرجات تدعم حكمك ولا تحل محله. استمع إلى الإجابات قبل اتخاذ القرار.",
|
| 215 |
+
share_hint: "يستطيع أي شخص لديه هذا الرابط إجراء المقابلة بعد تسجيل الدخول.",
|
| 216 |
+
|
| 217 |
+
apply_title: "تدعوك {company} لإجراء مقابلة", apply_for: "لوظيفة {title}", apply_q: "{n} أسئلة",
|
| 218 |
+
apply_time: "حتى {m} دقيقة لكل إجابة", apply_how: "ستجيب عن كل سؤال بصوتك. اختر مكاناً هادئاً واسمح باستخدام الميكروفون.",
|
| 219 |
+
apply_start: "ابدأ المقابلة", apply_signin: "سجّل الدخول للبدء", apply_closed: "هذه الوظيفة لم تعد تستقبل مقابلات.",
|
| 220 |
+
apply_done: "أكملت هذه المقابلة. سيراجعها فريق التوظيف.",
|
| 221 |
+
|
| 222 |
+
settings_title: "الإعدادات", profile: "الملف الشخصي", headline: "نبذة قصيرة", headline_ph: "مثال: خريج هندسة بيانات",
|
| 223 |
+
target_track: "المجال المستهدف", new_password: "كلمة مرور جديدة", change_password: "تغيير كلمة المرور", password_changed: "تم تغيير كلمة المرور",
|
| 224 |
+
company: "الشركة",
|
| 225 |
+
};
|
| 226 |
+
|
| 227 |
+
export type Lang = "en" | "ar";
|
| 228 |
+
type I18n = { lang: Lang; dir: "ltr" | "rtl"; t: (k: keyof Dict, vars?: Record<string, string | number>) => string; d: Dict; setLang: (l: Lang) => void };
|
| 229 |
+
const Ctx = createContext<I18n | null>(null);
|
| 230 |
+
|
| 231 |
+
function initialLang(): Lang {
|
| 232 |
+
try {
|
| 233 |
+
const s = localStorage.getItem("evalbot_lang");
|
| 234 |
+
if (s === "en" || s === "ar") return s;
|
| 235 |
+
} catch {
|
| 236 |
+
/* ignore */
|
| 237 |
+
}
|
| 238 |
+
return navigator.language?.startsWith("ar") ? "ar" : "en";
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
export function I18nProvider({ children }: { children: ReactNode }) {
|
| 242 |
+
const [lang, setLangState] = useState<Lang>(initialLang);
|
| 243 |
+
const d = lang === "ar" ? ar : en;
|
| 244 |
+
useEffect(() => {
|
| 245 |
+
document.documentElement.lang = lang;
|
| 246 |
+
document.documentElement.dir = lang === "ar" ? "rtl" : "ltr";
|
| 247 |
+
}, [lang]);
|
| 248 |
+
const setLang = (l: Lang) => {
|
| 249 |
+
setLangState(l);
|
| 250 |
+
try {
|
| 251 |
+
localStorage.setItem("evalbot_lang", l);
|
| 252 |
+
} catch {
|
| 253 |
+
/* ignore */
|
| 254 |
+
}
|
| 255 |
+
};
|
| 256 |
+
const t = (k: keyof Dict, vars?: Record<string, string | number>) => {
|
| 257 |
+
let s = String(d[k] ?? en[k] ?? k);
|
| 258 |
+
if (vars) for (const [vk, vv] of Object.entries(vars)) s = s.replace(`{${vk}}`, String(vv));
|
| 259 |
+
return s;
|
| 260 |
+
};
|
| 261 |
+
return <Ctx.Provider value={{ lang, dir: lang === "ar" ? "rtl" : "ltr", t, d, setLang }}>{children}</Ctx.Provider>;
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
export function useI18n(): I18n {
|
| 265 |
+
const v = useContext(Ctx);
|
| 266 |
+
if (!v) throw new Error("useI18n outside provider");
|
| 267 |
+
return v;
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
export function trackName(tracks: { id: string; en: string; ar: string }[] | undefined, id: string | null | undefined, lang: Lang) {
|
| 271 |
+
const t = tracks?.find((x) => x.id === id);
|
| 272 |
+
return t ? (lang === "ar" ? t.ar : t.en) : id || "";
|
| 273 |
+
}
|
frontend/src/lib/media.ts
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useCallback, useEffect, useRef, useState } from "react";
|
| 2 |
+
|
| 3 |
+
/* ---------------------------------------------------------------------------------------
|
| 4 |
+
* Microphone recorder with live level meter (for the waveform)
|
| 5 |
+
* ------------------------------------------------------------------------------------- */
|
| 6 |
+
export type Recording = { blob: Blob; seconds: number; ext: string };
|
| 7 |
+
|
| 8 |
+
export function useRecorder(bars = 32) {
|
| 9 |
+
const [state, setState] = useState<"idle" | "recording">("idle");
|
| 10 |
+
const [levels, setLevels] = useState<number[]>(Array(bars).fill(0.08));
|
| 11 |
+
const [seconds, setSeconds] = useState(0);
|
| 12 |
+
const rec = useRef<MediaRecorder | null>(null);
|
| 13 |
+
const stream = useRef<MediaStream | null>(null);
|
| 14 |
+
const ctx = useRef<AudioContext | null>(null);
|
| 15 |
+
const raf = useRef<number>(0);
|
| 16 |
+
const started = useRef(0);
|
| 17 |
+
const resolver = useRef<((r: Recording) => void) | null>(null);
|
| 18 |
+
|
| 19 |
+
const cleanup = useCallback(() => {
|
| 20 |
+
cancelAnimationFrame(raf.current);
|
| 21 |
+
stream.current?.getTracks().forEach((t) => t.stop());
|
| 22 |
+
stream.current = null;
|
| 23 |
+
ctx.current?.close().catch(() => undefined);
|
| 24 |
+
ctx.current = null;
|
| 25 |
+
}, []);
|
| 26 |
+
|
| 27 |
+
useEffect(() => cleanup, [cleanup]);
|
| 28 |
+
|
| 29 |
+
const start = useCallback(async () => {
|
| 30 |
+
const s = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } });
|
| 31 |
+
stream.current = s;
|
| 32 |
+
const mime = ["audio/webm;codecs=opus", "audio/webm", "audio/mp4", "audio/ogg"].find((m) => window.MediaRecorder?.isTypeSupported(m)) || "";
|
| 33 |
+
const r = new MediaRecorder(s, mime ? { mimeType: mime } : undefined);
|
| 34 |
+
const chunks: Blob[] = [];
|
| 35 |
+
r.ondataavailable = (e) => e.data.size && chunks.push(e.data);
|
| 36 |
+
r.onstop = () => {
|
| 37 |
+
const type = r.mimeType || "audio/webm";
|
| 38 |
+
const ext = type.includes("mp4") ? ".m4a" : type.includes("ogg") ? ".ogg" : ".webm";
|
| 39 |
+
const secs = (Date.now() - started.current) / 1000;
|
| 40 |
+
cleanup();
|
| 41 |
+
setState("idle");
|
| 42 |
+
setLevels(Array(bars).fill(0.08));
|
| 43 |
+
resolver.current?.({ blob: new Blob(chunks, { type }), seconds: secs, ext });
|
| 44 |
+
};
|
| 45 |
+
// level meter
|
| 46 |
+
const ac = new AudioContext();
|
| 47 |
+
ctx.current = ac;
|
| 48 |
+
const an = ac.createAnalyser();
|
| 49 |
+
an.fftSize = 512;
|
| 50 |
+
ac.createMediaStreamSource(s).connect(an);
|
| 51 |
+
const buf = new Uint8Array(an.fftSize);
|
| 52 |
+
const hist: number[] = Array(bars).fill(0.08);
|
| 53 |
+
let last = 0;
|
| 54 |
+
const tick = (ts: number) => {
|
| 55 |
+
an.getByteTimeDomainData(buf);
|
| 56 |
+
let sum = 0;
|
| 57 |
+
for (const v of buf) sum += ((v - 128) / 128) ** 2;
|
| 58 |
+
const rms = Math.sqrt(sum / buf.length);
|
| 59 |
+
if (ts - last > 70) {
|
| 60 |
+
hist.shift();
|
| 61 |
+
hist.push(Math.min(1, 0.08 + rms * 4));
|
| 62 |
+
setLevels([...hist]);
|
| 63 |
+
setSeconds((Date.now() - started.current) / 1000);
|
| 64 |
+
last = ts;
|
| 65 |
+
}
|
| 66 |
+
raf.current = requestAnimationFrame(tick);
|
| 67 |
+
};
|
| 68 |
+
raf.current = requestAnimationFrame(tick);
|
| 69 |
+
started.current = Date.now();
|
| 70 |
+
setSeconds(0);
|
| 71 |
+
r.start(1000);
|
| 72 |
+
rec.current = r;
|
| 73 |
+
setState("recording");
|
| 74 |
+
}, [bars, cleanup]);
|
| 75 |
+
|
| 76 |
+
const stop = useCallback(
|
| 77 |
+
() =>
|
| 78 |
+
new Promise<Recording>((resolve) => {
|
| 79 |
+
resolver.current = resolve;
|
| 80 |
+
if (rec.current && rec.current.state !== "inactive") rec.current.stop();
|
| 81 |
+
}),
|
| 82 |
+
[],
|
| 83 |
+
);
|
| 84 |
+
|
| 85 |
+
return { state, levels, seconds, start, stop };
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/* ---------------------------------------------------------------------------------------
|
| 89 |
+
* Optional camera presence metrics, computed on-device with MediaPipe Face Landmarker.
|
| 90 |
+
* Only aggregate numbers leave the browser.
|
| 91 |
+
* ------------------------------------------------------------------------------------- */
|
| 92 |
+
type Sample = { face: boolean; looking: boolean; smile: number; move: number };
|
| 93 |
+
|
| 94 |
+
export function usePresence() {
|
| 95 |
+
const [enabled, setEnabled] = useState(false);
|
| 96 |
+
const [ready, setReady] = useState(false);
|
| 97 |
+
const [error, setError] = useState<string | null>(null);
|
| 98 |
+
const video = useRef<HTMLVideoElement | null>(null);
|
| 99 |
+
const stream = useRef<MediaStream | null>(null);
|
| 100 |
+
const landmarker = useRef<any>(null);
|
| 101 |
+
const samples = useRef<Sample[]>([]);
|
| 102 |
+
const collecting = useRef(false);
|
| 103 |
+
const timer = useRef<number>(0);
|
| 104 |
+
const prevNose = useRef<[number, number] | null>(null);
|
| 105 |
+
|
| 106 |
+
const stopCamera = useCallback(() => {
|
| 107 |
+
window.clearInterval(timer.current);
|
| 108 |
+
stream.current?.getTracks().forEach((t) => t.stop());
|
| 109 |
+
stream.current = null;
|
| 110 |
+
setReady(false);
|
| 111 |
+
}, []);
|
| 112 |
+
|
| 113 |
+
useEffect(() => stopCamera, [stopCamera]);
|
| 114 |
+
|
| 115 |
+
const enable = useCallback(async (el: HTMLVideoElement | null) => {
|
| 116 |
+
setError(null);
|
| 117 |
+
try {
|
| 118 |
+
const s = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480, facingMode: "user" } });
|
| 119 |
+
stream.current = s;
|
| 120 |
+
video.current = el;
|
| 121 |
+
if (el) {
|
| 122 |
+
el.srcObject = s;
|
| 123 |
+
await el.play().catch(() => undefined);
|
| 124 |
+
}
|
| 125 |
+
setEnabled(true);
|
| 126 |
+
if (!landmarker.current) {
|
| 127 |
+
const vision = await import("@mediapipe/tasks-vision");
|
| 128 |
+
const fileset = await vision.FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.21/wasm");
|
| 129 |
+
landmarker.current = await vision.FaceLandmarker.createFromOptions(fileset, {
|
| 130 |
+
baseOptions: {
|
| 131 |
+
modelAssetPath: "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",
|
| 132 |
+
delegate: "GPU",
|
| 133 |
+
},
|
| 134 |
+
runningMode: "VIDEO",
|
| 135 |
+
numFaces: 1,
|
| 136 |
+
outputFaceBlendshapes: true,
|
| 137 |
+
});
|
| 138 |
+
}
|
| 139 |
+
timer.current = window.setInterval(() => {
|
| 140 |
+
const v = video.current;
|
| 141 |
+
if (!collecting.current || !v || v.readyState < 2 || !landmarker.current) return;
|
| 142 |
+
const res = landmarker.current.detectForVideo(v, performance.now());
|
| 143 |
+
const lm = res.faceLandmarks?.[0];
|
| 144 |
+
if (!lm) {
|
| 145 |
+
samples.current.push({ face: false, looking: false, smile: 0, move: 0 });
|
| 146 |
+
return;
|
| 147 |
+
}
|
| 148 |
+
const bs: Record<string, number> = {};
|
| 149 |
+
for (const c of res.faceBlendshapes?.[0]?.categories ?? []) bs[c.categoryName] = c.score;
|
| 150 |
+
// head yaw proxy: nose tip relative to the outer eye corners
|
| 151 |
+
const nose = lm[1], l = lm[33], r = lm[263];
|
| 152 |
+
const mid = (l.x + r.x) / 2;
|
| 153 |
+
const yaw = Math.abs(nose.x - mid) / Math.max(1e-3, Math.abs(r.x - l.x));
|
| 154 |
+
const gazeAway = Math.max(bs.eyeLookOutLeft ?? 0, bs.eyeLookOutRight ?? 0, bs.eyeLookInLeft ?? 0, bs.eyeLookInRight ?? 0,
|
| 155 |
+
bs.eyeLookUpLeft ?? 0, bs.eyeLookDownLeft ?? 0);
|
| 156 |
+
const looking = yaw < 0.12 && gazeAway < 0.55;
|
| 157 |
+
const smile = ((bs.mouthSmileLeft ?? 0) + (bs.mouthSmileRight ?? 0)) / 2;
|
| 158 |
+
const p: [number, number] = [nose.x, nose.y];
|
| 159 |
+
const move = prevNose.current ? Math.hypot(p[0] - prevNose.current[0], p[1] - prevNose.current[1]) : 0;
|
| 160 |
+
prevNose.current = p;
|
| 161 |
+
samples.current.push({ face: true, looking, smile, move });
|
| 162 |
+
}, 250);
|
| 163 |
+
setReady(true);
|
| 164 |
+
} catch {
|
| 165 |
+
setError("camera");
|
| 166 |
+
stopCamera();
|
| 167 |
+
setEnabled(false);
|
| 168 |
+
}
|
| 169 |
+
}, [stopCamera]);
|
| 170 |
+
|
| 171 |
+
const disable = useCallback(() => {
|
| 172 |
+
stopCamera();
|
| 173 |
+
setEnabled(false);
|
| 174 |
+
}, [stopCamera]);
|
| 175 |
+
|
| 176 |
+
const begin = useCallback(() => {
|
| 177 |
+
samples.current = [];
|
| 178 |
+
prevNose.current = null;
|
| 179 |
+
collecting.current = true;
|
| 180 |
+
}, []);
|
| 181 |
+
|
| 182 |
+
const end = useCallback((): Record<string, number> | null => {
|
| 183 |
+
collecting.current = false;
|
| 184 |
+
const s = samples.current;
|
| 185 |
+
if (!enabled || s.length < 4) return null;
|
| 186 |
+
const faces = s.filter((x) => x.face);
|
| 187 |
+
const n = Math.max(1, faces.length);
|
| 188 |
+
return {
|
| 189 |
+
face_visible: faces.length / s.length,
|
| 190 |
+
eye_contact: faces.filter((x) => x.looking).length / n,
|
| 191 |
+
smile: faces.reduce((a, x) => a + x.smile, 0) / n,
|
| 192 |
+
head_movement: faces.reduce((a, x) => a + x.move, 0) / n,
|
| 193 |
+
samples: s.length,
|
| 194 |
+
};
|
| 195 |
+
}, [enabled]);
|
| 196 |
+
|
| 197 |
+
return { enabled, ready, error, enable, disable, begin, end };
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
/* ---------------------------------------------------------------------------------------
|
| 201 |
+
* Interviewer voice: the browser's speech synthesis
|
| 202 |
+
* ------------------------------------------------------------------------------------- */
|
| 203 |
+
export function speak(text: string, onEnd?: () => void) {
|
| 204 |
+
if (!("speechSynthesis" in window)) {
|
| 205 |
+
onEnd?.();
|
| 206 |
+
return;
|
| 207 |
+
}
|
| 208 |
+
speechSynthesis.cancel();
|
| 209 |
+
const u = new SpeechSynthesisUtterance(text);
|
| 210 |
+
u.lang = "en-US";
|
| 211 |
+
u.rate = 0.97;
|
| 212 |
+
const voices = speechSynthesis.getVoices();
|
| 213 |
+
const v = voices.find((x) => /en-(US|GB)/.test(x.lang) && /Google|Natural|Samantha|Daniel/.test(x.name)) || voices.find((x) => x.lang?.startsWith("en"));
|
| 214 |
+
if (v) u.voice = v;
|
| 215 |
+
u.onend = () => onEnd?.();
|
| 216 |
+
u.onerror = () => onEnd?.();
|
| 217 |
+
speechSynthesis.speak(u);
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
export function stopSpeaking() {
|
| 221 |
+
if ("speechSynthesis" in window) speechSynthesis.cancel();
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
export function fmtClock(s: number) {
|
| 225 |
+
const v = Math.max(0, Math.round(s));
|
| 226 |
+
return `${Math.floor(v / 60)}:${String(v % 60).padStart(2, "0")}`;
|
| 227 |
+
}
|
frontend/src/main.tsx
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { StrictMode, type ReactNode } from "react";
|
| 2 |
+
import { createRoot } from "react-dom/client";
|
| 3 |
+
import { BrowserRouter, Navigate, Route, Routes, useLocation } from "react-router-dom";
|
| 4 |
+
import { AppShell } from "./components/Shell";
|
| 5 |
+
import { Spinner } from "./components/ui";
|
| 6 |
+
import "./index.css";
|
| 7 |
+
import { AuthProvider, useAuth } from "./lib/auth";
|
| 8 |
+
import { I18nProvider } from "./lib/i18n";
|
| 9 |
+
import Apply from "./pages/Apply";
|
| 10 |
+
import Auth from "./pages/Auth";
|
| 11 |
+
import Dashboard from "./pages/Dashboard";
|
| 12 |
+
import History from "./pages/History";
|
| 13 |
+
import InterviewRoom from "./pages/InterviewRoom";
|
| 14 |
+
import JobEditor from "./pages/JobEditor";
|
| 15 |
+
import JobDetail from "./pages/JobDetail";
|
| 16 |
+
import Jobs from "./pages/Jobs";
|
| 17 |
+
import Landing from "./pages/Landing";
|
| 18 |
+
import NewInterview from "./pages/NewInterview";
|
| 19 |
+
import Onboarding from "./pages/Onboarding";
|
| 20 |
+
import ReportPage from "./pages/Report";
|
| 21 |
+
import SettingsPage from "./pages/Settings";
|
| 22 |
+
|
| 23 |
+
// apply the saved theme before first paint
|
| 24 |
+
try {
|
| 25 |
+
const s = localStorage.getItem("evalbot_theme");
|
| 26 |
+
if (s === "dark" || (!s && window.matchMedia("(prefers-color-scheme: dark)").matches)) document.documentElement.classList.add("dark");
|
| 27 |
+
} catch {
|
| 28 |
+
/* ignore */
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
function Private({ children, bare }: { children: ReactNode; bare?: boolean }) {
|
| 32 |
+
const { ready, profile } = useAuth();
|
| 33 |
+
const loc = useLocation();
|
| 34 |
+
if (!ready) return <Spinner />;
|
| 35 |
+
if (!profile) return <Navigate to={`/login?next=${encodeURIComponent(loc.pathname + loc.search)}`} replace />;
|
| 36 |
+
return bare ? <>{children}</> : <AppShell>{children}</AppShell>;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
createRoot(document.getElementById("root")!).render(
|
| 40 |
+
<StrictMode>
|
| 41 |
+
<I18nProvider>
|
| 42 |
+
<AuthProvider>
|
| 43 |
+
<BrowserRouter>
|
| 44 |
+
<Routes>
|
| 45 |
+
<Route path="/" element={<Landing />} />
|
| 46 |
+
<Route path="/login" element={<Auth mode="signin" />} />
|
| 47 |
+
<Route path="/signup" element={<Auth mode="signup" />} />
|
| 48 |
+
<Route path="/apply/:token" element={<Apply />} />
|
| 49 |
+
<Route path="/app/welcome" element={<Private bare><Onboarding /></Private>} />
|
| 50 |
+
<Route path="/app" element={<Private><Dashboard /></Private>} />
|
| 51 |
+
<Route path="/app/new" element={<Private><NewInterview /></Private>} />
|
| 52 |
+
<Route path="/app/history" element={<Private><History /></Private>} />
|
| 53 |
+
<Route path="/app/interview/:id" element={<Private bare><InterviewRoom /></Private>} />
|
| 54 |
+
<Route path="/app/report/:id" element={<Private><ReportPage /></Private>} />
|
| 55 |
+
<Route path="/app/settings" element={<Private><SettingsPage /></Private>} />
|
| 56 |
+
<Route path="/app/jobs" element={<Private><Jobs /></Private>} />
|
| 57 |
+
<Route path="/app/jobs/new" element={<Private><JobEditor /></Private>} />
|
| 58 |
+
<Route path="/app/jobs/:id/edit" element={<Private><JobEditor /></Private>} />
|
| 59 |
+
<Route path="/app/jobs/:id" element={<Private><JobDetail /></Private>} />
|
| 60 |
+
<Route path="*" element={<Navigate to="/" replace />} />
|
| 61 |
+
</Routes>
|
| 62 |
+
</BrowserRouter>
|
| 63 |
+
</AuthProvider>
|
| 64 |
+
</I18nProvider>
|
| 65 |
+
</StrictMode>,
|
| 66 |
+
);
|
frontend/src/pages/Apply.tsx
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Clock, ListChecks, Mic } from "lucide-react";
|
| 2 |
+
import { useEffect, useState } from "react";
|
| 3 |
+
import { Link, useNavigate, useParams } from "react-router-dom";
|
| 4 |
+
import { PublicHeader } from "../components/Shell";
|
| 5 |
+
import { Button, ErrorNote, Spinner, Waveform } from "../components/ui";
|
| 6 |
+
import { api, type Session } from "../lib/api";
|
| 7 |
+
import { useAuth } from "../lib/auth";
|
| 8 |
+
import { useI18n } from "../lib/i18n";
|
| 9 |
+
|
| 10 |
+
type PublicJob = { id: string; title: string; company: string; description: string | null; answer_seconds: number; status: string; question_count: number };
|
| 11 |
+
|
| 12 |
+
export default function Apply() {
|
| 13 |
+
const { token } = useParams();
|
| 14 |
+
const { t, lang } = useI18n();
|
| 15 |
+
const { profile, ready } = useAuth();
|
| 16 |
+
const nav = useNavigate();
|
| 17 |
+
const [job, setJob] = useState<PublicJob | null>(null);
|
| 18 |
+
const [error, setError] = useState<string | null>(null);
|
| 19 |
+
const [busy, setBusy] = useState(false);
|
| 20 |
+
const [done, setDone] = useState(false);
|
| 21 |
+
|
| 22 |
+
useEffect(() => {
|
| 23 |
+
api.get<PublicJob>(`/public/jobs/${token}`).then(setJob).catch((e) => setError(e.message));
|
| 24 |
+
}, [token]);
|
| 25 |
+
|
| 26 |
+
const start = async () => {
|
| 27 |
+
setBusy(true);
|
| 28 |
+
try {
|
| 29 |
+
const s = await api.post<Session>(`/jobs/apply/${token}`, { language: lang });
|
| 30 |
+
if (s.status === "in_progress") nav(`/app/interview/${s.id}`);
|
| 31 |
+
else setDone(true);
|
| 32 |
+
} catch (e: any) {
|
| 33 |
+
setError(e.message);
|
| 34 |
+
} finally {
|
| 35 |
+
setBusy(false);
|
| 36 |
+
}
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
return (
|
| 40 |
+
<div className="min-h-screen">
|
| 41 |
+
<PublicHeader />
|
| 42 |
+
<main className="mx-auto max-w-2xl px-4 pb-16 pt-8">
|
| 43 |
+
{error ? <ErrorNote>{error}</ErrorNote> : !job || !ready ? <Spinner /> : (
|
| 44 |
+
<div className="rounded-3xl border border-line bg-surface p-6 sm:p-10">
|
| 45 |
+
<div className="h-10 w-40"><Waveform bars={20} color="var(--color-nile)" /></div>
|
| 46 |
+
<h1 className="mt-6 text-3xl font-semibold text-ink">{t("apply_title", { company: job.company })}</h1>
|
| 47 |
+
<p className="mt-1 text-xl text-muted">{t("apply_for", { title: job.title })}</p>
|
| 48 |
+
{job.description && <p className="mt-6 whitespace-pre-line text-[15px] text-ink">{job.description}</p>}
|
| 49 |
+
<ul className="mt-6 space-y-2 text-[15px] text-ink">
|
| 50 |
+
<li className="flex items-center gap-3"><ListChecks size={18} className="text-nile" /> {t("apply_q", { n: job.question_count })}</li>
|
| 51 |
+
<li className="flex items-center gap-3"><Clock size={18} className="text-nile" /> {t("apply_time", { m: Math.round(job.answer_seconds / 60) })}</li>
|
| 52 |
+
<li className="flex items-start gap-3"><Mic size={18} className="mt-0.5 flex-none text-nile" /> {t("apply_how")}</li>
|
| 53 |
+
</ul>
|
| 54 |
+
<div className="mt-8">
|
| 55 |
+
{job.status !== "open" ? <p className="text-muted">{t("apply_closed")}</p>
|
| 56 |
+
: done ? <p className="rounded-xl bg-nile-soft px-4 py-3 text-nile-deep">{t("apply_done")}</p>
|
| 57 |
+
: profile ? <Button size="lg" onClick={start} busy={busy}>{t("apply_start")}</Button>
|
| 58 |
+
: <Link to={`/signup?next=${encodeURIComponent(`/apply/${token}`)}`} className="inline-block rounded-xl bg-nile px-6 py-3.5 font-medium text-white dark:text-paper">{t("apply_signin")}</Link>}
|
| 59 |
+
</div>
|
| 60 |
+
</div>
|
| 61 |
+
)}
|
| 62 |
+
</main>
|
| 63 |
+
</div>
|
| 64 |
+
);
|
| 65 |
+
}
|
frontend/src/pages/Auth.tsx
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useState, type FormEvent } from "react";
|
| 2 |
+
import { Link, useNavigate, useSearchParams } from "react-router-dom";
|
| 3 |
+
import { PublicHeader } from "../components/Shell";
|
| 4 |
+
import { Button, ErrorNote, Field, Input } from "../components/ui";
|
| 5 |
+
import { useAuth } from "../lib/auth";
|
| 6 |
+
import { useI18n } from "../lib/i18n";
|
| 7 |
+
|
| 8 |
+
export default function Auth({ mode }: { mode: "signin" | "signup" }) {
|
| 9 |
+
const { t } = useI18n();
|
| 10 |
+
const { signIn, signUp, signInWithGoogle, resetPassword, config } = useAuth();
|
| 11 |
+
const [params] = useSearchParams();
|
| 12 |
+
const nav = useNavigate();
|
| 13 |
+
const [email, setEmail] = useState("");
|
| 14 |
+
const [password, setPassword] = useState("");
|
| 15 |
+
const [name, setName] = useState("");
|
| 16 |
+
const [busy, setBusy] = useState(false);
|
| 17 |
+
const [error, setError] = useState<string | null>(null);
|
| 18 |
+
const [notice, setNotice] = useState<string | null>(null);
|
| 19 |
+
const next = params.get("next");
|
| 20 |
+
const asCompany = params.get("as") === "company";
|
| 21 |
+
|
| 22 |
+
const submit = async (e: FormEvent) => {
|
| 23 |
+
e.preventDefault();
|
| 24 |
+
setBusy(true);
|
| 25 |
+
setError(null);
|
| 26 |
+
try {
|
| 27 |
+
if (mode === "signin") {
|
| 28 |
+
await signIn(email, password);
|
| 29 |
+
nav(next || "/app");
|
| 30 |
+
} else {
|
| 31 |
+
const r = await signUp(email, password, name);
|
| 32 |
+
if (r.needsConfirmation) setNotice(t("check_email"));
|
| 33 |
+
else nav(next || `/app/welcome${asCompany ? "?as=company" : ""}`);
|
| 34 |
+
}
|
| 35 |
+
} catch (err: any) {
|
| 36 |
+
setError(err?.message || t("error_generic"));
|
| 37 |
+
} finally {
|
| 38 |
+
setBusy(false);
|
| 39 |
+
}
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
const forgot = async () => {
|
| 43 |
+
if (!email) {
|
| 44 |
+
setError(t("email"));
|
| 45 |
+
return;
|
| 46 |
+
}
|
| 47 |
+
try {
|
| 48 |
+
await resetPassword(email);
|
| 49 |
+
setNotice(t("reset_sent"));
|
| 50 |
+
} catch (err: any) {
|
| 51 |
+
setError(err?.message || t("error_generic"));
|
| 52 |
+
}
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
return (
|
| 56 |
+
<div className="min-h-screen">
|
| 57 |
+
<PublicHeader />
|
| 58 |
+
<main className="mx-auto max-w-md px-4 pb-16 pt-8">
|
| 59 |
+
<h1 className="text-3xl font-semibold text-ink">{mode === "signin" ? t("auth_signin_title") : t("auth_signup_title")}</h1>
|
| 60 |
+
{config && !config.enabled ? (
|
| 61 |
+
<div className="mt-6 space-y-4">
|
| 62 |
+
<p className="rounded-xl bg-amber-soft px-4 py-3 text-ink">{t("accounts_soon")}</p>
|
| 63 |
+
<a href="/demo" className="inline-block rounded-xl bg-nile px-5 py-3 font-medium text-white dark:text-paper">{t("open_demo")}</a>
|
| 64 |
+
</div>
|
| 65 |
+
) : notice ? (
|
| 66 |
+
<p className="mt-6 rounded-xl bg-nile-soft px-4 py-3 text-nile-deep">{notice}</p>
|
| 67 |
+
) : (
|
| 68 |
+
<form onSubmit={submit} className="mt-8 space-y-4">
|
| 69 |
+
{config?.supabase_url && (
|
| 70 |
+
<>
|
| 71 |
+
<Button type="button" variant="outline" className="w-full" onClick={() => signInWithGoogle().catch((e) => setError(e.message))}>
|
| 72 |
+
<svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true"><path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z"/><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/><path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-7.9l-6.5 5C9.5 39.6 16.2 44 24 44z"/><path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.4-.4-3.5z"/></svg>
|
| 73 |
+
{t("google")}
|
| 74 |
+
</Button>
|
| 75 |
+
<div className="flex items-center gap-3 text-sm text-muted"><span className="h-px flex-1 bg-line" />{t("or")}<span className="h-px flex-1 bg-line" /></div>
|
| 76 |
+
</>
|
| 77 |
+
)}
|
| 78 |
+
{mode === "signup" && (
|
| 79 |
+
<Field label={t("full_name")}><Input value={name} onChange={(e) => setName(e.target.value)} required autoComplete="name" /></Field>
|
| 80 |
+
)}
|
| 81 |
+
<Field label={t("email")}><Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required autoComplete="email" /></Field>
|
| 82 |
+
<Field label={t("password")} hint={mode === "signup" ? t("password_hint") : undefined}>
|
| 83 |
+
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={mode === "signup" ? 8 : 1}
|
| 84 |
+
autoComplete={mode === "signup" ? "new-password" : "current-password"} />
|
| 85 |
+
</Field>
|
| 86 |
+
{error && <ErrorNote>{error}</ErrorNote>}
|
| 87 |
+
<Button type="submit" busy={busy} className="w-full" size="lg">{mode === "signin" ? t("sign_in") : t("sign_up")}</Button>
|
| 88 |
+
{mode === "signin" && config?.supabase_url && (
|
| 89 |
+
<button type="button" onClick={forgot} className="text-sm text-nile hover:underline">{t("forgot")}</button>
|
| 90 |
+
)}
|
| 91 |
+
</form>
|
| 92 |
+
)}
|
| 93 |
+
<p className="mt-8 text-sm text-muted">
|
| 94 |
+
{mode === "signin" ? t("no_account") : t("have_account")}{" "}
|
| 95 |
+
<Link to={`${mode === "signin" ? "/signup" : "/login"}${next ? `?next=${encodeURIComponent(next)}` : ""}`} className="font-medium text-nile hover:underline">
|
| 96 |
+
{mode === "signin" ? t("sign_up") : t("sign_in")}
|
| 97 |
+
</Link>
|
| 98 |
+
</p>
|
| 99 |
+
</main>
|
| 100 |
+
</div>
|
| 101 |
+
);
|
| 102 |
+
}
|
frontend/src/pages/Dashboard.tsx
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useEffect, useState } from "react";
|
| 2 |
+
import { Link, Navigate } from "react-router-dom";
|
| 3 |
+
import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
| 4 |
+
import { Meter, Panel, Spinner, Waveform } from "../components/ui";
|
| 5 |
+
import { api, type SessionRow } from "../lib/api";
|
| 6 |
+
import { useAuth } from "../lib/auth";
|
| 7 |
+
import { useI18n } from "../lib/i18n";
|
| 8 |
+
import { SessionList } from "./History";
|
| 9 |
+
|
| 10 |
+
type Stats = {
|
| 11 |
+
interviews: number; answers: number; speaking_minutes: number; average: number | null; best: number | null;
|
| 12 |
+
trend: { date: string; score: number; track: string }[]; skills: { skill: string; avg: number; n: number }[];
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
export default function Dashboard() {
|
| 16 |
+
const { t } = useI18n();
|
| 17 |
+
const { profile } = useAuth();
|
| 18 |
+
const [stats, setStats] = useState<Stats | null>(null);
|
| 19 |
+
const [rows, setRows] = useState<SessionRow[] | null>(null);
|
| 20 |
+
useEffect(() => {
|
| 21 |
+
api.get<Stats>("/stats").then(setStats).catch(() => undefined);
|
| 22 |
+
api.get<SessionRow[]>("/sessions").then(setRows).catch(() => setRows([]));
|
| 23 |
+
}, []);
|
| 24 |
+
if (profile?.role === "recruiter" && !profile.company_id) return <Navigate to="/app/welcome?as=company" replace />;
|
| 25 |
+
if (!stats || !rows) return <Spinner />;
|
| 26 |
+
const first = (profile?.full_name || "").split(" ")[0] || "";
|
| 27 |
+
const tile = (label: string, value: string | number | null) => (
|
| 28 |
+
<div className="rounded-2xl border border-line bg-surface p-4">
|
| 29 |
+
<p className="text-sm text-muted">{label}</p>
|
| 30 |
+
<p className="mt-1 font-display text-3xl font-semibold tabular text-ink">{value ?? "–"}</p>
|
| 31 |
+
</div>
|
| 32 |
+
);
|
| 33 |
+
const skills = [...stats.skills].sort((a, b) => b.avg - a.avg);
|
| 34 |
+
|
| 35 |
+
return (
|
| 36 |
+
<div className="space-y-6">
|
| 37 |
+
<div className="flex flex-col gap-4 rounded-3xl bg-nile p-6 text-white sm:flex-row sm:items-center sm:justify-between sm:p-8 dark:text-paper">
|
| 38 |
+
<div>
|
| 39 |
+
<h1 className="text-3xl font-semibold">{first ? t("hello", { name: first }) : t("dash_sub")}</h1>
|
| 40 |
+
{first && <p className="mt-1 opacity-85">{t("dash_sub")}</p>}
|
| 41 |
+
</div>
|
| 42 |
+
<div className="flex items-center gap-5">
|
| 43 |
+
<div className="hidden h-12 w-36 md:block"><Waveform bars={22} color="var(--color-amber)" /></div>
|
| 44 |
+
<Link to="/app/new" className="rounded-xl bg-white px-5 py-3 font-medium text-nile-deep hover:bg-amber-soft dark:bg-paper">{t("nav_new")}</Link>
|
| 45 |
+
</div>
|
| 46 |
+
</div>
|
| 47 |
+
|
| 48 |
+
{stats.interviews === 0 && rows.length === 0 ? (
|
| 49 |
+
<Panel><p className="text-muted">{t("empty_dash")}</p></Panel>
|
| 50 |
+
) : (
|
| 51 |
+
<>
|
| 52 |
+
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
| 53 |
+
{tile(t("stat_interviews"), stats.interviews)}
|
| 54 |
+
{tile(t("stat_average"), stats.average)}
|
| 55 |
+
{tile(t("stat_best"), stats.best)}
|
| 56 |
+
{tile(t("stat_minutes"), stats.speaking_minutes)}
|
| 57 |
+
</div>
|
| 58 |
+
<div className="grid gap-6 lg:grid-cols-[1.4fr_1fr]">
|
| 59 |
+
<Panel title={t("progress_title")}>
|
| 60 |
+
{stats.trend.length > 1 ? (
|
| 61 |
+
<div className="h-56" dir="ltr">
|
| 62 |
+
<ResponsiveContainer width="100%" height="100%">
|
| 63 |
+
<LineChart data={stats.trend} margin={{ left: -20, right: 8, top: 8 }}>
|
| 64 |
+
<CartesianGrid stroke="var(--color-line)" vertical={false} />
|
| 65 |
+
<XAxis dataKey="date" stroke="var(--color-muted)" fontSize={12} />
|
| 66 |
+
<YAxis domain={[0, 100]} stroke="var(--color-muted)" fontSize={12} />
|
| 67 |
+
<Tooltip contentStyle={{ background: "var(--color-surface)", border: "1px solid var(--color-line)", borderRadius: 12 }} />
|
| 68 |
+
<Line type="monotone" dataKey="score" stroke="var(--color-nile)" strokeWidth={2.5} dot={{ r: 4, fill: "var(--color-nile)" }} />
|
| 69 |
+
</LineChart>
|
| 70 |
+
</ResponsiveContainer>
|
| 71 |
+
</div>
|
| 72 |
+
) : (
|
| 73 |
+
<p className="text-sm text-muted">{stats.trend.length === 1 ? `${stats.trend[0].score}` : "–"}</p>
|
| 74 |
+
)}
|
| 75 |
+
</Panel>
|
| 76 |
+
<Panel title={t("skills_title")}>
|
| 77 |
+
{skills.length ? (
|
| 78 |
+
<ul className="space-y-3">
|
| 79 |
+
{skills.map((s) => (
|
| 80 |
+
<li key={s.skill}>
|
| 81 |
+
<div className="mb-1 flex justify-between gap-2 text-sm"><span className="ltr truncate text-ink">{s.skill}</span><span className="tabular text-muted">{s.avg}/10</span></div>
|
| 82 |
+
<Meter value={s.avg} max={10} />
|
| 83 |
+
</li>
|
| 84 |
+
))}
|
| 85 |
+
</ul>
|
| 86 |
+
) : <p className="text-sm text-muted">–</p>}
|
| 87 |
+
</Panel>
|
| 88 |
+
</div>
|
| 89 |
+
<div>
|
| 90 |
+
<h2 className="mb-3 text-lg font-semibold text-ink">{t("recent")}</h2>
|
| 91 |
+
<SessionList rows={rows.slice(0, 6)} />
|
| 92 |
+
</div>
|
| 93 |
+
</>
|
| 94 |
+
)}
|
| 95 |
+
</div>
|
| 96 |
+
);
|
| 97 |
+
}
|
frontend/src/pages/History.tsx
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Trash2 } from "lucide-react";
|
| 2 |
+
import { useEffect, useState } from "react";
|
| 3 |
+
import { Link } from "react-router-dom";
|
| 4 |
+
import { Badge, Spinner, StatusBadge, fmtDate, scoreColor, useCatalog } from "../components/ui";
|
| 5 |
+
import { api, type SessionRow } from "../lib/api";
|
| 6 |
+
import { trackName, useI18n } from "../lib/i18n";
|
| 7 |
+
|
| 8 |
+
export function SessionList({ rows, onDelete }: { rows: SessionRow[]; onDelete?: (id: string) => void }) {
|
| 9 |
+
const { t, lang } = useI18n();
|
| 10 |
+
const catalog = useCatalog();
|
| 11 |
+
return (
|
| 12 |
+
<ul className="divide-y divide-line overflow-hidden rounded-2xl border border-line bg-surface">
|
| 13 |
+
{rows.map((s) => {
|
| 14 |
+
const href = s.status === "in_progress" ? `/app/interview/${s.id}` : `/app/report/${s.id}`;
|
| 15 |
+
return (
|
| 16 |
+
<li key={s.id} className="flex items-center gap-4 px-4 py-3.5 hover:bg-sunken/60 sm:px-5">
|
| 17 |
+
<div className="flex h-12 w-12 flex-none items-center justify-center rounded-xl bg-sunken font-display text-lg font-semibold tabular"
|
| 18 |
+
style={{ color: scoreColor(s.overall_score) }}>
|
| 19 |
+
{s.overall_score != null ? Math.round(s.overall_score) : "–"}
|
| 20 |
+
</div>
|
| 21 |
+
<Link to={href} className="min-w-0 flex-1">
|
| 22 |
+
<p className="truncate font-medium text-ink">{s.job_title || s.role || trackName(catalog?.tracks, s.track, lang)}</p>
|
| 23 |
+
<p className="mt-0.5 flex flex-wrap items-center gap-2 text-sm text-muted">
|
| 24 |
+
<span>{fmtDate(s.created_at, lang)}</span>
|
| 25 |
+
<Badge>{s.mode === "job" ? t("job") : t("mock")}</Badge>
|
| 26 |
+
<StatusBadge status={s.status} />
|
| 27 |
+
{s.status === "in_progress" && <span>{t("answered_n", { a: s.answered, b: s.planned })}</span>}
|
| 28 |
+
</p>
|
| 29 |
+
</Link>
|
| 30 |
+
<Link to={href} className="hidden rounded-lg px-3 py-1.5 text-sm font-medium text-nile hover:bg-nile-soft sm:inline-block">
|
| 31 |
+
{s.status === "in_progress" ? t("resume") : t("view_report")}
|
| 32 |
+
</Link>
|
| 33 |
+
{onDelete && s.mode !== "job" && (
|
| 34 |
+
<button onClick={() => onDelete(s.id)} className="rounded-lg p-2 text-muted hover:bg-danger-soft hover:text-danger" aria-label={t("delete")}>
|
| 35 |
+
<Trash2 size={16} />
|
| 36 |
+
</button>
|
| 37 |
+
)}
|
| 38 |
+
</li>
|
| 39 |
+
);
|
| 40 |
+
})}
|
| 41 |
+
</ul>
|
| 42 |
+
);
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
export default function History() {
|
| 46 |
+
const { t } = useI18n();
|
| 47 |
+
const [rows, setRows] = useState<SessionRow[] | null>(null);
|
| 48 |
+
const load = () => api.get<SessionRow[]>("/sessions").then(setRows);
|
| 49 |
+
useEffect(() => {
|
| 50 |
+
load();
|
| 51 |
+
}, []);
|
| 52 |
+
const del = async (id: string) => {
|
| 53 |
+
if (!confirm(t("delete_confirm"))) return;
|
| 54 |
+
await api.del(`/sessions/${id}`);
|
| 55 |
+
load();
|
| 56 |
+
};
|
| 57 |
+
return (
|
| 58 |
+
<div className="space-y-6">
|
| 59 |
+
<div className="flex items-center justify-between gap-3">
|
| 60 |
+
<h1 className="text-3xl font-semibold text-ink">{t("nav_history")}</h1>
|
| 61 |
+
<Link to="/app/new" className="rounded-xl bg-nile px-4 py-2.5 text-sm font-medium text-white dark:text-paper">{t("nav_new")}</Link>
|
| 62 |
+
</div>
|
| 63 |
+
{!rows ? <Spinner /> : rows.length === 0 ? <p className="text-muted">{t("empty_dash")}</p> : <SessionList rows={rows} onDelete={del} />}
|
| 64 |
+
</div>
|
| 65 |
+
);
|
| 66 |
+
}
|
frontend/src/pages/InterviewRoom.tsx
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Camera, CameraOff, Mic, Square, Volume2 } from "lucide-react";
|
| 2 |
+
import { useCallback, useEffect, useRef, useState } from "react";
|
| 3 |
+
import { Link, useNavigate, useParams } from "react-router-dom";
|
| 4 |
+
import { Button, ErrorNote, Logo, Spinner, Waveform } from "../components/ui";
|
| 5 |
+
import { api, type Session } from "../lib/api";
|
| 6 |
+
import { useI18n } from "../lib/i18n";
|
| 7 |
+
import { fmtClock, speak, stopSpeaking, usePresence, useRecorder, type Recording } from "../lib/media";
|
| 8 |
+
|
| 9 |
+
type Next = { done: boolean; idx?: number; total: number; question?: string; kind?: string; is_followup?: boolean; answer_seconds?: number };
|
| 10 |
+
type Phase = "loading" | "asking" | "ready" | "recording" | "review_short" | "saving" | "waiting_followup" | "done" | "finishing";
|
| 11 |
+
|
| 12 |
+
export default function InterviewRoom() {
|
| 13 |
+
const { id } = useParams();
|
| 14 |
+
const { t } = useI18n();
|
| 15 |
+
const nav = useNavigate();
|
| 16 |
+
const rec = useRecorder(36);
|
| 17 |
+
const presence = usePresence();
|
| 18 |
+
const videoRef = useRef<HTMLVideoElement | null>(null);
|
| 19 |
+
const [session, setSession] = useState<Session | null>(null);
|
| 20 |
+
const [next, setNext] = useState<Next | null>(null);
|
| 21 |
+
const [phase, setPhase] = useState<Phase>("loading");
|
| 22 |
+
const [error, setError] = useState<string | null>(null);
|
| 23 |
+
const [saved, setSaved] = useState(0);
|
| 24 |
+
const pending = useRef<Recording | null>(null);
|
| 25 |
+
const autoStop = useRef<number>(0);
|
| 26 |
+
|
| 27 |
+
const ask = useCallback((n: Next) => {
|
| 28 |
+
setNext(n);
|
| 29 |
+
if (n.done || !n.question) return;
|
| 30 |
+
setPhase("asking");
|
| 31 |
+
speak(n.question, () => setPhase((p) => (p === "asking" ? "ready" : p)));
|
| 32 |
+
}, []);
|
| 33 |
+
|
| 34 |
+
const loadNext = useCallback(async () => {
|
| 35 |
+
const n = await api.get<Next>(`/sessions/${id}/next`);
|
| 36 |
+
if (n.done) {
|
| 37 |
+
setNext(n);
|
| 38 |
+
setPhase("waiting_followup");
|
| 39 |
+
// give the last answer's analysis a moment to propose a follow-up question
|
| 40 |
+
for (let i = 0; i < 8; i++) {
|
| 41 |
+
await new Promise((r) => setTimeout(r, 3000));
|
| 42 |
+
const m = await api.get<Next>(`/sessions/${id}/next`);
|
| 43 |
+
if (!m.done) {
|
| 44 |
+
ask(m);
|
| 45 |
+
return;
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
setPhase("done");
|
| 49 |
+
} else ask(n);
|
| 50 |
+
}, [id, ask]);
|
| 51 |
+
|
| 52 |
+
useEffect(() => {
|
| 53 |
+
api.get<Session>(`/sessions/${id}`).then((s) => {
|
| 54 |
+
setSession(s);
|
| 55 |
+
if (s.status !== "in_progress") {
|
| 56 |
+
nav(`/app/report/${id}`, { replace: true });
|
| 57 |
+
return;
|
| 58 |
+
}
|
| 59 |
+
setSaved(s.answers?.length ?? 0);
|
| 60 |
+
loadNext().catch((e) => setError(e.message));
|
| 61 |
+
}).catch((e) => setError(e.message));
|
| 62 |
+
return () => stopSpeaking();
|
| 63 |
+
}, [id, nav, loadNext]);
|
| 64 |
+
|
| 65 |
+
const upload = useCallback(async (r: Recording) => {
|
| 66 |
+
if (!next || next.idx == null) return;
|
| 67 |
+
setPhase("saving");
|
| 68 |
+
const form = new FormData();
|
| 69 |
+
form.append("idx", String(next.idx));
|
| 70 |
+
form.append("file", r.blob, `answer${r.ext}`);
|
| 71 |
+
const p = presence.end();
|
| 72 |
+
if (p) form.append("presence", JSON.stringify(p));
|
| 73 |
+
try {
|
| 74 |
+
await api.upload(`/sessions/${id}/answers`, form);
|
| 75 |
+
setSaved((x) => x + 1);
|
| 76 |
+
await loadNext();
|
| 77 |
+
} catch (e: any) {
|
| 78 |
+
setError(e.message);
|
| 79 |
+
setPhase("ready");
|
| 80 |
+
}
|
| 81 |
+
}, [next, id, presence, loadNext]);
|
| 82 |
+
|
| 83 |
+
const startAnswer = async () => {
|
| 84 |
+
stopSpeaking();
|
| 85 |
+
setError(null);
|
| 86 |
+
try {
|
| 87 |
+
await rec.start();
|
| 88 |
+
presence.begin();
|
| 89 |
+
setPhase("recording");
|
| 90 |
+
const limit = (next?.answer_seconds ?? session?.context.answer_seconds ?? 120) * 1000;
|
| 91 |
+
window.clearTimeout(autoStop.current);
|
| 92 |
+
autoStop.current = window.setTimeout(() => stopAnswer(), limit);
|
| 93 |
+
} catch {
|
| 94 |
+
setError(t("mic_error"));
|
| 95 |
+
}
|
| 96 |
+
};
|
| 97 |
+
|
| 98 |
+
const stopAnswer = async () => {
|
| 99 |
+
window.clearTimeout(autoStop.current);
|
| 100 |
+
const r = await rec.stop();
|
| 101 |
+
if (r.seconds < 3) {
|
| 102 |
+
pending.current = r;
|
| 103 |
+
setPhase("review_short");
|
| 104 |
+
return;
|
| 105 |
+
}
|
| 106 |
+
upload(r);
|
| 107 |
+
};
|
| 108 |
+
|
| 109 |
+
const finish = async () => {
|
| 110 |
+
setPhase("finishing");
|
| 111 |
+
stopSpeaking();
|
| 112 |
+
try {
|
| 113 |
+
await api.post(`/sessions/${id}/finish`);
|
| 114 |
+
nav(`/app/report/${id}`, { replace: true });
|
| 115 |
+
} catch (e: any) {
|
| 116 |
+
setError(e.message);
|
| 117 |
+
setPhase("done");
|
| 118 |
+
}
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
if (!session && !error) return <Spinner />;
|
| 122 |
+
const limit = next?.answer_seconds ?? session?.context.answer_seconds ?? 120;
|
| 123 |
+
const total = next?.total ?? session?.context.plan.length ?? 0;
|
| 124 |
+
const qNumber = (next?.idx ?? 0) + 1;
|
| 125 |
+
|
| 126 |
+
return (
|
| 127 |
+
<div className="flex min-h-screen flex-col bg-paper">
|
| 128 |
+
<header className="flex items-center justify-between gap-4 border-b border-line bg-surface px-4 py-3 sm:px-6">
|
| 129 |
+
<Link to="/app" aria-label="Dashboard"><Logo size={24} /></Link>
|
| 130 |
+
<div className="flex flex-1 items-center justify-center gap-3">
|
| 131 |
+
{total > 0 && (
|
| 132 |
+
<div className="hidden w-64 items-center gap-3 sm:flex" aria-label={t("q_of", { n: Math.min(qNumber, total), total })}>
|
| 133 |
+
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-sunken">
|
| 134 |
+
<div className="h-full rounded-full bg-nile transition-all" style={{ width: `${(saved / total) * 100}%` }} />
|
| 135 |
+
</div>
|
| 136 |
+
<span className="text-sm tabular text-muted">{saved}/{total}</span>
|
| 137 |
+
</div>
|
| 138 |
+
)}
|
| 139 |
+
</div>
|
| 140 |
+
<Button variant="outline" onClick={finish} disabled={saved === 0 || phase === "recording" || phase === "finishing"}>{t("finish_now")}</Button>
|
| 141 |
+
</header>
|
| 142 |
+
|
| 143 |
+
<main className="mx-auto grid w-full max-w-5xl flex-1 gap-6 px-4 py-8 sm:px-6 lg:grid-cols-[1fr_260px]">
|
| 144 |
+
<section className="flex flex-col">
|
| 145 |
+
{error && <div className="mb-4"><ErrorNote>{error}</ErrorNote></div>}
|
| 146 |
+
|
| 147 |
+
{phase === "finishing" || phase === "done" || phase === "waiting_followup" ? (
|
| 148 |
+
<div className="flex flex-1 flex-col items-center justify-center gap-6 text-center">
|
| 149 |
+
<div className="h-16 w-60"><Waveform animated={phase !== "done"} bars={28} color="var(--color-nile)" /></div>
|
| 150 |
+
<p className="font-display text-2xl text-ink">{t("interview_done")}</p>
|
| 151 |
+
<p className="text-muted">{t("answers_saved", { n: saved })}</p>
|
| 152 |
+
<Button size="lg" onClick={finish} busy={phase === "finishing"} disabled={phase === "waiting_followup"}>{t("finish_now")}</Button>
|
| 153 |
+
</div>
|
| 154 |
+
) : (
|
| 155 |
+
<>
|
| 156 |
+
{/* interviewer */}
|
| 157 |
+
<div className="rounded-3xl border border-line bg-surface p-6 sm:p-8">
|
| 158 |
+
<div className="flex items-center justify-between gap-3">
|
| 159 |
+
<p className="text-sm font-medium text-muted">
|
| 160 |
+
{next?.is_followup ? t("followup") : t("q_of", { n: qNumber, total })}
|
| 161 |
+
</p>
|
| 162 |
+
{next?.question && (
|
| 163 |
+
<button onClick={() => { setPhase("asking"); speak(next.question!, () => setPhase((p) => (p === "asking" ? "ready" : p))); }}
|
| 164 |
+
disabled={phase === "recording"} className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-sm text-nile hover:bg-nile-soft disabled:opacity-40">
|
| 165 |
+
<Volume2 size={16} /> {t("listen_again")}
|
| 166 |
+
</button>
|
| 167 |
+
)}
|
| 168 |
+
</div>
|
| 169 |
+
<p className="ltr mt-4 font-display text-2xl font-medium leading-snug text-ink sm:text-[1.7rem]" dir="ltr">
|
| 170 |
+
{phase === "loading" ? "…" : next?.question}
|
| 171 |
+
</p>
|
| 172 |
+
<div className="mt-6 h-8 w-40">{phase === "asking" && <Waveform animated bars={18} color="var(--color-nile)" />}</div>
|
| 173 |
+
</div>
|
| 174 |
+
|
| 175 |
+
{/* candidate */}
|
| 176 |
+
<div className="mt-6 rounded-3xl border border-line bg-surface p-6 sm:p-8">
|
| 177 |
+
{phase === "review_short" ? (
|
| 178 |
+
<div className="space-y-4 text-center">
|
| 179 |
+
<p className="text-ink">{t("too_short")}</p>
|
| 180 |
+
<div className="flex justify-center gap-3">
|
| 181 |
+
<Button onClick={startAnswer}>{t("record_again")}</Button>
|
| 182 |
+
<Button variant="outline" onClick={() => pending.current && upload(pending.current)}>{t("use_it")}</Button>
|
| 183 |
+
</div>
|
| 184 |
+
</div>
|
| 185 |
+
) : phase === "saving" ? (
|
| 186 |
+
<Spinner label={t("uploading")} />
|
| 187 |
+
) : (
|
| 188 |
+
<div className="flex flex-col items-center gap-5">
|
| 189 |
+
<div className="h-16 w-full max-w-md">
|
| 190 |
+
<Waveform levels={phase === "recording" ? rec.levels : undefined} bars={36}
|
| 191 |
+
color={phase === "recording" ? "var(--color-amber)" : "var(--color-line)"} />
|
| 192 |
+
</div>
|
| 193 |
+
{phase === "recording" ? (
|
| 194 |
+
<>
|
| 195 |
+
<p className="flex items-center gap-2 text-sm tabular text-danger">
|
| 196 |
+
<span className="pulse-dot h-2.5 w-2.5 rounded-full bg-danger" /> {t("recording")} {fmtClock(rec.seconds)}
|
| 197 |
+
<span className="text-muted">· {t("time_left", { t: fmtClock(limit - rec.seconds) })}</span>
|
| 198 |
+
</p>
|
| 199 |
+
<Button size="lg" variant="danger" onClick={stopAnswer}><Square size={18} /> {t("stop_answer")}</Button>
|
| 200 |
+
</>
|
| 201 |
+
) : (
|
| 202 |
+
<>
|
| 203 |
+
<p className="text-sm text-muted">{t("get_ready")}</p>
|
| 204 |
+
<Button size="lg" onClick={startAnswer} disabled={phase === "loading"}><Mic size={18} /> {t("start_answer")}</Button>
|
| 205 |
+
</>
|
| 206 |
+
)}
|
| 207 |
+
</div>
|
| 208 |
+
)}
|
| 209 |
+
</div>
|
| 210 |
+
</>
|
| 211 |
+
)}
|
| 212 |
+
</section>
|
| 213 |
+
|
| 214 |
+
{/* camera */}
|
| 215 |
+
<aside className="space-y-3">
|
| 216 |
+
<div className="relative aspect-[4/3] overflow-hidden rounded-2xl border border-line bg-sunken">
|
| 217 |
+
<video ref={videoRef} muted playsInline className={`h-full w-full scale-x-[-1] object-cover ${presence.enabled ? "" : "hidden"}`} />
|
| 218 |
+
{!presence.enabled && <div className="flex h-full items-center justify-center text-muted"><CameraOff size={28} /></div>}
|
| 219 |
+
</div>
|
| 220 |
+
<Button variant="outline" className="w-full" onClick={() => (presence.enabled ? presence.disable() : presence.enable(videoRef.current))}
|
| 221 |
+
disabled={phase === "recording"}>
|
| 222 |
+
{presence.enabled ? <><CameraOff size={16} /> {t("camera_off")}</> : <><Camera size={16} /> {t("camera_on")}</>}
|
| 223 |
+
</Button>
|
| 224 |
+
<p className="text-xs text-muted">{t("camera_hint")}</p>
|
| 225 |
+
</aside>
|
| 226 |
+
</main>
|
| 227 |
+
</div>
|
| 228 |
+
);
|
| 229 |
+
}
|
frontend/src/pages/JobDetail.tsx
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Pencil, Star } from "lucide-react";
|
| 2 |
+
import { useEffect, useState } from "react";
|
| 3 |
+
import { Link, useNavigate, useParams } from "react-router-dom";
|
| 4 |
+
import { Badge, Panel, Spinner, StatusBadge, fmtDate, scoreColor, useCatalog } from "../components/ui";
|
| 5 |
+
import { api, type CandidateRow, type Job } from "../lib/api";
|
| 6 |
+
import { trackName, useI18n } from "../lib/i18n";
|
| 7 |
+
import { CopyLink } from "./Jobs";
|
| 8 |
+
|
| 9 |
+
const FILTERS = ["all", "new", "shortlisted", "rejected", "hired"] as const;
|
| 10 |
+
|
| 11 |
+
export default function JobDetail() {
|
| 12 |
+
const { id } = useParams();
|
| 13 |
+
const { t, lang } = useI18n();
|
| 14 |
+
const catalog = useCatalog();
|
| 15 |
+
const nav = useNavigate();
|
| 16 |
+
const [job, setJob] = useState<Job | null>(null);
|
| 17 |
+
const [rows, setRows] = useState<CandidateRow[] | null>(null);
|
| 18 |
+
const [filter, setFilter] = useState<(typeof FILTERS)[number]>("all");
|
| 19 |
+
useEffect(() => {
|
| 20 |
+
api.get<Job>(`/jobs/${id}`).then(setJob);
|
| 21 |
+
api.get<CandidateRow[]>(`/jobs/${id}/candidates`).then(setRows);
|
| 22 |
+
}, [id]);
|
| 23 |
+
if (!job || !rows) return <Spinner />;
|
| 24 |
+
const shown = rows.filter((r) => filter === "all" || r.review_status === filter);
|
| 25 |
+
const sigTone = (s: string | null) => (s === "strong_yes" || s === "yes" ? "good" : s === "maybe" ? "warn" : s === "no" ? "bad" : "neutral");
|
| 26 |
+
const rvTone = { new: "neutral", shortlisted: "info", rejected: "bad", hired: "good" } as const;
|
| 27 |
+
|
| 28 |
+
return (
|
| 29 |
+
<div className="space-y-6">
|
| 30 |
+
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
| 31 |
+
<div>
|
| 32 |
+
<h1 className="text-3xl font-semibold text-ink">{job.title}</h1>
|
| 33 |
+
<p className="mt-1 text-muted">{trackName(catalog?.tracks, job.track, lang)}, {t(`lv_${job.level}` as "lv_junior")}, {job.questions.length} {t("questions")}</p>
|
| 34 |
+
</div>
|
| 35 |
+
<div className="flex items-center gap-2">
|
| 36 |
+
<CopyLink token={job.share_token} />
|
| 37 |
+
<Link to={`/app/jobs/${job.id}/edit`} className="inline-flex items-center gap-1.5 rounded-lg border border-line px-3 py-1.5 text-sm text-ink hover:border-nile"><Pencil size={14} /> {t("edit")}</Link>
|
| 38 |
+
</div>
|
| 39 |
+
</div>
|
| 40 |
+
<p className="text-sm text-muted">{t("share_hint")}</p>
|
| 41 |
+
|
| 42 |
+
<Panel title={t("candidates_title")} action={
|
| 43 |
+
<div className="flex flex-wrap gap-1">
|
| 44 |
+
{FILTERS.map((f) => (
|
| 45 |
+
<button key={f} onClick={() => setFilter(f)} aria-pressed={filter === f}
|
| 46 |
+
className={`rounded-lg px-2.5 py-1 text-sm ${filter === f ? "bg-nile-soft font-medium text-nile-deep" : "text-muted hover:bg-sunken"}`}>
|
| 47 |
+
{f === "all" ? t("all") : t(`rv_${f}`)}
|
| 48 |
+
</button>
|
| 49 |
+
))}
|
| 50 |
+
</div>
|
| 51 |
+
}>
|
| 52 |
+
{shown.length === 0 ? (
|
| 53 |
+
<p className="py-6 text-center text-muted">{t("empty_candidates")}</p>
|
| 54 |
+
) : (
|
| 55 |
+
<div className="-mx-5 overflow-x-auto sm:-mx-6">
|
| 56 |
+
<table className="w-full min-w-[640px] text-start text-[15px]">
|
| 57 |
+
<thead>
|
| 58 |
+
<tr className="border-b border-line text-sm text-muted">
|
| 59 |
+
<th className="px-5 py-2 text-start font-medium sm:px-6">#</th>
|
| 60 |
+
<th className="py-2 text-start font-medium">{t("c_name")}</th>
|
| 61 |
+
<th className="py-2 text-start font-medium">{t("c_score")}</th>
|
| 62 |
+
<th className="py-2 text-start font-medium">{t("c_signal")}</th>
|
| 63 |
+
<th className="py-2 text-start font-medium">{t("c_status")}</th>
|
| 64 |
+
<th className="px-5 py-2 text-start font-medium sm:px-6">{t("c_date")}</th>
|
| 65 |
+
</tr>
|
| 66 |
+
</thead>
|
| 67 |
+
<tbody>
|
| 68 |
+
{shown.map((r, i) => (
|
| 69 |
+
<tr key={r.id} onClick={() => nav(`/app/report/${r.id}`)} className="cursor-pointer border-b border-line last:border-0 hover:bg-sunken/60">
|
| 70 |
+
<td className="px-5 py-3 tabular text-muted sm:px-6">{i + 1}</td>
|
| 71 |
+
<td className="py-3">
|
| 72 |
+
<p className="font-medium text-ink">{r.full_name || r.email}</p>
|
| 73 |
+
{r.rating && <p className="flex">{Array.from({ length: r.rating }).map((_, k) => <Star key={k} size={12} className="fill-amber text-amber" />)}</p>}
|
| 74 |
+
</td>
|
| 75 |
+
<td className="py-3">
|
| 76 |
+
{r.status === "completed" ? (
|
| 77 |
+
<span className="font-display text-lg font-semibold tabular" style={{ color: scoreColor(r.overall_score) }}>{r.overall_score != null ? Math.round(r.overall_score) : "–"}</span>
|
| 78 |
+
) : <StatusBadge status={r.status} />}
|
| 79 |
+
</td>
|
| 80 |
+
<td className="py-3">{r.hiring_signal && <Badge tone={sigTone(r.hiring_signal)}>{t(`sig_${r.hiring_signal}` as "sig_yes")}</Badge>}</td>
|
| 81 |
+
<td className="py-3"><Badge tone={rvTone[r.review_status]}>{t(`rv_${r.review_status}`)}</Badge></td>
|
| 82 |
+
<td className="px-5 py-3 text-sm text-muted sm:px-6">{fmtDate(r.created_at, lang)}</td>
|
| 83 |
+
</tr>
|
| 84 |
+
))}
|
| 85 |
+
</tbody>
|
| 86 |
+
</table>
|
| 87 |
+
</div>
|
| 88 |
+
)}
|
| 89 |
+
</Panel>
|
| 90 |
+
<p className="text-sm text-muted">{t("fairness")}</p>
|
| 91 |
+
</div>
|
| 92 |
+
);
|
| 93 |
+
}
|
frontend/src/pages/JobEditor.tsx
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ArrowDown, ArrowUp, Plus, Sparkles, Trash2 } from "lucide-react";
|
| 2 |
+
import { useEffect, useState } from "react";
|
| 3 |
+
import { useNavigate, useParams } from "react-router-dom";
|
| 4 |
+
import { Button, ErrorNote, Field, Input, Panel, Select, Spinner, Textarea, useCatalog } from "../components/ui";
|
| 5 |
+
import { api, type Job, type PlanQuestion } from "../lib/api";
|
| 6 |
+
import { useI18n } from "../lib/i18n";
|
| 7 |
+
|
| 8 |
+
export default function JobEditor() {
|
| 9 |
+
const { id } = useParams();
|
| 10 |
+
const { t, lang } = useI18n();
|
| 11 |
+
const catalog = useCatalog();
|
| 12 |
+
const nav = useNavigate();
|
| 13 |
+
const [loaded, setLoaded] = useState(!id);
|
| 14 |
+
const [title, setTitle] = useState("");
|
| 15 |
+
const [track, setTrack] = useState("data_engineering");
|
| 16 |
+
const [level, setLevel] = useState("junior");
|
| 17 |
+
const [desc, setDesc] = useState("");
|
| 18 |
+
const [secs, setSecs] = useState(120);
|
| 19 |
+
const [status, setStatus] = useState<Job["status"]>("open");
|
| 20 |
+
const [qs, setQs] = useState<PlanQuestion[]>([{ text: "" }]);
|
| 21 |
+
const [busy, setBusy] = useState(false);
|
| 22 |
+
const [suggesting, setSuggesting] = useState(false);
|
| 23 |
+
const [error, setError] = useState<string | null>(null);
|
| 24 |
+
|
| 25 |
+
useEffect(() => {
|
| 26 |
+
if (!id) return;
|
| 27 |
+
api.get<Job>(`/jobs/${id}`).then((j) => {
|
| 28 |
+
setTitle(j.title); setTrack(j.track); setLevel(j.level); setDesc(j.description || "");
|
| 29 |
+
setSecs(j.answer_seconds); setStatus(j.status); setQs(j.questions.length ? j.questions : [{ text: "" }]);
|
| 30 |
+
setLoaded(true);
|
| 31 |
+
});
|
| 32 |
+
}, [id]);
|
| 33 |
+
|
| 34 |
+
const suggest = async () => {
|
| 35 |
+
setSuggesting(true);
|
| 36 |
+
setError(null);
|
| 37 |
+
try {
|
| 38 |
+
const r = await api.post<{ questions: PlanQuestion[] }>("/questions/generate", { track, level, interview_type: "mixed", count: 6, custom_role: title, jd_text: desc });
|
| 39 |
+
setQs((cur) => [...cur.filter((x) => x.text.trim()), ...r.questions]);
|
| 40 |
+
} catch (e: any) {
|
| 41 |
+
setError(e.message);
|
| 42 |
+
} finally {
|
| 43 |
+
setSuggesting(false);
|
| 44 |
+
}
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
const move = (i: number, d: number) => setQs((cur) => {
|
| 48 |
+
const n = [...cur];
|
| 49 |
+
const j = i + d;
|
| 50 |
+
if (j < 0 || j >= n.length) return n;
|
| 51 |
+
[n[i], n[j]] = [n[j], n[i]];
|
| 52 |
+
return n;
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
const save = async () => {
|
| 56 |
+
setBusy(true);
|
| 57 |
+
setError(null);
|
| 58 |
+
try {
|
| 59 |
+
const body = { title, track, level, description: desc, answer_seconds: secs, status, questions: qs.filter((x) => x.text.trim()) };
|
| 60 |
+
const j = id ? await api.put<Job>(`/jobs/${id}`, body) : await api.post<Job>("/jobs", body);
|
| 61 |
+
nav(`/app/jobs/${j.id}`);
|
| 62 |
+
} catch (e: any) {
|
| 63 |
+
setError(e.message);
|
| 64 |
+
setBusy(false);
|
| 65 |
+
}
|
| 66 |
+
};
|
| 67 |
+
|
| 68 |
+
if (!loaded || !catalog) return <Spinner />;
|
| 69 |
+
const levels = ["intern", "junior", "mid", "senior", "lead"];
|
| 70 |
+
return (
|
| 71 |
+
<div className="space-y-6">
|
| 72 |
+
<h1 className="text-3xl font-semibold text-ink">{id ? title : t("new_job")}</h1>
|
| 73 |
+
<Panel>
|
| 74 |
+
<div className="grid gap-4 md:grid-cols-2">
|
| 75 |
+
<Field label={t("job_title")}><Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Junior Data Engineer" /></Field>
|
| 76 |
+
<Field label={t("track")}><Select value={track} onChange={setTrack} options={catalog.tracks.map((x) => ({ value: x.id, label: lang === "ar" ? x.ar : x.en }))} /></Field>
|
| 77 |
+
<Field label={t("level")}><Select value={level} onChange={setLevel} options={levels.map((l) => ({ value: l, label: t(`lv_${l}` as "lv_junior") }))} /></Field>
|
| 78 |
+
<div className="grid grid-cols-2 gap-4">
|
| 79 |
+
<Field label={t("answer_time")}>
|
| 80 |
+
<Select value={String(secs)} onChange={(v) => setSecs(+v)} options={[60, 90, 120, 180, 240, 300].map((s) => ({ value: String(s), label: `${s / 60} ${t("min")}` }))} />
|
| 81 |
+
</Field>
|
| 82 |
+
<Field label={t("job_status")}>
|
| 83 |
+
<Select value={status} onChange={(v) => setStatus(v as Job["status"])} options={(["open", "draft", "closed"] as const).map((s) => ({ value: s, label: t(`jst_${s}`) }))} />
|
| 84 |
+
</Field>
|
| 85 |
+
</div>
|
| 86 |
+
<div className="md:col-span-2"><Field label={t("job_desc")}><Textarea value={desc} onChange={(e) => setDesc(e.target.value)} /></Field></div>
|
| 87 |
+
</div>
|
| 88 |
+
</Panel>
|
| 89 |
+
|
| 90 |
+
<Panel title={t("questions")} action={<Button variant="outline" onClick={suggest} busy={suggesting}><Sparkles size={16} /> {suggesting ? t("suggesting") : t("suggest")}</Button>}>
|
| 91 |
+
<ol className="space-y-3">
|
| 92 |
+
{qs.map((q, i) => (
|
| 93 |
+
<li key={i} className="flex items-start gap-2">
|
| 94 |
+
<span className="mt-2.5 w-6 flex-none text-center text-sm tabular text-muted">{i + 1}</span>
|
| 95 |
+
<Textarea value={q.text} onChange={(e) => setQs((cur) => cur.map((x, k) => (k === i ? { ...x, text: e.target.value } : x)))}
|
| 96 |
+
placeholder={t("question_ph")} className="ltr min-h-16" dir="ltr" />
|
| 97 |
+
<div className="flex flex-col">
|
| 98 |
+
<button onClick={() => move(i, -1)} className="rounded p-1 text-muted hover:bg-sunken" aria-label="Move up"><ArrowUp size={16} /></button>
|
| 99 |
+
<button onClick={() => move(i, 1)} className="rounded p-1 text-muted hover:bg-sunken" aria-label="Move down"><ArrowDown size={16} /></button>
|
| 100 |
+
</div>
|
| 101 |
+
<button onClick={() => setQs((cur) => cur.filter((_, k) => k !== i))} className="mt-1 rounded-lg p-2 text-muted hover:bg-danger-soft hover:text-danger" aria-label={t("delete")}>
|
| 102 |
+
<Trash2 size={16} />
|
| 103 |
+
</button>
|
| 104 |
+
</li>
|
| 105 |
+
))}
|
| 106 |
+
</ol>
|
| 107 |
+
<Button variant="quiet" className="mt-3" onClick={() => setQs((cur) => [...cur, { text: "" }])}><Plus size={16} /> {t("add_question")}</Button>
|
| 108 |
+
</Panel>
|
| 109 |
+
|
| 110 |
+
{error && <ErrorNote>{error}</ErrorNote>}
|
| 111 |
+
<div className="flex justify-end gap-3">
|
| 112 |
+
<Button variant="quiet" onClick={() => nav(-1)}>{t("cancel")}</Button>
|
| 113 |
+
<Button size="lg" onClick={save} busy={busy} disabled={title.trim().length < 2 || !qs.some((x) => x.text.trim())}>{t("save_job")}</Button>
|
| 114 |
+
</div>
|
| 115 |
+
</div>
|
| 116 |
+
);
|
| 117 |
+
}
|
frontend/src/pages/Jobs.tsx
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Link2, Plus } from "lucide-react";
|
| 2 |
+
import { useEffect, useState } from "react";
|
| 3 |
+
import { Link, Navigate } from "react-router-dom";
|
| 4 |
+
import { Badge, Spinner, fmtDate, useCatalog } from "../components/ui";
|
| 5 |
+
import { api, type Job } from "../lib/api";
|
| 6 |
+
import { useAuth } from "../lib/auth";
|
| 7 |
+
import { trackName, useI18n } from "../lib/i18n";
|
| 8 |
+
|
| 9 |
+
export function CopyLink({ token }: { token: string }) {
|
| 10 |
+
const { t } = useI18n();
|
| 11 |
+
const [done, setDone] = useState(false);
|
| 12 |
+
const url = `${location.origin}/apply/${token}`;
|
| 13 |
+
return (
|
| 14 |
+
<button onClick={async () => { await navigator.clipboard.writeText(url).catch(() => undefined); setDone(true); setTimeout(() => setDone(false), 2000); }}
|
| 15 |
+
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-sm font-medium text-nile hover:bg-nile-soft">
|
| 16 |
+
<Link2 size={15} /> {done ? t("link_copied") : t("copy_link")}
|
| 17 |
+
</button>
|
| 18 |
+
);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
export default function Jobs() {
|
| 22 |
+
const { t, lang } = useI18n();
|
| 23 |
+
const { profile } = useAuth();
|
| 24 |
+
const catalog = useCatalog();
|
| 25 |
+
const [jobs, setJobs] = useState<Job[] | null>(null);
|
| 26 |
+
useEffect(() => {
|
| 27 |
+
if (profile?.company_id) api.get<Job[]>("/jobs").then(setJobs).catch(() => setJobs([]));
|
| 28 |
+
}, [profile]);
|
| 29 |
+
if (profile && !profile.company_id) return <Navigate to="/app/welcome?as=company" replace />;
|
| 30 |
+
if (!jobs) return <Spinner />;
|
| 31 |
+
const tone = { open: "good", draft: "neutral", closed: "bad" } as const;
|
| 32 |
+
return (
|
| 33 |
+
<div className="space-y-6">
|
| 34 |
+
<div className="flex items-center justify-between gap-3">
|
| 35 |
+
<div>
|
| 36 |
+
<h1 className="text-3xl font-semibold text-ink">{t("jobs_title")}</h1>
|
| 37 |
+
{profile?.company && <p className="text-muted">{profile.company.name}</p>}
|
| 38 |
+
</div>
|
| 39 |
+
<Link to="/app/jobs/new" className="inline-flex items-center gap-2 rounded-xl bg-nile px-4 py-2.5 text-sm font-medium text-white dark:text-paper"><Plus size={16} /> {t("new_job")}</Link>
|
| 40 |
+
</div>
|
| 41 |
+
{jobs.length === 0 ? (
|
| 42 |
+
<p className="rounded-2xl border border-dashed border-line p-8 text-center text-muted">{t("empty_jobs")}</p>
|
| 43 |
+
) : (
|
| 44 |
+
<ul className="divide-y divide-line overflow-hidden rounded-2xl border border-line bg-surface">
|
| 45 |
+
{jobs.map((j) => (
|
| 46 |
+
<li key={j.id} className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center">
|
| 47 |
+
<Link to={`/app/jobs/${j.id}`} className="min-w-0 flex-1">
|
| 48 |
+
<p className="truncate font-medium text-ink">{j.title}</p>
|
| 49 |
+
<p className="mt-0.5 flex flex-wrap items-center gap-2 text-sm text-muted">
|
| 50 |
+
<span>{trackName(catalog?.tracks, j.track, lang)}</span>
|
| 51 |
+
<Badge tone={tone[j.status]}>{t(`jst_${j.status}`)}</Badge>
|
| 52 |
+
<span>{fmtDate(j.created_at, lang)}</span>
|
| 53 |
+
</p>
|
| 54 |
+
</Link>
|
| 55 |
+
<div className="flex items-center gap-6">
|
| 56 |
+
<div className="text-center"><p className="font-display text-xl font-semibold tabular text-ink">{j.applicants ?? 0}</p><p className="text-xs text-muted">{t("applicants")}</p></div>
|
| 57 |
+
<div className="text-center"><p className="font-display text-xl font-semibold tabular text-ink">{j.completed ?? 0}</p><p className="text-xs text-muted">{t("completed_n")}</p></div>
|
| 58 |
+
<CopyLink token={j.share_token} />
|
| 59 |
+
</div>
|
| 60 |
+
</li>
|
| 61 |
+
))}
|
| 62 |
+
</ul>
|
| 63 |
+
)}
|
| 64 |
+
</div>
|
| 65 |
+
);
|
| 66 |
+
}
|
frontend/src/pages/Landing.tsx
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useEffect, useState } from "react";
|
| 2 |
+
import { Link } from "react-router-dom";
|
| 3 |
+
import { Bar, BarChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
| 4 |
+
import { PublicHeader } from "../components/Shell";
|
| 5 |
+
import { Waveform, useCatalog } from "../components/ui";
|
| 6 |
+
import { api } from "../lib/api";
|
| 7 |
+
import { useI18n } from "../lib/i18n";
|
| 8 |
+
|
| 9 |
+
type Card = { traits: { trait: string; label: string; model_r: number; human_r: number }[]; reference?: { interviews: number } };
|
| 10 |
+
|
| 11 |
+
function LiveInterview() {
|
| 12 |
+
const { t } = useI18n();
|
| 13 |
+
return (
|
| 14 |
+
<div className="rise relative rounded-3xl border border-line bg-surface p-5 sm:p-6" aria-label="Example of a practice interview">
|
| 15 |
+
<div className="flex items-center gap-2 text-sm text-muted">
|
| 16 |
+
<span className="pulse-dot inline-block h-2 w-2 rounded-full bg-nile" /> {t("demo_asking")}
|
| 17 |
+
</div>
|
| 18 |
+
<p className="ltr mt-3 font-display text-lg font-medium text-ink sm:text-xl" dir="ltr">{t("demo_question")}</p>
|
| 19 |
+
<div className="mt-6 rounded-2xl bg-sunken p-4">
|
| 20 |
+
<div className="flex items-center justify-between text-sm">
|
| 21 |
+
<span className="font-medium text-ink">{t("demo_you")}</span>
|
| 22 |
+
<span className="flex items-center gap-1.5 text-danger"><span className="pulse-dot h-2 w-2 rounded-full bg-danger" />{t("demo_listening")}</span>
|
| 23 |
+
</div>
|
| 24 |
+
<div className="mt-3 h-14"><Waveform animated bars={40} /></div>
|
| 25 |
+
<p className="ltr mt-3 text-sm text-muted" dir="ltr">{t("demo_answer")}</p>
|
| 26 |
+
</div>
|
| 27 |
+
<div className="mt-5 grid grid-cols-3 gap-3">
|
| 28 |
+
{[[t("demo_content"), 8.1], [t("demo_delivery"), 7.4], [t("demo_structure"), 6.2]].map(([k, v]) => (
|
| 29 |
+
<div key={k as string}>
|
| 30 |
+
<div className="text-xs text-muted">{k}</div>
|
| 31 |
+
<div className="font-display text-2xl font-semibold tabular text-ink">{v}<span className="text-sm text-muted">/10</span></div>
|
| 32 |
+
<div className="mt-1 h-1.5 rounded-full bg-sunken"><div className="h-full rounded-full bg-amber" style={{ width: `${(v as number) * 10}%` }} /></div>
|
| 33 |
+
</div>
|
| 34 |
+
))}
|
| 35 |
+
</div>
|
| 36 |
+
</div>
|
| 37 |
+
);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
export default function Landing() {
|
| 41 |
+
const { t, lang } = useI18n();
|
| 42 |
+
const catalog = useCatalog();
|
| 43 |
+
const [card, setCard] = useState<Card | null>(null);
|
| 44 |
+
useEffect(() => {
|
| 45 |
+
api.get<Card>(`/model-card?lang=${lang}`).then(setCard).catch(() => setCard(null));
|
| 46 |
+
}, [lang]);
|
| 47 |
+
const chart = (card?.traits ?? []).filter((x) => ["RecommendHiring", "Overall", "Excited", "EngagingTone", "Friendly", "NoFillers", "StructuredAnswers", "Engaged"].includes(x.trait));
|
| 48 |
+
|
| 49 |
+
const feature = (title: string, body: string) => (
|
| 50 |
+
<div className="border-t border-line pt-4">
|
| 51 |
+
<h3 className="text-base font-semibold text-ink">{title}</h3>
|
| 52 |
+
<p className="mt-1.5 text-[15px] text-muted">{body}</p>
|
| 53 |
+
</div>
|
| 54 |
+
);
|
| 55 |
+
|
| 56 |
+
return (
|
| 57 |
+
<div className="min-h-screen">
|
| 58 |
+
<PublicHeader />
|
| 59 |
+
<main>
|
| 60 |
+
{/* hero */}
|
| 61 |
+
<section className="mx-auto grid max-w-6xl items-center gap-10 px-4 pb-16 pt-6 sm:px-6 lg:grid-cols-[1.05fr_1fr] lg:pb-24 lg:pt-14">
|
| 62 |
+
<div>
|
| 63 |
+
<h1 className="max-w-xl text-4xl font-semibold text-ink sm:text-5xl lg:text-[3.4rem]">{t("hero_title")}</h1>
|
| 64 |
+
<p className="mt-5 max-w-xl text-lg text-muted">{t("hero_sub")}</p>
|
| 65 |
+
<div className="mt-8 flex flex-wrap gap-3">
|
| 66 |
+
<Link to="/signup" className="rounded-xl bg-nile px-6 py-3.5 font-medium text-white hover:bg-nile-deep dark:text-paper">{t("cta_candidate")}</Link>
|
| 67 |
+
<Link to="/signup?as=company" className="rounded-xl border border-line bg-surface px-6 py-3.5 font-medium text-ink hover:border-nile hover:text-nile">{t("cta_company")}</Link>
|
| 68 |
+
</div>
|
| 69 |
+
</div>
|
| 70 |
+
<LiveInterview />
|
| 71 |
+
</section>
|
| 72 |
+
|
| 73 |
+
{/* how it works: a real sequence */}
|
| 74 |
+
<section className="border-y border-line bg-surface">
|
| 75 |
+
<div className="mx-auto max-w-6xl px-4 py-12 sm:px-6">
|
| 76 |
+
<h2 className="text-2xl font-semibold text-ink">{t("how_title")}</h2>
|
| 77 |
+
<ol className="mt-6 grid gap-6 sm:grid-cols-3">
|
| 78 |
+
{[t("how_1"), t("how_2"), t("how_3")].map((s, i) => (
|
| 79 |
+
<li key={i} className="flex gap-4">
|
| 80 |
+
<span className="flex h-9 w-9 flex-none items-center justify-center rounded-full bg-nile-soft font-display font-semibold text-nile-deep">{i + 1}</span>
|
| 81 |
+
<p className="pt-1 text-[15px] text-ink">{s}</p>
|
| 82 |
+
</li>
|
| 83 |
+
))}
|
| 84 |
+
</ol>
|
| 85 |
+
</div>
|
| 86 |
+
</section>
|
| 87 |
+
|
| 88 |
+
{/* two audiences */}
|
| 89 |
+
<section className="mx-auto grid max-w-6xl gap-12 px-4 py-16 sm:px-6 lg:grid-cols-2">
|
| 90 |
+
<div>
|
| 91 |
+
<h2 className="text-2xl font-semibold text-ink">{t("for_candidates")}</h2>
|
| 92 |
+
<div className="mt-6 grid gap-5 sm:grid-cols-2">
|
| 93 |
+
{feature(t("c1_t"), t("c1_d"))}{feature(t("c2_t"), t("c2_d"))}{feature(t("c3_t"), t("c3_d"))}{feature(t("c4_t"), t("c4_d"))}
|
| 94 |
+
</div>
|
| 95 |
+
</div>
|
| 96 |
+
<div>
|
| 97 |
+
<h2 className="text-2xl font-semibold text-ink">{t("for_companies")}</h2>
|
| 98 |
+
<div className="mt-6 grid gap-5 sm:grid-cols-2">
|
| 99 |
+
{feature(t("r1_t"), t("r1_d"))}{feature(t("r2_t"), t("r2_d"))}{feature(t("r3_t"), t("r3_d"))}{feature(t("r4_t"), t("r4_d"))}
|
| 100 |
+
</div>
|
| 101 |
+
</div>
|
| 102 |
+
</section>
|
| 103 |
+
|
| 104 |
+
{/* science */}
|
| 105 |
+
{chart.length > 0 && (
|
| 106 |
+
<section className="bg-ink text-paper dark:bg-surface dark:text-ink">
|
| 107 |
+
<div className="mx-auto grid max-w-6xl gap-10 px-4 py-16 sm:px-6 lg:grid-cols-[1fr_1.3fr]">
|
| 108 |
+
<div>
|
| 109 |
+
<h2 className="text-3xl font-semibold">{t("science_title")}</h2>
|
| 110 |
+
<p className="mt-4 text-[17px] opacity-80">{t("science_text")}</p>
|
| 111 |
+
<p className="mt-4 text-sm opacity-60">{t("science_note")}</p>
|
| 112 |
+
</div>
|
| 113 |
+
<div className="h-80 rounded-2xl bg-surface p-4 text-ink" dir="ltr">
|
| 114 |
+
<ResponsiveContainer width="100%" height="100%">
|
| 115 |
+
<BarChart data={chart} layout="vertical" margin={{ left: 10, right: 16, top: 4, bottom: 4 }} barGap={2}>
|
| 116 |
+
<CartesianGrid horizontal={false} stroke="var(--color-line)" />
|
| 117 |
+
<XAxis type="number" domain={[0, 1]} tickCount={6} stroke="var(--color-muted)" fontSize={12} />
|
| 118 |
+
<YAxis type="category" dataKey="label" width={lang === "ar" ? 120 : 150} stroke="var(--color-muted)" fontSize={12}
|
| 119 |
+
tick={{ fill: "var(--color-ink)" }} />
|
| 120 |
+
<Tooltip cursor={{ fill: "var(--color-sunken)" }} contentStyle={{ background: "var(--color-surface)", border: "1px solid var(--color-line)", borderRadius: 12 }} />
|
| 121 |
+
<Legend wrapperStyle={{ fontSize: 12 }} />
|
| 122 |
+
<Bar dataKey="model_r" name={t("science_model")} fill="var(--color-nile)" radius={[0, 4, 4, 0]} />
|
| 123 |
+
<Bar dataKey="human_r" name={t("science_human")} fill="var(--color-amber)" radius={[0, 4, 4, 0]} />
|
| 124 |
+
</BarChart>
|
| 125 |
+
</ResponsiveContainer>
|
| 126 |
+
</div>
|
| 127 |
+
</div>
|
| 128 |
+
</section>
|
| 129 |
+
)}
|
| 130 |
+
|
| 131 |
+
{/* tracks */}
|
| 132 |
+
<section className="mx-auto max-w-6xl px-4 py-16 sm:px-6">
|
| 133 |
+
<h2 className="text-2xl font-semibold text-ink">{t("tracks_title")}</h2>
|
| 134 |
+
<div className="mt-6 flex flex-wrap gap-2">
|
| 135 |
+
{catalog?.tracks.map((tr) => (
|
| 136 |
+
<span key={tr.id} className="rounded-full border border-line bg-surface px-3.5 py-1.5 text-sm text-ink">{lang === "ar" ? tr.ar : tr.en}</span>
|
| 137 |
+
))}
|
| 138 |
+
</div>
|
| 139 |
+
<div className="mt-12 flex flex-col items-start gap-4 rounded-3xl bg-nile-soft p-8 sm:flex-row sm:items-center sm:justify-between">
|
| 140 |
+
<div className="h-12 w-48"><Waveform bars={30} color="var(--color-nile)" /></div>
|
| 141 |
+
<Link to="/signup" className="rounded-xl bg-nile px-6 py-3.5 font-medium text-white hover:bg-nile-deep dark:text-paper">{t("cta_candidate")}</Link>
|
| 142 |
+
</div>
|
| 143 |
+
</section>
|
| 144 |
+
</main>
|
| 145 |
+
<footer className="border-t border-line">
|
| 146 |
+
<div className="mx-auto flex max-w-6xl flex-col gap-2 px-4 py-8 text-sm text-muted sm:px-6">
|
| 147 |
+
<p>{t("footer_text")}</p>
|
| 148 |
+
<p>{t("footer_privacy")}</p>
|
| 149 |
+
</div>
|
| 150 |
+
</footer>
|
| 151 |
+
</div>
|
| 152 |
+
);
|
| 153 |
+
}
|
frontend/src/pages/NewInterview.tsx
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Search } from "lucide-react";
|
| 2 |
+
import { useMemo, useState } from "react";
|
| 3 |
+
import { useNavigate } from "react-router-dom";
|
| 4 |
+
import { Button, ErrorNote, Field, Input, Panel, Spinner, Textarea, Waveform, useCatalog } from "../components/ui";
|
| 5 |
+
import { api, type Session } from "../lib/api";
|
| 6 |
+
import { useAuth } from "../lib/auth";
|
| 7 |
+
import { useI18n } from "../lib/i18n";
|
| 8 |
+
|
| 9 |
+
const LEVELS = ["intern", "junior", "mid", "senior", "lead"] as const;
|
| 10 |
+
const TYPES = ["mixed", "technical", "behavioral", "hr", "case"] as const;
|
| 11 |
+
|
| 12 |
+
export default function NewInterview() {
|
| 13 |
+
const { t, lang } = useI18n();
|
| 14 |
+
const { profile } = useAuth();
|
| 15 |
+
const catalog = useCatalog();
|
| 16 |
+
const nav = useNavigate();
|
| 17 |
+
const [track, setTrack] = useState(profile?.target_track || "data_engineering");
|
| 18 |
+
const [query, setQuery] = useState("");
|
| 19 |
+
const [level, setLevel] = useState<string>("junior");
|
| 20 |
+
const [itype, setType] = useState<string>("mixed");
|
| 21 |
+
const [count, setCount] = useState(6);
|
| 22 |
+
const [fbLang, setFbLang] = useState<"en" | "ar">(lang);
|
| 23 |
+
const [role, setRole] = useState("");
|
| 24 |
+
const [cv, setCv] = useState("");
|
| 25 |
+
const [jd, setJd] = useState("");
|
| 26 |
+
const [busy, setBusy] = useState(false);
|
| 27 |
+
const [error, setError] = useState<string | null>(null);
|
| 28 |
+
|
| 29 |
+
const groups = useMemo(() => {
|
| 30 |
+
const q = query.trim().toLowerCase();
|
| 31 |
+
const list = (catalog?.tracks ?? []).filter((x) => !q || x.en.toLowerCase().includes(q) || x.ar.includes(q));
|
| 32 |
+
return ["tech", "design", "business", "other"].map((g) => ({ g, items: list.filter((x) => x.group === g) })).filter((x) => x.items.length);
|
| 33 |
+
}, [catalog, query]);
|
| 34 |
+
|
| 35 |
+
const start = async () => {
|
| 36 |
+
setBusy(true);
|
| 37 |
+
setError(null);
|
| 38 |
+
try {
|
| 39 |
+
const s = await api.post<Session>("/sessions", { track, level, interview_type: itype, count, custom_role: role, cv_text: cv, jd_text: jd, language: fbLang });
|
| 40 |
+
nav(`/app/interview/${s.id}`);
|
| 41 |
+
} catch (e: any) {
|
| 42 |
+
setError(e.message);
|
| 43 |
+
setBusy(false);
|
| 44 |
+
}
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
if (busy)
|
| 48 |
+
return (
|
| 49 |
+
<div className="flex flex-col items-center justify-center gap-6 py-24 text-center">
|
| 50 |
+
<div className="h-16 w-56"><Waveform animated bars={26} color="var(--color-nile)" /></div>
|
| 51 |
+
<p className="text-lg text-ink">{t("preparing")}</p>
|
| 52 |
+
</div>
|
| 53 |
+
);
|
| 54 |
+
if (!catalog) return <Spinner />;
|
| 55 |
+
|
| 56 |
+
const chip = (active: boolean) =>
|
| 57 |
+
`rounded-xl border px-3.5 py-2 text-sm text-start transition-colors ${active ? "border-nile bg-nile-soft font-medium text-nile-deep" : "border-line bg-surface text-ink hover:border-nile"}`;
|
| 58 |
+
|
| 59 |
+
return (
|
| 60 |
+
<div className="space-y-6">
|
| 61 |
+
<h1 className="text-3xl font-semibold text-ink">{t("new_title")}</h1>
|
| 62 |
+
|
| 63 |
+
<Panel title={t("track")} action={
|
| 64 |
+
<div className="relative w-48 sm:w-64">
|
| 65 |
+
<Search size={16} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-muted" />
|
| 66 |
+
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("search_tracks")} className="ps-9" aria-label={t("search_tracks")} />
|
| 67 |
+
</div>
|
| 68 |
+
}>
|
| 69 |
+
<div className="space-y-4">
|
| 70 |
+
{groups.map(({ g, items }) => (
|
| 71 |
+
<div key={g}>
|
| 72 |
+
<p className="mb-2 text-sm text-muted">{t(`g_${g}` as "g_tech")}</p>
|
| 73 |
+
<div className="flex flex-wrap gap-2">
|
| 74 |
+
{items.map((x) => (
|
| 75 |
+
<button key={x.id} onClick={() => setTrack(x.id)} className={chip(track === x.id)} aria-pressed={track === x.id}>
|
| 76 |
+
{lang === "ar" ? x.ar : x.en}
|
| 77 |
+
</button>
|
| 78 |
+
))}
|
| 79 |
+
</div>
|
| 80 |
+
</div>
|
| 81 |
+
))}
|
| 82 |
+
</div>
|
| 83 |
+
</Panel>
|
| 84 |
+
|
| 85 |
+
<div className="grid gap-6 lg:grid-cols-2">
|
| 86 |
+
<Panel title={t("level")}>
|
| 87 |
+
<div className="flex flex-wrap gap-2">
|
| 88 |
+
{LEVELS.map((l) => <button key={l} onClick={() => setLevel(l)} className={chip(level === l)} aria-pressed={level === l}>{t(`lv_${l}` as "lv_junior")}</button>)}
|
| 89 |
+
</div>
|
| 90 |
+
<div className="mt-6 grid grid-cols-2 gap-4">
|
| 91 |
+
<Field label={t("count")}>
|
| 92 |
+
<div className="flex items-center gap-3">
|
| 93 |
+
<input type="range" min={3} max={10} value={count} onChange={(e) => setCount(+e.target.value)} className="flex-1 accent-[var(--color-nile)]" aria-label={t("count")} />
|
| 94 |
+
<span className="w-6 text-center font-display font-semibold tabular text-ink">{count}</span>
|
| 95 |
+
</div>
|
| 96 |
+
</Field>
|
| 97 |
+
<Field label={t("feedback_lang")}>
|
| 98 |
+
<div className="flex gap-2">
|
| 99 |
+
<button onClick={() => setFbLang("en")} className={chip(fbLang === "en")}>{t("english")}</button>
|
| 100 |
+
<button onClick={() => setFbLang("ar")} className={chip(fbLang === "ar")}>{t("arabic")}</button>
|
| 101 |
+
</div>
|
| 102 |
+
</Field>
|
| 103 |
+
</div>
|
| 104 |
+
</Panel>
|
| 105 |
+
<Panel title={t("style")}>
|
| 106 |
+
<div className="grid gap-2">
|
| 107 |
+
{TYPES.map((ty) => (
|
| 108 |
+
<button key={ty} onClick={() => setType(ty)} className={chip(itype === ty)} aria-pressed={itype === ty}>
|
| 109 |
+
<span className="font-medium">{t(`ty_${ty}` as "ty_mixed")}</span>
|
| 110 |
+
<span className="ms-2 text-muted">{t(`ty_${ty}_d` as "ty_mixed_d")}</span>
|
| 111 |
+
</button>
|
| 112 |
+
))}
|
| 113 |
+
</div>
|
| 114 |
+
</Panel>
|
| 115 |
+
</div>
|
| 116 |
+
|
| 117 |
+
<Panel>
|
| 118 |
+
<div className="grid gap-4 lg:grid-cols-3">
|
| 119 |
+
<Field label={`${t("custom_role")} (${t("optional")})`}><Input value={role} onChange={(e) => setRole(e.target.value)} placeholder={t("custom_role_ph")} /></Field>
|
| 120 |
+
<Field label={`${t("jd")} (${t("optional")})`}><Textarea value={jd} onChange={(e) => setJd(e.target.value)} placeholder={t("jd_ph")} /></Field>
|
| 121 |
+
<Field label={`${t("cv")} (${t("optional")})`}><Textarea value={cv} onChange={(e) => setCv(e.target.value)} placeholder={t("cv_ph")} /></Field>
|
| 122 |
+
</div>
|
| 123 |
+
</Panel>
|
| 124 |
+
|
| 125 |
+
{error && <ErrorNote>{error}</ErrorNote>}
|
| 126 |
+
<div className="flex justify-end"><Button size="lg" onClick={start}>{t("start")}</Button></div>
|
| 127 |
+
</div>
|
| 128 |
+
);
|
| 129 |
+
}
|
frontend/src/pages/Onboarding.tsx
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Building2, Mic } from "lucide-react";
|
| 2 |
+
import { useState } from "react";
|
| 3 |
+
import { useNavigate, useSearchParams } from "react-router-dom";
|
| 4 |
+
import { PublicHeader } from "../components/Shell";
|
| 5 |
+
import { Button, ErrorNote, Field, Input } from "../components/ui";
|
| 6 |
+
import { api } from "../lib/api";
|
| 7 |
+
import { useAuth } from "../lib/auth";
|
| 8 |
+
import { useI18n } from "../lib/i18n";
|
| 9 |
+
|
| 10 |
+
export default function Onboarding() {
|
| 11 |
+
const { t } = useI18n();
|
| 12 |
+
const { refresh } = useAuth();
|
| 13 |
+
const nav = useNavigate();
|
| 14 |
+
const [params] = useSearchParams();
|
| 15 |
+
const [choice, setChoice] = useState<"candidate" | "recruiter">(params.get("as") === "company" ? "recruiter" : "candidate");
|
| 16 |
+
const [company, setCompany] = useState("");
|
| 17 |
+
const [website, setWebsite] = useState("");
|
| 18 |
+
const [busy, setBusy] = useState(false);
|
| 19 |
+
const [error, setError] = useState<string | null>(null);
|
| 20 |
+
|
| 21 |
+
const go = async () => {
|
| 22 |
+
setBusy(true);
|
| 23 |
+
setError(null);
|
| 24 |
+
try {
|
| 25 |
+
if (choice === "recruiter") {
|
| 26 |
+
await api.post("/companies", { name: company, website: website || null });
|
| 27 |
+
await refresh();
|
| 28 |
+
nav("/app/jobs");
|
| 29 |
+
} else {
|
| 30 |
+
await api.patch("/me", { role: "candidate" });
|
| 31 |
+
await refresh();
|
| 32 |
+
nav("/app/new");
|
| 33 |
+
}
|
| 34 |
+
} catch (e: any) {
|
| 35 |
+
setError(e.message);
|
| 36 |
+
} finally {
|
| 37 |
+
setBusy(false);
|
| 38 |
+
}
|
| 39 |
+
};
|
| 40 |
+
|
| 41 |
+
const option = (key: "candidate" | "recruiter", Icon: typeof Mic, title: string, desc: string) => (
|
| 42 |
+
<button type="button" onClick={() => setChoice(key)} aria-pressed={choice === key}
|
| 43 |
+
className={`flex w-full items-start gap-4 rounded-2xl border p-5 text-start transition-colors ${choice === key ? "border-nile bg-nile-soft" : "border-line bg-surface hover:border-nile"}`}>
|
| 44 |
+
<Icon className={choice === key ? "text-nile" : "text-muted"} size={24} />
|
| 45 |
+
<span>
|
| 46 |
+
<span className="block font-semibold text-ink">{title}</span>
|
| 47 |
+
<span className="mt-0.5 block text-sm text-muted">{desc}</span>
|
| 48 |
+
</span>
|
| 49 |
+
</button>
|
| 50 |
+
);
|
| 51 |
+
|
| 52 |
+
return (
|
| 53 |
+
<div className="min-h-screen">
|
| 54 |
+
<PublicHeader />
|
| 55 |
+
<main className="mx-auto max-w-lg px-4 pb-16 pt-8">
|
| 56 |
+
<h1 className="text-3xl font-semibold text-ink">{t("onboard_title")}</h1>
|
| 57 |
+
<div className="mt-8 space-y-3">
|
| 58 |
+
{option("candidate", Mic, t("onboard_candidate"), t("onboard_candidate_d"))}
|
| 59 |
+
{option("recruiter", Building2, t("onboard_recruiter"), t("onboard_recruiter_d"))}
|
| 60 |
+
</div>
|
| 61 |
+
{choice === "recruiter" && (
|
| 62 |
+
<div className="mt-6 space-y-4">
|
| 63 |
+
<Field label={t("company_name")}><Input value={company} onChange={(e) => setCompany(e.target.value)} required /></Field>
|
| 64 |
+
<Field label={`${t("website")} (${t("optional")})`}><Input value={website} onChange={(e) => setWebsite(e.target.value)} type="url" placeholder="https://" /></Field>
|
| 65 |
+
</div>
|
| 66 |
+
)}
|
| 67 |
+
{error && <div className="mt-4"><ErrorNote>{error}</ErrorNote></div>}
|
| 68 |
+
<Button className="mt-8 w-full" size="lg" busy={busy} disabled={choice === "recruiter" && company.trim().length < 2} onClick={go}>{t("continue")}</Button>
|
| 69 |
+
</main>
|
| 70 |
+
</div>
|
| 71 |
+
);
|
| 72 |
+
}
|
frontend/src/pages/Report.tsx
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ChevronDown, Download, Play, Star } from "lucide-react";
|
| 2 |
+
import { useEffect, useState } from "react";
|
| 3 |
+
import { Link, useParams } from "react-router-dom";
|
| 4 |
+
import { Badge, Button, ErrorNote, Field, Meter, Panel, ScoreRing, Spinner, Textarea, Waveform, fmtDate, scoreColor, useCatalog } from "../components/ui";
|
| 5 |
+
import { api, type Answer, type Session } from "../lib/api";
|
| 6 |
+
import { useAuth } from "../lib/auth";
|
| 7 |
+
import { trackName, useI18n } from "../lib/i18n";
|
| 8 |
+
|
| 9 |
+
function AnswerAudio({ sid, idx }: { sid: string; idx: number }) {
|
| 10 |
+
const [url, setUrl] = useState<string | null>(null);
|
| 11 |
+
const [busy, setBusy] = useState(false);
|
| 12 |
+
useEffect(() => () => { if (url) URL.revokeObjectURL(url); }, [url]);
|
| 13 |
+
if (url) return <audio src={url} controls autoPlay className="h-10 w-full" />;
|
| 14 |
+
return (
|
| 15 |
+
<button onClick={async () => { setBusy(true); try { setUrl(URL.createObjectURL(await api.blob(`/sessions/${sid}/answers/${idx}/audio`))); } finally { setBusy(false); } }}
|
| 16 |
+
className="inline-flex items-center gap-2 rounded-lg border border-line px-3 py-1.5 text-sm text-ink hover:border-nile hover:text-nile" disabled={busy}>
|
| 17 |
+
<Play size={14} /> {busy ? "…" : "Play"}
|
| 18 |
+
</button>
|
| 19 |
+
);
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
function QuestionCard({ a, sid, open: initial, lang }: { a: Answer; sid: string; open: boolean; lang: string }) {
|
| 23 |
+
const { t } = useI18n();
|
| 24 |
+
const [open, setOpen] = useState(initial);
|
| 25 |
+
const fb = a.feedback || ({} as NonNullable<Answer["feedback"]>);
|
| 26 |
+
const dir = lang === "ar" ? "rtl" : "ltr";
|
| 27 |
+
const p = a.presence;
|
| 28 |
+
return (
|
| 29 |
+
<div className="rounded-2xl border border-line bg-surface">
|
| 30 |
+
<button onClick={() => setOpen(!open)} className="flex w-full items-start gap-4 p-4 text-start sm:p-5" aria-expanded={open}>
|
| 31 |
+
<span className="flex h-10 w-10 flex-none items-center justify-center rounded-xl font-display font-semibold tabular text-white dark:text-paper"
|
| 32 |
+
style={{ background: scoreColor(a.score, 10) }}>{a.score ?? "–"}</span>
|
| 33 |
+
<span className="min-w-0 flex-1">
|
| 34 |
+
{a.is_followup && <Badge tone="info">{t("followup")}</Badge>}
|
| 35 |
+
<span className="ltr mt-1 block font-medium text-ink" dir="ltr">{a.question}</span>
|
| 36 |
+
</span>
|
| 37 |
+
<ChevronDown size={18} className={`mt-2 flex-none text-muted transition-transform ${open ? "rotate-180" : ""}`} />
|
| 38 |
+
</button>
|
| 39 |
+
{open && (
|
| 40 |
+
<div className="space-y-3 border-t border-line p-4 sm:p-5">
|
| 41 |
+
<div className="rounded-xl bg-sunken p-4">
|
| 42 |
+
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
|
| 43 |
+
<span className="text-sm font-medium text-muted">{t("your_answer")}</span>
|
| 44 |
+
{a.has_audio && <AnswerAudio sid={sid} idx={a.idx} />}
|
| 45 |
+
</div>
|
| 46 |
+
<p className="ltr text-[15px] text-ink" dir="ltr">{a.transcript || t("not_answered")}</p>
|
| 47 |
+
</div>
|
| 48 |
+
{fb.summary && <p className="text-[15px] text-ink" dir={dir}>{fb.summary}</p>}
|
| 49 |
+
<div className="grid gap-3 md:grid-cols-2">
|
| 50 |
+
{!!fb.strengths?.length && (
|
| 51 |
+
<div className="rounded-xl bg-nile-soft p-4"><p className="mb-1.5 text-sm font-medium text-nile-deep">{t("went_well")}</p>
|
| 52 |
+
<ul className="list-disc space-y-1 ps-5 text-[15px] text-ink" dir={dir}>{fb.strengths.map((s, i) => <li key={i}>{s}</li>)}</ul></div>
|
| 53 |
+
)}
|
| 54 |
+
{!!fb.improvements?.length && (
|
| 55 |
+
<div className="rounded-xl bg-amber-soft p-4"><p className="mb-1.5 text-sm font-medium text-ink">{t("improve")}</p>
|
| 56 |
+
<ul className="list-disc space-y-1 ps-5 text-[15px] text-ink" dir={dir}>{fb.improvements.map((s, i) => <li key={i}>{s}</li>)}</ul></div>
|
| 57 |
+
)}
|
| 58 |
+
</div>
|
| 59 |
+
{fb.improved_answer && (
|
| 60 |
+
<div className="rounded-xl border border-line p-4"><p className="mb-1.5 text-sm font-medium text-muted">{t("stronger")}</p>
|
| 61 |
+
<p className="ltr text-[15px] text-ink" dir="ltr">{fb.improved_answer}</p></div>
|
| 62 |
+
)}
|
| 63 |
+
<div className="flex flex-wrap gap-2 text-sm text-muted">
|
| 64 |
+
{fb.delivery_tip && <span dir={dir}><span className="font-medium text-ink">{t("delivery_tip")}: </span>{fb.delivery_tip}</span>}
|
| 65 |
+
</div>
|
| 66 |
+
{p && (
|
| 67 |
+
<div className="flex flex-wrap gap-2">
|
| 68 |
+
<Badge>{t("eye_contact")}: {Math.round((p.eye_contact ?? 0) * 100)}%</Badge>
|
| 69 |
+
<Badge>{t("smile")}: {Math.round((p.smile ?? 0) * 100)}%</Badge>
|
| 70 |
+
<Badge>{t("face_visible")}: {Math.round((p.face_visible ?? 0) * 100)}%</Badge>
|
| 71 |
+
</div>
|
| 72 |
+
)}
|
| 73 |
+
</div>
|
| 74 |
+
)}
|
| 75 |
+
</div>
|
| 76 |
+
);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
function ReviewPanel({ s }: { s: Session }) {
|
| 80 |
+
const { t } = useI18n();
|
| 81 |
+
const [status, setStatus] = useState("new");
|
| 82 |
+
const [rating, setRating] = useState<number | null>(null);
|
| 83 |
+
const [notes, setNotes] = useState("");
|
| 84 |
+
const [saved, setSaved] = useState(false);
|
| 85 |
+
useEffect(() => {
|
| 86 |
+
if (!s.job_id) return;
|
| 87 |
+
api.get<any[]>(`/jobs/${s.job_id}/candidates`).then((rows) => {
|
| 88 |
+
const r = rows.find((x) => x.id === s.id);
|
| 89 |
+
if (r) { setStatus(r.review_status); setRating(r.rating); setNotes(r.notes || ""); }
|
| 90 |
+
});
|
| 91 |
+
}, [s]);
|
| 92 |
+
const save = async () => {
|
| 93 |
+
await api.put(`/reviews/${s.id}`, { status, rating, notes });
|
| 94 |
+
setSaved(true);
|
| 95 |
+
setTimeout(() => setSaved(false), 2000);
|
| 96 |
+
};
|
| 97 |
+
return (
|
| 98 |
+
<Panel title={t("decision")}>
|
| 99 |
+
<p className="mb-4 text-sm text-muted">{t("fairness")}</p>
|
| 100 |
+
<div className="flex flex-wrap gap-2">
|
| 101 |
+
{(["new", "shortlisted", "rejected", "hired"] as const).map((k) => (
|
| 102 |
+
<button key={k} onClick={() => setStatus(k)} aria-pressed={status === k}
|
| 103 |
+
className={`rounded-xl border px-3.5 py-2 text-sm ${status === k ? "border-nile bg-nile-soft font-medium text-nile-deep" : "border-line text-ink hover:border-nile"}`}>{t(`rv_${k}`)}</button>
|
| 104 |
+
))}
|
| 105 |
+
</div>
|
| 106 |
+
<div className="mt-4 flex items-center gap-1" aria-label={t("rating")}>
|
| 107 |
+
<span className="me-2 text-sm text-muted">{t("rating")}</span>
|
| 108 |
+
{[1, 2, 3, 4, 5].map((n) => (
|
| 109 |
+
<button key={n} onClick={() => setRating(n)} aria-label={`${n}`} className="p-0.5">
|
| 110 |
+
<Star size={20} className={rating && n <= rating ? "fill-amber text-amber" : "text-line"} />
|
| 111 |
+
</button>
|
| 112 |
+
))}
|
| 113 |
+
</div>
|
| 114 |
+
<div className="mt-4"><Field label={t("notes")}><Textarea value={notes} onChange={(e) => setNotes(e.target.value)} /></Field></div>
|
| 115 |
+
<div className="mt-4 flex items-center gap-3"><Button onClick={save}>{t("save_review")}</Button>{saved && <span className="text-sm text-nile">{t("saved")}</span>}</div>
|
| 116 |
+
</Panel>
|
| 117 |
+
);
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
export default function ReportPage() {
|
| 121 |
+
const { id } = useParams();
|
| 122 |
+
const { t, lang, d } = useI18n();
|
| 123 |
+
const level = (k?: string) => (k ? d.lv[k] ?? k : "–");
|
| 124 |
+
const { profile } = useAuth();
|
| 125 |
+
const catalog = useCatalog();
|
| 126 |
+
const [s, setS] = useState<Session | null>(null);
|
| 127 |
+
const [error, setError] = useState<string | null>(null);
|
| 128 |
+
const [pdfBusy, setPdfBusy] = useState(false);
|
| 129 |
+
|
| 130 |
+
useEffect(() => {
|
| 131 |
+
let timer = 0;
|
| 132 |
+
const load = () => api.get<Session>(`/sessions/${id}`).then((x) => {
|
| 133 |
+
setS(x);
|
| 134 |
+
if (x.status === "processing" || x.status === "in_progress") timer = window.setTimeout(load, 4000);
|
| 135 |
+
}).catch((e) => setError(e.message));
|
| 136 |
+
load();
|
| 137 |
+
return () => window.clearTimeout(timer);
|
| 138 |
+
}, [id]);
|
| 139 |
+
|
| 140 |
+
if (error) return <ErrorNote>{error}</ErrorNote>;
|
| 141 |
+
if (!s) return <Spinner />;
|
| 142 |
+
if (s.status === "processing" || (s.status === "in_progress" && s.user_id !== profile?.id))
|
| 143 |
+
return (
|
| 144 |
+
<div className="flex flex-col items-center justify-center gap-6 py-24 text-center">
|
| 145 |
+
<div className="h-16 w-64"><Waveform animated bars={30} color="var(--color-nile)" /></div>
|
| 146 |
+
<h1 className="text-2xl font-semibold text-ink">{t("building_title")}</h1>
|
| 147 |
+
<p className="max-w-md text-muted">{t("building_sub")}</p>
|
| 148 |
+
</div>
|
| 149 |
+
);
|
| 150 |
+
if (s.status === "failed" || !s.report) return <ErrorNote>{t("report_failed")} {s.error}</ErrorNote>;
|
| 151 |
+
|
| 152 |
+
const r = s.report;
|
| 153 |
+
const sum = r.summary || {};
|
| 154 |
+
const dir = s.language === "ar" ? "rtl" : "ltr";
|
| 155 |
+
const v = r.voice || {};
|
| 156 |
+
const isReviewer = s.user_id !== profile?.id;
|
| 157 |
+
const signal = sum.hiring_signal;
|
| 158 |
+
const title = s.job?.title || s.context.role || trackName(catalog?.tracks, s.track, lang);
|
| 159 |
+
const humanR = r.calibrated?.traits.find((x) => x.trait === "Overall")?.human_r ?? 0.5;
|
| 160 |
+
|
| 161 |
+
const downloadPdf = async () => {
|
| 162 |
+
setPdfBusy(true);
|
| 163 |
+
try {
|
| 164 |
+
const b = await api.blob(`/sessions/${s.id}/pdf`);
|
| 165 |
+
const url = URL.createObjectURL(b);
|
| 166 |
+
const a = document.createElement("a");
|
| 167 |
+
a.href = url;
|
| 168 |
+
a.download = `evalbot-report-${s.id.slice(0, 8)}.pdf`;
|
| 169 |
+
a.click();
|
| 170 |
+
setTimeout(() => URL.revokeObjectURL(url), 5000);
|
| 171 |
+
} finally {
|
| 172 |
+
setPdfBusy(false);
|
| 173 |
+
}
|
| 174 |
+
};
|
| 175 |
+
|
| 176 |
+
return (
|
| 177 |
+
<div className="space-y-6">
|
| 178 |
+
{/* header */}
|
| 179 |
+
<div className="flex flex-col gap-6 rounded-3xl border border-line bg-surface p-6 sm:flex-row sm:items-center sm:p-8">
|
| 180 |
+
<ScoreRing value={r.overall} size={132} label={t("overall")} />
|
| 181 |
+
<div className="min-w-0 flex-1">
|
| 182 |
+
<p className="text-sm text-muted">{isReviewer && s.candidate ? `${s.candidate.full_name || s.candidate.email}, ` : ""}{title}, {fmtDate(s.created_at, lang)}</p>
|
| 183 |
+
<h1 className="mt-1 text-2xl font-semibold text-ink" dir={dir}>{sum.headline || t("overall")}</h1>
|
| 184 |
+
<div className="mt-4 flex flex-wrap gap-6">
|
| 185 |
+
<div><p className="text-sm text-muted">{t("content")}</p><p className="font-display text-xl font-semibold tabular text-ink">{r.content_score ?? "–"}</p></div>
|
| 186 |
+
<div><p className="text-sm text-muted">{t("delivery")}</p><p className="font-display text-xl font-semibold tabular text-ink">{r.delivery_score != null ? Math.round(r.delivery_score) : "–"}</p></div>
|
| 187 |
+
{signal && <div><p className="text-sm text-muted">{t("hiring_signal")}</p>
|
| 188 |
+
<Badge tone={signal === "strong_yes" || signal === "yes" ? "good" : signal === "maybe" ? "warn" : "bad"}>{t(`sig_${signal}` as "sig_yes")}</Badge></div>}
|
| 189 |
+
</div>
|
| 190 |
+
</div>
|
| 191 |
+
<div className="flex flex-col gap-2">
|
| 192 |
+
<Button variant="outline" onClick={downloadPdf} busy={pdfBusy}><Download size={16} /> {t("download_pdf")}</Button>
|
| 193 |
+
{!isReviewer && s.mode === "mock" && <Link to="/app/new" className="rounded-xl px-4 py-2.5 text-center text-sm font-medium text-nile hover:bg-nile-soft">{t("practice_again")}</Link>}
|
| 194 |
+
</div>
|
| 195 |
+
</div>
|
| 196 |
+
|
| 197 |
+
{isReviewer && s.job_id && <ReviewPanel s={s} />}
|
| 198 |
+
|
| 199 |
+
{!!sum.executive_summary?.length && (
|
| 200 |
+
<Panel title={t("summary")}>
|
| 201 |
+
<ul className="list-disc space-y-1.5 ps-5 text-[15px] text-ink" dir={dir}>{sum.executive_summary.map((x, i) => <li key={i}>{x}</li>)}</ul>
|
| 202 |
+
</Panel>
|
| 203 |
+
)}
|
| 204 |
+
|
| 205 |
+
{/* human-calibrated */}
|
| 206 |
+
{r.calibrated && r.calibrated.traits.length > 0 && (
|
| 207 |
+
<Panel title={t("calibrated_title")}>
|
| 208 |
+
<p className="mb-5 max-w-3xl text-sm text-muted">{t("calibrated_sub", { h: humanR.toFixed(2) })}</p>
|
| 209 |
+
<ul className="grid gap-x-8 gap-y-4 md:grid-cols-2">
|
| 210 |
+
{r.calibrated.traits.map((x) => (
|
| 211 |
+
<li key={x.trait}>
|
| 212 |
+
<div className="mb-1.5 flex items-baseline justify-between gap-3">
|
| 213 |
+
<span className="font-medium text-ink">{x.label}</span>
|
| 214 |
+
<span className="text-sm tabular text-muted">{t("pct", { p: x.percentile })}</span>
|
| 215 |
+
</div>
|
| 216 |
+
<Meter value={x.percentile} />
|
| 217 |
+
<p className="mt-1 text-xs text-muted">{t("reliability")}: r = {x.model_r.toFixed(2)}</p>
|
| 218 |
+
</li>
|
| 219 |
+
))}
|
| 220 |
+
</ul>
|
| 221 |
+
</Panel>
|
| 222 |
+
)}
|
| 223 |
+
|
| 224 |
+
{/* voice */}
|
| 225 |
+
{v && !v.error && (
|
| 226 |
+
<Panel title={t("voice_title")}>
|
| 227 |
+
<div className="grid grid-cols-2 gap-4 md:grid-cols-4">
|
| 228 |
+
<div><p className="text-sm text-muted">{t("speaking_rate")}</p><p className="font-display text-xl font-semibold tabular text-ink">{v.speaking_rate}</p><p className="text-xs text-muted">{t("wps")}</p></div>
|
| 229 |
+
<div><p className="text-sm text-muted">{t("fillers")}</p><p className="font-display text-xl font-semibold tabular text-ink">{(v.filler_ratio * 100).toFixed(1)}%</p>
|
| 230 |
+
<p className="ltr text-xs text-muted" dir="ltr">{Object.entries(v.filler_words || {}).slice(0, 3).map(([k, n]) => `${k} ×${n}`).join(", ")}</p></div>
|
| 231 |
+
<div><p className="text-sm text-muted">{t("fluency")}</p><p className="font-display text-xl font-semibold text-ink">{level(v.interpretation?.fluency_level)}</p></div>
|
| 232 |
+
<div><p className="text-sm text-muted">{t("confidence")}</p><p className="font-display text-xl font-semibold text-ink">{level(v.interpretation?.confidence_level)}</p></div>
|
| 233 |
+
</div>
|
| 234 |
+
</Panel>
|
| 235 |
+
)}
|
| 236 |
+
|
| 237 |
+
{/* per question */}
|
| 238 |
+
<div>
|
| 239 |
+
<h2 className="mb-3 text-lg font-semibold text-ink">{t("per_question")}</h2>
|
| 240 |
+
<div className="space-y-3">{(s.answers || []).map((a, i) => <QuestionCard key={a.id} a={a} sid={s.id} open={i === 0} lang={s.language} />)}</div>
|
| 241 |
+
</div>
|
| 242 |
+
|
| 243 |
+
{(!!sum.strengths?.length || !!sum.weaknesses?.length) && (
|
| 244 |
+
<div className="grid gap-6 lg:grid-cols-2">
|
| 245 |
+
<Panel title={t("strengths")}>
|
| 246 |
+
<ul className="space-y-4" dir={dir}>{sum.strengths?.map((x, i) => (
|
| 247 |
+
<li key={i}><p className="font-medium text-ink">{x.competency}</p><p className="text-[15px] text-ink">{x.explanation}</p>
|
| 248 |
+
<p className="mt-1 text-sm text-muted">{t("evidence")}: <span className="ltr" dir="ltr">{x.evidence}</span></p></li>))}</ul>
|
| 249 |
+
</Panel>
|
| 250 |
+
<Panel title={t("weaknesses")}>
|
| 251 |
+
<ul className="space-y-4" dir={dir}>{sum.weaknesses?.map((x, i) => (
|
| 252 |
+
<li key={i}><p className="font-medium text-ink">{x.area}</p><p className="text-[15px] text-ink">{x.feedback}</p></li>))}</ul>
|
| 253 |
+
</Panel>
|
| 254 |
+
</div>
|
| 255 |
+
)}
|
| 256 |
+
|
| 257 |
+
{!!sum.learning_plan?.length && !isReviewer && (
|
| 258 |
+
<Panel title={t("learning_plan")}>
|
| 259 |
+
<ol className="space-y-4" dir={dir}>{sum.learning_plan.map((x, i) => (
|
| 260 |
+
<li key={i} className="flex gap-4">
|
| 261 |
+
<span className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-nile-soft font-display text-sm font-semibold text-nile-deep">{i + 1}</span>
|
| 262 |
+
<div><p className="font-medium text-ink">{x.topic}</p><p className="text-[15px] text-muted">{x.why}</p><p className="mt-1 text-[15px] text-ink">{x.how}</p></div>
|
| 263 |
+
</li>))}</ol>
|
| 264 |
+
</Panel>
|
| 265 |
+
)}
|
| 266 |
+
|
| 267 |
+
{(!!sum.next_steps?.length || !!sum.role_fit?.length) && (
|
| 268 |
+
<div className="grid gap-6 lg:grid-cols-2">
|
| 269 |
+
{!!sum.role_fit?.length && <Panel title={t("role_fit")}><ul className="list-disc space-y-1.5 ps-5 text-[15px] text-ink" dir={dir}>{sum.role_fit.map((x, i) => <li key={i}>{x}</li>)}</ul></Panel>}
|
| 270 |
+
{!!sum.next_steps?.length && <Panel title={t("next_steps")}><ul className="list-disc space-y-1.5 ps-5 text-[15px] text-ink" dir={dir}>{sum.next_steps.map((x, i) => <li key={i}>{x}</li>)}</ul></Panel>}
|
| 271 |
+
</div>
|
| 272 |
+
)}
|
| 273 |
+
</div>
|
| 274 |
+
);
|
| 275 |
+
}
|
frontend/src/pages/Settings.tsx
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useEffect, useState } from "react";
|
| 2 |
+
import { Button, ErrorNote, Field, Input, Panel, Select, useCatalog } from "../components/ui";
|
| 3 |
+
import { api } from "../lib/api";
|
| 4 |
+
import { updatePassword, useAuth } from "../lib/auth";
|
| 5 |
+
import { useI18n } from "../lib/i18n";
|
| 6 |
+
|
| 7 |
+
export default function SettingsPage() {
|
| 8 |
+
const { t, lang } = useI18n();
|
| 9 |
+
const { profile, refresh, config } = useAuth();
|
| 10 |
+
const catalog = useCatalog();
|
| 11 |
+
const [name, setName] = useState("");
|
| 12 |
+
const [headline, setHeadline] = useState("");
|
| 13 |
+
const [track, setTrack] = useState("");
|
| 14 |
+
const [company, setCompany] = useState("");
|
| 15 |
+
const [pw, setPw] = useState("");
|
| 16 |
+
const [msg, setMsg] = useState<string | null>(null);
|
| 17 |
+
const [error, setError] = useState<string | null>(null);
|
| 18 |
+
const [busy, setBusy] = useState(false);
|
| 19 |
+
|
| 20 |
+
useEffect(() => {
|
| 21 |
+
if (!profile) return;
|
| 22 |
+
setName(profile.full_name || "");
|
| 23 |
+
setHeadline(profile.headline || "");
|
| 24 |
+
setTrack(profile.target_track || "");
|
| 25 |
+
setCompany(profile.company?.name || "");
|
| 26 |
+
}, [profile]);
|
| 27 |
+
|
| 28 |
+
const save = async () => {
|
| 29 |
+
setBusy(true);
|
| 30 |
+
setError(null);
|
| 31 |
+
try {
|
| 32 |
+
await api.patch("/me", { full_name: name, headline, target_track: track || null });
|
| 33 |
+
if (profile?.role === "recruiter" && company.trim()) await api.post("/companies", { name: company.trim() });
|
| 34 |
+
await refresh();
|
| 35 |
+
setMsg(t("saved"));
|
| 36 |
+
} catch (e: any) {
|
| 37 |
+
setError(e.message);
|
| 38 |
+
} finally {
|
| 39 |
+
setBusy(false);
|
| 40 |
+
}
|
| 41 |
+
};
|
| 42 |
+
|
| 43 |
+
const changePw = async () => {
|
| 44 |
+
try {
|
| 45 |
+
await updatePassword(pw);
|
| 46 |
+
setPw("");
|
| 47 |
+
setMsg(t("password_changed"));
|
| 48 |
+
} catch (e: any) {
|
| 49 |
+
setError(e.message);
|
| 50 |
+
}
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
return (
|
| 54 |
+
<div className="space-y-6">
|
| 55 |
+
<h1 className="text-3xl font-semibold text-ink">{t("settings_title")}</h1>
|
| 56 |
+
<Panel title={t("profile")}>
|
| 57 |
+
<div className="grid gap-4 sm:grid-cols-2">
|
| 58 |
+
<Field label={t("full_name")}><Input value={name} onChange={(e) => setName(e.target.value)} /></Field>
|
| 59 |
+
<Field label={t("email")}><Input value={profile?.email || ""} disabled /></Field>
|
| 60 |
+
<Field label={t("headline")}><Input value={headline} onChange={(e) => setHeadline(e.target.value)} placeholder={t("headline_ph")} /></Field>
|
| 61 |
+
<Field label={t("target_track")}>
|
| 62 |
+
<Select value={track} onChange={setTrack} options={[{ value: "", label: "—" }, ...(catalog?.tracks ?? []).map((x) => ({ value: x.id, label: lang === "ar" ? x.ar : x.en }))]} />
|
| 63 |
+
</Field>
|
| 64 |
+
{profile?.role === "recruiter" && (
|
| 65 |
+
<Field label={t("company")}><Input value={company} onChange={(e) => setCompany(e.target.value)} /></Field>
|
| 66 |
+
)}
|
| 67 |
+
</div>
|
| 68 |
+
<div className="mt-5 flex items-center gap-3">
|
| 69 |
+
<Button onClick={save} busy={busy}>{t("save")}</Button>
|
| 70 |
+
{msg && <span className="text-sm text-nile">{msg}</span>}
|
| 71 |
+
</div>
|
| 72 |
+
{error && <div className="mt-4"><ErrorNote>{error}</ErrorNote></div>}
|
| 73 |
+
</Panel>
|
| 74 |
+
{config?.supabase_url && (
|
| 75 |
+
<Panel title={t("change_password")}>
|
| 76 |
+
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
| 77 |
+
<div className="flex-1"><Field label={t("new_password")} hint={t("password_hint")}><Input type="password" value={pw} onChange={(e) => setPw(e.target.value)} minLength={8} autoComplete="new-password" /></Field></div>
|
| 78 |
+
<Button variant="outline" disabled={pw.length < 8} onClick={changePw}>{t("change_password")}</Button>
|
| 79 |
+
</div>
|
| 80 |
+
</Panel>
|
| 81 |
+
)}
|
| 82 |
+
</div>
|
| 83 |
+
);
|
| 84 |
+
}
|
frontend/tsconfig.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"compilerOptions": {
|
| 3 |
+
"target": "ES2022",
|
| 4 |
+
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
| 5 |
+
"module": "ESNext",
|
| 6 |
+
"moduleResolution": "bundler",
|
| 7 |
+
"jsx": "react-jsx",
|
| 8 |
+
"strict": true,
|
| 9 |
+
"noUnusedLocals": true,
|
| 10 |
+
"noUnusedParameters": true,
|
| 11 |
+
"skipLibCheck": true,
|
| 12 |
+
"noEmit": true,
|
| 13 |
+
"isolatedModules": true,
|
| 14 |
+
"resolveJsonModule": true
|
| 15 |
+
},
|
| 16 |
+
"include": ["src"]
|
| 17 |
+
}
|
frontend/tsconfig.tsbuildinfo
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"root":["./src/main.tsx","./src/components/Shell.tsx","./src/components/ui.tsx","./src/lib/api.ts","./src/lib/auth.tsx","./src/lib/i18n.tsx","./src/lib/media.ts","./src/pages/Apply.tsx","./src/pages/Auth.tsx","./src/pages/Dashboard.tsx","./src/pages/History.tsx","./src/pages/InterviewRoom.tsx","./src/pages/JobDetail.tsx","./src/pages/JobEditor.tsx","./src/pages/Jobs.tsx","./src/pages/Landing.tsx","./src/pages/NewInterview.tsx","./src/pages/Onboarding.tsx","./src/pages/Report.tsx","./src/pages/Settings.tsx"],"version":"5.8.3"}
|
frontend/vite.config.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { defineConfig } from "vite";
|
| 2 |
+
import react from "@vitejs/plugin-react";
|
| 3 |
+
import tailwindcss from "@tailwindcss/vite";
|
| 4 |
+
|
| 5 |
+
export default defineConfig({
|
| 6 |
+
plugins: [react(), tailwindcss()],
|
| 7 |
+
server: { proxy: { "/api": "http://127.0.0.1:7870", "/demo": "http://127.0.0.1:7870" } },
|
| 8 |
+
build: { outDir: "dist", chunkSizeWarningLimit: 1200 },
|
| 9 |
+
});
|
gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
platform_app/__init__.py
ADDED
|
File without changes
|
platform_app/ai.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interview intelligence: tracks, question generation, answer evaluation, follow-ups, session summaries."""
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
from typing import Dict, List, Optional
|
| 7 |
+
|
| 8 |
+
import librosa
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
import process_interview as pi
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger("evalbot.ai")
|
| 14 |
+
|
| 15 |
+
# --------------------------------------------------------------------------------------
|
| 16 |
+
# Catalog
|
| 17 |
+
# --------------------------------------------------------------------------------------
|
| 18 |
+
TRACKS = [
|
| 19 |
+
# id, English, Arabic, group
|
| 20 |
+
("data_engineering", "Data Engineering", "هندسة البيانات", "tech"),
|
| 21 |
+
("data_analysis", "Data Analysis / BI", "تحليل البيانات", "tech"),
|
| 22 |
+
("data_science", "Data Science", "علم البيانات", "tech"),
|
| 23 |
+
("ai_ml", "AI / Machine Learning", "الذكاء الاصطناعي وتعلم الآلة", "tech"),
|
| 24 |
+
("backend", "Backend Development", "تطوير الـ Backend", "tech"),
|
| 25 |
+
("frontend", "Frontend Development", "تطوير الـ Frontend", "tech"),
|
| 26 |
+
("fullstack", "Full-Stack Development", "تطوير Full-Stack", "tech"),
|
| 27 |
+
("mobile", "Mobile Development (Android / iOS / Flutter)", "تطوير تطبيقات الموبايل", "tech"),
|
| 28 |
+
("devops_cloud", "DevOps & Cloud", "DevOps والحوسبة السحابية", "tech"),
|
| 29 |
+
("cybersecurity", "Cybersecurity", "الأمن السيبراني", "tech"),
|
| 30 |
+
("qa_testing", "Software Testing / QA", "اختبار البرمجيات", "tech"),
|
| 31 |
+
("embedded", "Embedded Systems & IoT", "الأنظمة المدمجة وإنترنت الأشياء", "tech"),
|
| 32 |
+
("networking", "Networking & IT Infrastructure", "الشبكات والبنية التحتية", "tech"),
|
| 33 |
+
("it_support", "IT Support", "الدعم الفني", "tech"),
|
| 34 |
+
("ui_ux", "UI / UX Design", "تصميم واجهات وتجربة المستخدم", "design"),
|
| 35 |
+
("graphic_design", "Graphic Design", "التصميم الجرافيكي", "design"),
|
| 36 |
+
("product_management", "Product Management", "إدارة المنتجات", "business"),
|
| 37 |
+
("project_management", "Project Management", "إدارة المشروعات", "business"),
|
| 38 |
+
("business_analysis", "Business Analysis", "تحليل الأعمال", "business"),
|
| 39 |
+
("marketing", "Marketing & Digital Marketing", "التسويق والتسويق الرقمي", "business"),
|
| 40 |
+
("sales", "Sales & Business Development", "المبيعات وتطوير الأعمال", "business"),
|
| 41 |
+
("hr", "Human Resources", "الموارد البشرية", "business"),
|
| 42 |
+
("finance", "Accounting & Finance", "المحاسبة والمالية", "business"),
|
| 43 |
+
("customer_service", "Customer Service", "خدمة العملاء", "business"),
|
| 44 |
+
("operations", "Operations & Supply Chain", "العمليات وسلاسل الإمداد", "business"),
|
| 45 |
+
("content", "Content Writing & Communication", "كتابة المحتوى والتواصل", "business"),
|
| 46 |
+
("teaching", "Teaching & Training", "التدريس والتدريب", "other"),
|
| 47 |
+
("engineering", "Engineering (Civil / Mechanical / Electrical)", "الهندسة (مدني / ميكانيكا / كهرباء)", "other"),
|
| 48 |
+
("healthcare", "Healthcare", "الرعاية الصحية", "other"),
|
| 49 |
+
("general", "General / Any role", "عام / أي وظيفة", "other"),
|
| 50 |
+
]
|
| 51 |
+
TRACK_NAMES = {t[0]: t[1] for t in TRACKS}
|
| 52 |
+
LEVELS = {"intern": "Internship", "junior": "Junior (0-2 years)", "mid": "Mid-level (2-5 years)",
|
| 53 |
+
"senior": "Senior (5+ years)", "lead": "Lead / Manager"}
|
| 54 |
+
TYPES = {"mixed": "a balanced mix of technical, behavioral and motivation questions",
|
| 55 |
+
"technical": "mostly technical / role-specific knowledge questions, plus one opening question",
|
| 56 |
+
"behavioral": "behavioral questions (STAR) about past experiences, teamwork, conflict, failure, leadership",
|
| 57 |
+
"hr": "HR / fit questions: motivation, career goals, culture fit, strengths and weaknesses, salary expectations",
|
| 58 |
+
"case": "problem-solving / case / scenario questions where the candidate must reason out loud"}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def catalog() -> Dict:
|
| 62 |
+
return {"tracks": [{"id": i, "en": en, "ar": ar, "group": g} for i, en, ar, g in TRACKS],
|
| 63 |
+
"levels": list(LEVELS), "types": list(TYPES)}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def role_name(track: str, custom_role: str = "") -> str:
|
| 67 |
+
return (custom_role or "").strip()[:80] or TRACK_NAMES.get(track, "General / Any role")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# --------------------------------------------------------------------------------------
|
| 71 |
+
# Question generation
|
| 72 |
+
# --------------------------------------------------------------------------------------
|
| 73 |
+
QUESTION_SCHEMA = {
|
| 74 |
+
"type": "object",
|
| 75 |
+
"properties": {"questions": {"type": "array", "items": {"type": "object", "properties": {
|
| 76 |
+
"text": {"type": "string"},
|
| 77 |
+
"kind": {"type": "string", "enum": ["opening", "technical", "behavioral", "situational", "motivation", "closing"]},
|
| 78 |
+
"skill": {"type": "string", "description": "the competency this question tests, 1-3 words"},
|
| 79 |
+
"rubric": {"type": "string", "description": "what a strong answer includes, 1-2 sentences"}},
|
| 80 |
+
"required": ["text", "kind", "skill", "rubric"]}}},
|
| 81 |
+
"required": ["questions"],
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def generate_questions(track: str, level: str, itype: str, count: int = 6, custom_role: str = "",
|
| 86 |
+
cv_text: str = "", jd_text: str = "") -> List[Dict]:
|
| 87 |
+
role = role_name(track, custom_role)
|
| 88 |
+
ctx = ""
|
| 89 |
+
if jd_text.strip():
|
| 90 |
+
ctx += f"\nJob description (tailor questions to it):\n{jd_text.strip()[:4000]}\n"
|
| 91 |
+
if cv_text.strip():
|
| 92 |
+
ctx += f"\nCandidate CV (ask about their real experience where relevant):\n{cv_text.strip()[:4000]}\n"
|
| 93 |
+
prompt = f"""You are an expert interviewer. Write {count} spoken interview questions for this interview:
|
| 94 |
+
- Role: {role}
|
| 95 |
+
- Level: {LEVELS.get(level, level)}
|
| 96 |
+
- Interview style: {TYPES.get(itype, TYPES['mixed'])}
|
| 97 |
+
{ctx}
|
| 98 |
+
Rules:
|
| 99 |
+
- Questions are asked out loud, so keep each one to one or two clear sentences; no code to read, no lists.
|
| 100 |
+
- Calibrate difficulty to the level. Technical questions must be specific to the role (real tools, concepts, trade-offs).
|
| 101 |
+
- Each question must be answerable in about 1-2 minutes of speaking.
|
| 102 |
+
- Start with a short opening question unless the style is purely technical; avoid near-duplicates.
|
| 103 |
+
- Write the questions in English.
|
| 104 |
+
"""
|
| 105 |
+
res = pi._gemini_json(prompt, QUESTION_SCHEMA, temperature=0.8)
|
| 106 |
+
qs = [q for q in (res or {}).get("questions", []) if q.get("text", "").strip()][:count]
|
| 107 |
+
if not qs: # offline fallback: built-in bank
|
| 108 |
+
bank = pi.QUESTION_BANK["General"] + pi.QUESTION_BANK["Behavioral"]
|
| 109 |
+
qs = [{"text": t, "kind": "behavioral", "skill": "communication", "rubric": ""} for t in bank[:count]]
|
| 110 |
+
return qs
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# --------------------------------------------------------------------------------------
|
| 114 |
+
# Answer evaluation (one recorded answer)
|
| 115 |
+
# --------------------------------------------------------------------------------------
|
| 116 |
+
ANSWER_SCHEMA = {
|
| 117 |
+
"type": "object",
|
| 118 |
+
"properties": {
|
| 119 |
+
"score": {"type": "integer", "description": "0-10"},
|
| 120 |
+
"relevance": {"type": "string", "enum": ["on_topic", "partially", "off_topic"]},
|
| 121 |
+
"summary": {"type": "string"},
|
| 122 |
+
"strengths": {"type": "array", "items": {"type": "string"}},
|
| 123 |
+
"improvements": {"type": "array", "items": {"type": "string"}},
|
| 124 |
+
"delivery_tip": {"type": "string"},
|
| 125 |
+
"improved_answer": {"type": "string"},
|
| 126 |
+
"followup_question": {"type": "string", "description": "a natural probing follow-up, or empty string if not needed"},
|
| 127 |
+
},
|
| 128 |
+
"required": ["score", "relevance", "summary", "strengths", "improvements", "delivery_tip", "improved_answer",
|
| 129 |
+
"followup_question"],
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def transcribe_answer(audio_bytes: bytes, suffix: str = ".webm") -> Dict:
|
| 134 |
+
"""Transcribe one answer and compute its voice metrics. Returns transcript, words, duration, voice."""
|
| 135 |
+
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
|
| 136 |
+
tmp.write(audio_bytes)
|
| 137 |
+
src = tmp.name
|
| 138 |
+
wav = None
|
| 139 |
+
try:
|
| 140 |
+
wav = pi.convert_to_wav(src)
|
| 141 |
+
y, sr = librosa.load(wav, sr=16000)
|
| 142 |
+
if len(y) < sr:
|
| 143 |
+
return {"transcript": "", "duration_s": len(y) / sr, "voice": {"error": "too short"}, "silent": True}
|
| 144 |
+
tr = pi.transcribe(wav, speakers_expected=None, diarize=False)
|
| 145 |
+
words = tr.get("words") or []
|
| 146 |
+
text = (tr.get("text") or "").strip()
|
| 147 |
+
if not words or not text:
|
| 148 |
+
return {"transcript": "", "duration_s": len(y) / sr, "voice": {"error": "no speech"}, "silent": True}
|
| 149 |
+
start, end = words[0]["start"], words[-1]["end"]
|
| 150 |
+
utt = {"role": "Interviewee", "start": start, "end": end, "text": text,
|
| 151 |
+
"prosodic_features": pi.extract_prosodic_features(y, sr, start, end)}
|
| 152 |
+
voice = pi.analyze_interviewee_voice(y, sr, [utt])
|
| 153 |
+
return {"transcript": text, "duration_s": round((end - start) / 1000, 1), "voice": voice, "silent": False,
|
| 154 |
+
"speech_start_ms": start, "speech_end_ms": end}
|
| 155 |
+
finally:
|
| 156 |
+
for p in (src, wav):
|
| 157 |
+
if p and os.path.exists(p):
|
| 158 |
+
os.remove(p)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def evaluate_answer(question: Dict, transcript: str, voice: Dict, role: str, level: str, lang: str,
|
| 162 |
+
allow_followup: bool) -> Dict:
|
| 163 |
+
metrics = {k: voice.get(k) for k in ("speaking_rate", "filler_ratio", "interpretation")} if "error" not in voice else {}
|
| 164 |
+
prompt = f"""You are a fair, encouraging but honest interview coach. A candidate for "{role}" ({LEVELS.get(level, level)})
|
| 165 |
+
answered this interview question out loud. Evaluate the answer.
|
| 166 |
+
|
| 167 |
+
Question: {question['text']}
|
| 168 |
+
What a strong answer includes: {question.get('rubric') or 'n/a'}
|
| 169 |
+
Answer (speech-to-text transcript): {transcript}
|
| 170 |
+
Voice metrics: {json.dumps(metrics)}
|
| 171 |
+
|
| 172 |
+
- score 0-10 for content quality: relevance, correctness, depth, structure (STAR where it fits), specificity.
|
| 173 |
+
- 2-4 strengths and 2-4 improvements, one sentence each, concrete and tied to what they said.
|
| 174 |
+
- delivery_tip: one tip from the voice metrics.
|
| 175 |
+
- improved_answer: a stronger version (4-6 sentences, first person) that keeps the candidate's own facts and uses
|
| 176 |
+
placeholders like [number] for missing details. Keep it in English.
|
| 177 |
+
- followup_question: {"one short probing follow-up a real interviewer would ask about something specific the candidate said (in English), or an empty string if the answer was complete" if allow_followup else "always an empty string"}.
|
| 178 |
+
{pi._language_rule(lang)}"""
|
| 179 |
+
res = pi._gemini_json(prompt, ANSWER_SCHEMA)
|
| 180 |
+
if not res:
|
| 181 |
+
return {"score": None, "relevance": None, "summary": "", "strengths": [], "improvements": [],
|
| 182 |
+
"delivery_tip": "", "improved_answer": "", "followup_question": "", "ai_generated": False}
|
| 183 |
+
res["score"] = int(max(0, min(10, res.get("score", 0))))
|
| 184 |
+
res["ai_generated"] = True
|
| 185 |
+
if not allow_followup:
|
| 186 |
+
res["followup_question"] = ""
|
| 187 |
+
return res
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# --------------------------------------------------------------------------------------
|
| 191 |
+
# Session summary
|
| 192 |
+
# --------------------------------------------------------------------------------------
|
| 193 |
+
SUMMARY_SCHEMA = {
|
| 194 |
+
"type": "object",
|
| 195 |
+
"properties": {
|
| 196 |
+
"headline": {"type": "string", "description": "one-sentence overall verdict"},
|
| 197 |
+
"executive_summary": {"type": "array", "items": {"type": "string"}},
|
| 198 |
+
"strengths": {"type": "array", "items": {"type": "object", "properties": {
|
| 199 |
+
"competency": {"type": "string"}, "explanation": {"type": "string"}, "evidence": {"type": "string"}},
|
| 200 |
+
"required": ["competency", "explanation", "evidence"]}},
|
| 201 |
+
"weaknesses": {"type": "array", "items": {"type": "object", "properties": {
|
| 202 |
+
"area": {"type": "string"}, "feedback": {"type": "string"}}, "required": ["area", "feedback"]}},
|
| 203 |
+
"role_fit": {"type": "array", "items": {"type": "string"}},
|
| 204 |
+
"recommendations": {"type": "array", "items": {"type": "object", "properties": {
|
| 205 |
+
"category": {"type": "string", "enum": ["Communication Skills", "Content Delivery", "Professional Presentation"]},
|
| 206 |
+
"recommendation": {"type": "string"}, "how_to": {"type": "string"}},
|
| 207 |
+
"required": ["category", "recommendation", "how_to"]}},
|
| 208 |
+
"learning_plan": {"type": "array", "items": {"type": "object", "properties": {
|
| 209 |
+
"topic": {"type": "string"}, "why": {"type": "string"}, "how": {"type": "string"}},
|
| 210 |
+
"required": ["topic", "why", "how"]}},
|
| 211 |
+
"next_steps": {"type": "array", "items": {"type": "string"}},
|
| 212 |
+
"hiring_signal": {"type": "string", "enum": ["strong_yes", "yes", "maybe", "no"]},
|
| 213 |
+
},
|
| 214 |
+
"required": ["headline", "executive_summary", "strengths", "weaknesses", "role_fit", "recommendations",
|
| 215 |
+
"learning_plan", "next_steps", "hiring_signal"],
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def summarize_session(role: str, level: str, lang: str, answers: List[Dict], voice: Dict,
|
| 220 |
+
calibrated: Optional[Dict], for_recruiter: bool) -> Optional[Dict]:
|
| 221 |
+
qa = "\n\n".join(f"[{i + 1}] Q: {a['question']}\nA: {a.get('transcript') or '(no answer)'}\n"
|
| 222 |
+
f"Score: {a.get('score')}/10" for i, a in enumerate(answers))
|
| 223 |
+
cal = ""
|
| 224 |
+
if calibrated:
|
| 225 |
+
cal = "Human-calibrated delivery scores (percentile vs 138 rated interviews): " + ", ".join(
|
| 226 |
+
f"{t['trait']} {t['percentile']}th" for t in calibrated["traits"])
|
| 227 |
+
vm = {k: voice.get(k) for k in ("speaking_rate", "filler_ratio", "interpretation")} if voice and "error" not in voice else {}
|
| 228 |
+
audience = ("The report is read by the hiring team." if for_recruiter
|
| 229 |
+
else "The report is read by the candidate, who wants to improve; next_steps are their practice steps.")
|
| 230 |
+
prompt = f"""You are EvalBot, a senior interviewer and career coach. Write the final evaluation of this interview.
|
| 231 |
+
Role: {role} ({LEVELS.get(level, level)}). {audience}
|
| 232 |
+
|
| 233 |
+
- Base every point on the answers below (quote briefly as evidence) and the metrics. Do not invent facts.
|
| 234 |
+
- 3 bullets executive summary, 3-6 strengths, 3-6 weaknesses, 3 role-fit bullets, exactly 3 recommendations
|
| 235 |
+
(one per category), a 3-5 item learning_plan of topics to study for this role, and 3-5 next_steps.
|
| 236 |
+
- hiring_signal: your recommendation for a {LEVELS.get(level, level)} {role} position.
|
| 237 |
+
{pi._language_rule(lang)}
|
| 238 |
+
Voice metrics: {json.dumps(vm)}
|
| 239 |
+
{cal}
|
| 240 |
+
|
| 241 |
+
Interview:
|
| 242 |
+
{qa}
|
| 243 |
+
"""
|
| 244 |
+
return pi._gemini_json(prompt, SUMMARY_SCHEMA)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# --------------------------------------------------------------------------------------
|
| 248 |
+
# Session-level audio features for calibrated scores
|
| 249 |
+
# --------------------------------------------------------------------------------------
|
| 250 |
+
def session_audio(answer_audio: List[bytes]) -> Optional[tuple]:
|
| 251 |
+
"""Concatenate answer recordings into one 16 kHz signal with candidate utterances."""
|
| 252 |
+
ys, utts, t = [], [], 0
|
| 253 |
+
for blob in answer_audio:
|
| 254 |
+
with tempfile.NamedTemporaryFile(suffix=".audio", delete=False) as tmp:
|
| 255 |
+
tmp.write(blob)
|
| 256 |
+
src = tmp.name
|
| 257 |
+
try:
|
| 258 |
+
wav = pi.convert_to_wav(src)
|
| 259 |
+
y, sr = librosa.load(wav, sr=16000)
|
| 260 |
+
os.remove(wav)
|
| 261 |
+
finally:
|
| 262 |
+
os.remove(src)
|
| 263 |
+
iv = librosa.effects.split(y, top_db=35)
|
| 264 |
+
if len(iv):
|
| 265 |
+
y = y[iv[0][0]: iv[-1][1]] # trim leading/trailing silence
|
| 266 |
+
if len(y) < 16000:
|
| 267 |
+
continue
|
| 268 |
+
utts.append({"role": "Interviewee", "start": t, "end": t + int(len(y) / 16), "text": ""})
|
| 269 |
+
ys.append(y)
|
| 270 |
+
gap = np.zeros(8000, dtype=y.dtype)
|
| 271 |
+
ys.append(gap)
|
| 272 |
+
t += int(len(y) / 16) + 500
|
| 273 |
+
if not ys:
|
| 274 |
+
return None
|
| 275 |
+
return np.concatenate(ys), 16000, utts
|
platform_app/core.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared infrastructure for the EvalBot platform: settings, database, auth, file storage."""
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
from typing import Any, Dict, List, Optional
|
| 8 |
+
|
| 9 |
+
import httpx
|
| 10 |
+
from fastapi import Depends, Header, HTTPException
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger("evalbot.platform")
|
| 13 |
+
|
| 14 |
+
# --------------------------------------------------------------------------------------
|
| 15 |
+
# Settings (all from environment / Space secrets)
|
| 16 |
+
# --------------------------------------------------------------------------------------
|
| 17 |
+
DATABASE_URL = os.getenv("DATABASE_URL", "")
|
| 18 |
+
SUPABASE_URL = os.getenv("SUPABASE_URL", "").rstrip("/")
|
| 19 |
+
SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY", "")
|
| 20 |
+
SUPABASE_SERVICE_ROLE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
|
| 21 |
+
STORAGE_BUCKET = os.getenv("STORAGE_BUCKET", "evalbot")
|
| 22 |
+
DEV_AUTH = os.getenv("EVALBOT_DEV_AUTH", "") == "1" # local testing only: accepts "dev:<uuid>:<email>"
|
| 23 |
+
LOCAL_STORAGE_DIR = os.getenv("EVALBOT_LOCAL_STORAGE", "./platform_storage")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def enabled() -> bool:
|
| 27 |
+
return bool(DATABASE_URL)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def public_config() -> Dict[str, Any]:
|
| 31 |
+
return {"enabled": enabled(), "supabase_url": SUPABASE_URL, "supabase_anon_key": SUPABASE_ANON_KEY,
|
| 32 |
+
"dev_auth": DEV_AUTH}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# --------------------------------------------------------------------------------------
|
| 36 |
+
# Database
|
| 37 |
+
# --------------------------------------------------------------------------------------
|
| 38 |
+
_pool = None
|
| 39 |
+
_pool_lock = threading.Lock()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def pool():
|
| 43 |
+
global _pool
|
| 44 |
+
if _pool is None:
|
| 45 |
+
with _pool_lock:
|
| 46 |
+
if _pool is None:
|
| 47 |
+
from psycopg.rows import dict_row
|
| 48 |
+
from psycopg_pool import ConnectionPool
|
| 49 |
+
|
| 50 |
+
_pool = ConnectionPool(DATABASE_URL, min_size=1, max_size=5, open=True,
|
| 51 |
+
kwargs={"row_factory": dict_row, "autocommit": True,
|
| 52 |
+
"prepare_threshold": None}) # pgbouncer-compatible
|
| 53 |
+
return _pool
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def init_db() -> None:
|
| 57 |
+
if not enabled():
|
| 58 |
+
logger.warning("DATABASE_URL not set: platform features are disabled")
|
| 59 |
+
return
|
| 60 |
+
sql = open(os.path.join(os.path.dirname(__file__), "schema.sql"), encoding="utf-8").read()
|
| 61 |
+
with pool().connection() as conn:
|
| 62 |
+
conn.execute(sql)
|
| 63 |
+
logger.info("Database schema ready")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _adapt(params):
|
| 67 |
+
from psycopg.types.json import Jsonb
|
| 68 |
+
|
| 69 |
+
if params is None:
|
| 70 |
+
return None
|
| 71 |
+
if isinstance(params, dict):
|
| 72 |
+
return {k: Jsonb(v) if isinstance(v, (dict, list)) else v for k, v in params.items()}
|
| 73 |
+
return [Jsonb(v) if isinstance(v, (dict, list)) else v for v in params]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def q(sql: str, params=None) -> List[Dict]:
|
| 77 |
+
with pool().connection() as conn:
|
| 78 |
+
cur = conn.execute(sql, _adapt(params))
|
| 79 |
+
return cur.fetchall() if cur.description else []
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def q1(sql: str, params=None) -> Optional[Dict]:
|
| 83 |
+
rows = q(sql, params)
|
| 84 |
+
return rows[0] if rows else None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# --------------------------------------------------------------------------------------
|
| 88 |
+
# Auth (Supabase access tokens)
|
| 89 |
+
# --------------------------------------------------------------------------------------
|
| 90 |
+
_token_cache: Dict[str, tuple] = {}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _verify_token(token: str) -> Dict:
|
| 94 |
+
hit = _token_cache.get(token)
|
| 95 |
+
if hit and hit[1] > time.time():
|
| 96 |
+
return hit[0]
|
| 97 |
+
if DEV_AUTH and token.startswith("dev:"):
|
| 98 |
+
_, uid, email = token.split(":", 2)
|
| 99 |
+
user = {"id": uid, "email": email}
|
| 100 |
+
else:
|
| 101 |
+
if not SUPABASE_URL:
|
| 102 |
+
raise HTTPException(500, "Authentication is not configured")
|
| 103 |
+
r = httpx.get(f"{SUPABASE_URL}/auth/v1/user", timeout=10,
|
| 104 |
+
headers={"Authorization": f"Bearer {token}", "apikey": SUPABASE_ANON_KEY})
|
| 105 |
+
if r.status_code != 200:
|
| 106 |
+
raise HTTPException(401, "Your session has expired. Please sign in again.")
|
| 107 |
+
d = r.json()
|
| 108 |
+
user = {"id": d["id"], "email": d.get("email"),
|
| 109 |
+
"name": (d.get("user_metadata") or {}).get("full_name") or (d.get("user_metadata") or {}).get("name")}
|
| 110 |
+
_token_cache[token] = (user, time.time() + 300)
|
| 111 |
+
return user
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def current_user(authorization: str = Header(default="")) -> Dict:
|
| 115 |
+
if not enabled():
|
| 116 |
+
raise HTTPException(503, "The platform is not configured yet")
|
| 117 |
+
if not authorization.lower().startswith("bearer "):
|
| 118 |
+
raise HTTPException(401, "Please sign in")
|
| 119 |
+
user = _verify_token(authorization.split(" ", 1)[1].strip())
|
| 120 |
+
prof = q1("select * from profiles where id = %s", [user["id"]])
|
| 121 |
+
if prof is None:
|
| 122 |
+
prof = q1("insert into profiles (id, email, full_name) values (%s, %s, %s) "
|
| 123 |
+
"on conflict (id) do update set email = excluded.email returning *",
|
| 124 |
+
[user["id"], user.get("email"), user.get("name")])
|
| 125 |
+
return prof
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def recruiter(user: Dict = Depends(current_user)) -> Dict:
|
| 129 |
+
if user["role"] != "recruiter" or not user.get("company_id"):
|
| 130 |
+
raise HTTPException(403, "This page is for company accounts")
|
| 131 |
+
return user
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# --------------------------------------------------------------------------------------
|
| 135 |
+
# File storage (Supabase Storage, or a local folder for development)
|
| 136 |
+
# --------------------------------------------------------------------------------------
|
| 137 |
+
def _storage_headers(content_type: Optional[str] = None) -> Dict[str, str]:
|
| 138 |
+
h = {"Authorization": f"Bearer {SUPABASE_SERVICE_ROLE_KEY}", "apikey": SUPABASE_SERVICE_ROLE_KEY}
|
| 139 |
+
if content_type:
|
| 140 |
+
h["Content-Type"] = content_type
|
| 141 |
+
return h
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _use_supabase_storage() -> bool:
|
| 145 |
+
return bool(SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def ensure_bucket() -> None:
|
| 149 |
+
if not _use_supabase_storage():
|
| 150 |
+
os.makedirs(LOCAL_STORAGE_DIR, exist_ok=True)
|
| 151 |
+
return
|
| 152 |
+
r = httpx.get(f"{SUPABASE_URL}/storage/v1/bucket/{STORAGE_BUCKET}", headers=_storage_headers(), timeout=15)
|
| 153 |
+
if r.status_code != 200:
|
| 154 |
+
r = httpx.post(f"{SUPABASE_URL}/storage/v1/bucket", headers=_storage_headers("application/json"),
|
| 155 |
+
json={"id": STORAGE_BUCKET, "name": STORAGE_BUCKET, "public": False}, timeout=15)
|
| 156 |
+
logger.info("Created storage bucket %s: %s", STORAGE_BUCKET, r.status_code)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def put_file(path: str, data: bytes, content_type: str) -> str:
|
| 160 |
+
if not _use_supabase_storage():
|
| 161 |
+
full = os.path.join(LOCAL_STORAGE_DIR, path)
|
| 162 |
+
os.makedirs(os.path.dirname(full), exist_ok=True)
|
| 163 |
+
with open(full, "wb") as f:
|
| 164 |
+
f.write(data)
|
| 165 |
+
return path
|
| 166 |
+
r = httpx.post(f"{SUPABASE_URL}/storage/v1/object/{STORAGE_BUCKET}/{path}", content=data, timeout=120,
|
| 167 |
+
headers={**_storage_headers(content_type), "x-upsert": "true"})
|
| 168 |
+
if r.status_code >= 300:
|
| 169 |
+
raise RuntimeError(f"Storage upload failed: {r.status_code} {r.text[:200]}")
|
| 170 |
+
return path
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def get_file(path: str) -> bytes:
|
| 174 |
+
if not _use_supabase_storage():
|
| 175 |
+
with open(os.path.join(LOCAL_STORAGE_DIR, path), "rb") as f:
|
| 176 |
+
return f.read()
|
| 177 |
+
r = httpx.get(f"{SUPABASE_URL}/storage/v1/object/{STORAGE_BUCKET}/{path}", headers=_storage_headers(), timeout=120)
|
| 178 |
+
if r.status_code != 200:
|
| 179 |
+
raise RuntimeError(f"Storage download failed: {r.status_code}")
|
| 180 |
+
return r.content
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def dumps(obj) -> str:
|
| 184 |
+
return json.dumps(obj, ensure_ascii=False, default=str)
|
platform_app/routes.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EvalBot platform API: candidates, mock interviews, companies, jobs and reviews."""
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
import time
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
+
from typing import Dict, List, Optional
|
| 9 |
+
|
| 10 |
+
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
| 11 |
+
from fastapi.responses import Response
|
| 12 |
+
from pydantic import BaseModel, Field
|
| 13 |
+
|
| 14 |
+
import calibration as cal
|
| 15 |
+
import process_interview as pi
|
| 16 |
+
from . import ai
|
| 17 |
+
from .core import current_user, dumps, get_file, public_config, put_file, q, q1, recruiter
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger("evalbot.routes")
|
| 20 |
+
router = APIRouter(prefix="/api")
|
| 21 |
+
_workers = ThreadPoolExecutor(max_workers=int(os.getenv("PLATFORM_WORKERS", "2")))
|
| 22 |
+
MAX_FOLLOWUPS = 2
|
| 23 |
+
MAX_AUDIO_MB = 25
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# --------------------------------------------------------------------------------------
|
| 27 |
+
# Public
|
| 28 |
+
# --------------------------------------------------------------------------------------
|
| 29 |
+
@router.get("/config")
|
| 30 |
+
def config():
|
| 31 |
+
return {**public_config(), "calibrated_model": cal.available()}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@router.get("/model-card")
|
| 35 |
+
def model_card(lang: str = "en"):
|
| 36 |
+
return cal.model_card("ar" if lang == "ar" else "en") or {"traits": []}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@router.get("/catalog")
|
| 40 |
+
def catalog():
|
| 41 |
+
return ai.catalog()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@router.get("/public/jobs/{token}")
|
| 45 |
+
def public_job(token: str):
|
| 46 |
+
j = q1("select j.id, j.title, j.track, j.level, j.description, j.answer_seconds, j.status, "
|
| 47 |
+
"jsonb_array_length(j.questions) as question_count, c.name as company, c.website "
|
| 48 |
+
"from jobs j join companies c on c.id = j.company_id where j.share_token = %s", [token])
|
| 49 |
+
if not j:
|
| 50 |
+
raise HTTPException(404, "This job link is not valid")
|
| 51 |
+
return j
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# --------------------------------------------------------------------------------------
|
| 55 |
+
# Profile & company
|
| 56 |
+
# --------------------------------------------------------------------------------------
|
| 57 |
+
class ProfileIn(BaseModel):
|
| 58 |
+
full_name: Optional[str] = None
|
| 59 |
+
headline: Optional[str] = None
|
| 60 |
+
target_track: Optional[str] = None
|
| 61 |
+
locale: Optional[str] = None
|
| 62 |
+
role: Optional[str] = None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@router.get("/me")
|
| 66 |
+
def me(user: Dict = Depends(current_user)):
|
| 67 |
+
company = q1("select * from companies where id = %s", [user["company_id"]]) if user.get("company_id") else None
|
| 68 |
+
return {**user, "company": company}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@router.patch("/me")
|
| 72 |
+
def update_me(body: ProfileIn, user: Dict = Depends(current_user)):
|
| 73 |
+
fields = {k: v for k, v in body.model_dump().items() if v is not None}
|
| 74 |
+
if "role" in fields and fields["role"] not in ("candidate", "recruiter"):
|
| 75 |
+
raise HTTPException(400, "Invalid role")
|
| 76 |
+
if fields:
|
| 77 |
+
sets = ", ".join(f"{k} = %({k})s" for k in fields)
|
| 78 |
+
q(f"update profiles set {sets} where id = %(id)s", {**fields, "id": user["id"]})
|
| 79 |
+
return me(q1("select * from profiles where id = %s", [user["id"]]))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class CompanyIn(BaseModel):
|
| 83 |
+
name: str = Field(min_length=2, max_length=120)
|
| 84 |
+
website: Optional[str] = None
|
| 85 |
+
about: Optional[str] = None
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@router.post("/companies")
|
| 89 |
+
def create_company(body: CompanyIn, user: Dict = Depends(current_user)):
|
| 90 |
+
if user.get("company_id"):
|
| 91 |
+
c = q1("update companies set name=%s, website=%s, about=%s where id=%s returning *",
|
| 92 |
+
[body.name, body.website, body.about, user["company_id"]])
|
| 93 |
+
else:
|
| 94 |
+
c = q1("insert into companies (name, website, about, created_by) values (%s, %s, %s, %s) returning *",
|
| 95 |
+
[body.name, body.website, body.about, user["id"]])
|
| 96 |
+
q("update profiles set role='recruiter', company_id=%s where id=%s", [c["id"], user["id"]])
|
| 97 |
+
return c
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# --------------------------------------------------------------------------------------
|
| 101 |
+
# Question generation
|
| 102 |
+
# --------------------------------------------------------------------------------------
|
| 103 |
+
class QuestionsIn(BaseModel):
|
| 104 |
+
track: str = "general"
|
| 105 |
+
level: str = "junior"
|
| 106 |
+
interview_type: str = "mixed"
|
| 107 |
+
count: int = Field(6, ge=3, le=12)
|
| 108 |
+
custom_role: str = ""
|
| 109 |
+
cv_text: str = ""
|
| 110 |
+
jd_text: str = ""
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@router.post("/questions/generate")
|
| 114 |
+
def generate(body: QuestionsIn, user: Dict = Depends(current_user)):
|
| 115 |
+
return {"questions": ai.generate_questions(body.track, body.level, body.interview_type, body.count,
|
| 116 |
+
body.custom_role, body.cv_text, body.jd_text)}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# --------------------------------------------------------------------------------------
|
| 120 |
+
# Sessions (mock interviews and job interviews)
|
| 121 |
+
# --------------------------------------------------------------------------------------
|
| 122 |
+
class SessionIn(QuestionsIn):
|
| 123 |
+
language: str = "en"
|
| 124 |
+
questions: Optional[List[Dict]] = None
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _can_view(session: Dict, user: Dict) -> bool:
|
| 128 |
+
if session["user_id"] == user["id"]:
|
| 129 |
+
return True
|
| 130 |
+
if session.get("job_id") and user["role"] == "recruiter":
|
| 131 |
+
return bool(q1("select 1 from jobs where id=%s and company_id=%s", [session["job_id"], user.get("company_id")]))
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _session(sid: str, user: Dict, owner_only: bool = False) -> Dict:
|
| 136 |
+
s = q1("select * from sessions where id = %s", [sid])
|
| 137 |
+
if not s or (owner_only and s["user_id"] != user["id"]) or not _can_view(s, user):
|
| 138 |
+
raise HTTPException(404, "Interview not found")
|
| 139 |
+
return s
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@router.post("/sessions")
|
| 143 |
+
def create_session(body: SessionIn, user: Dict = Depends(current_user)):
|
| 144 |
+
plan = body.questions or ai.generate_questions(body.track, body.level, body.interview_type, body.count,
|
| 145 |
+
body.custom_role, body.cv_text, body.jd_text)
|
| 146 |
+
plan = [{"text": p["text"].strip()[:500], "kind": p.get("kind", "custom"), "skill": p.get("skill", ""),
|
| 147 |
+
"rubric": p.get("rubric", "")} for p in plan if p.get("text", "").strip()]
|
| 148 |
+
ctx = {"plan": plan, "role": ai.role_name(body.track, body.custom_role), "answer_seconds": 120,
|
| 149 |
+
"has_cv": bool(body.cv_text.strip()), "has_jd": bool(body.jd_text.strip()), "followups": 0}
|
| 150 |
+
s = q1("insert into sessions (user_id, mode, track, level, interview_type, language, context) "
|
| 151 |
+
"values (%s, 'mock', %s, %s, %s, %s, %s) returning *",
|
| 152 |
+
[user["id"], body.track, body.level, body.interview_type, body.language if body.language in ("en", "ar") else "en", ctx])
|
| 153 |
+
return s
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class ApplyIn(BaseModel):
|
| 157 |
+
language: str = "en"
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@router.post("/jobs/apply/{token}")
|
| 161 |
+
def apply_job(token: str, body: ApplyIn, user: Dict = Depends(current_user)):
|
| 162 |
+
j = q1("select * from jobs where share_token = %s", [token])
|
| 163 |
+
if not j or j["status"] != "open":
|
| 164 |
+
raise HTTPException(404, "This job is not accepting interviews")
|
| 165 |
+
existing = q1("select * from sessions where job_id=%s and user_id=%s order by created_at desc limit 1", [j["id"], user["id"]])
|
| 166 |
+
if existing:
|
| 167 |
+
return existing
|
| 168 |
+
plan = [{"text": x["text"], "kind": x.get("kind", "custom"), "skill": x.get("skill", ""),
|
| 169 |
+
"rubric": x.get("rubric", "")} for x in j["questions"]]
|
| 170 |
+
ctx = {"plan": plan, "role": j["title"], "answer_seconds": j["answer_seconds"], "followups": 0,
|
| 171 |
+
"job_title": j["title"], "no_followups": True}
|
| 172 |
+
return q1("insert into sessions (user_id, job_id, mode, track, level, interview_type, language, context) "
|
| 173 |
+
"values (%s, %s, 'job', %s, %s, 'job', %s, %s) returning *",
|
| 174 |
+
[user["id"], j["id"], j["track"], j["level"], body.language if body.language in ("en", "ar") else "en", ctx])
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@router.get("/sessions")
|
| 178 |
+
def list_sessions(user: Dict = Depends(current_user)):
|
| 179 |
+
return q("select s.id, s.mode, s.track, s.level, s.interview_type, s.status, s.overall_score, s.created_at, "
|
| 180 |
+
"s.completed_at, s.context->>'role' as role, j.title as job_title, "
|
| 181 |
+
"(select count(*) from answers a where a.session_id = s.id) as answered, "
|
| 182 |
+
"jsonb_array_length(s.context->'plan') as planned "
|
| 183 |
+
"from sessions s left join jobs j on j.id = s.job_id where s.user_id = %s order by s.created_at desc limit 100",
|
| 184 |
+
[user["id"]])
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@router.get("/sessions/{sid}")
|
| 188 |
+
def get_session(sid: str, user: Dict = Depends(current_user)):
|
| 189 |
+
s = _session(sid, user)
|
| 190 |
+
s["answers"] = q("select id, idx, question, kind, is_followup, duration_s, transcript, voice, presence, feedback, "
|
| 191 |
+
"score, audio_path is not null as has_audio, created_at from answers where session_id=%s order by idx", [sid])
|
| 192 |
+
if s.get("job_id"):
|
| 193 |
+
s["job"] = q1("select j.title, c.name as company from jobs j join companies c on c.id=j.company_id where j.id=%s", [s["job_id"]])
|
| 194 |
+
if s["user_id"] != user["id"]:
|
| 195 |
+
s["candidate"] = q1("select full_name, email, headline from profiles where id=%s", [s["user_id"]])
|
| 196 |
+
return s
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@router.get("/sessions/{sid}/next")
|
| 200 |
+
def next_question(sid: str, user: Dict = Depends(current_user)):
|
| 201 |
+
s = _session(sid, user, owner_only=True)
|
| 202 |
+
plan = s["context"]["plan"]
|
| 203 |
+
done = {r["idx"] for r in q("select idx from answers where session_id=%s", [sid])}
|
| 204 |
+
for i, p in enumerate(plan):
|
| 205 |
+
if i not in done:
|
| 206 |
+
return {"done": False, "idx": i, "total": len(plan), "question": p["text"], "kind": p.get("kind"),
|
| 207 |
+
"is_followup": p.get("is_followup", False), "answer_seconds": s["context"].get("answer_seconds", 120)}
|
| 208 |
+
return {"done": True, "total": len(plan)}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _process_answer(sid: str, idx: int, blob: bytes, suffix: str):
|
| 212 |
+
try:
|
| 213 |
+
s = q1("select * from sessions where id=%s", [sid])
|
| 214 |
+
plan = s["context"]["plan"]
|
| 215 |
+
question = plan[idx]
|
| 216 |
+
tr = ai.transcribe_answer(blob, suffix)
|
| 217 |
+
if tr.get("silent"):
|
| 218 |
+
fb = {"score": 0, "relevance": "off_topic", "summary": "No answer was detected in this recording.",
|
| 219 |
+
"strengths": [], "improvements": ["Make sure your microphone is working and answer out loud."],
|
| 220 |
+
"delivery_tip": "", "improved_answer": "", "followup_question": "", "ai_generated": False}
|
| 221 |
+
else:
|
| 222 |
+
ctx = s["context"]
|
| 223 |
+
allow = (not ctx.get("no_followups") and ctx.get("followups", 0) < MAX_FOLLOWUPS
|
| 224 |
+
and not question.get("is_followup"))
|
| 225 |
+
fb = ai.evaluate_answer(question, tr["transcript"], tr["voice"], ctx.get("role", ""), s["level"] or "junior",
|
| 226 |
+
s["language"], allow)
|
| 227 |
+
fb["skill"] = question.get("skill", "")
|
| 228 |
+
q("update answers set transcript=%s, duration_s=%s, voice=%s, feedback=%s, score=%s where session_id=%s and idx=%s",
|
| 229 |
+
[tr.get("transcript"), tr.get("duration_s"), tr.get("voice"), fb, fb.get("score"), sid, idx])
|
| 230 |
+
fu = (fb.get("followup_question") or "").strip()
|
| 231 |
+
if fu:
|
| 232 |
+
# append the follow-up to the plan (atomic jsonb append, guarded by the follow-up counter)
|
| 233 |
+
q("update sessions set context = jsonb_set(jsonb_set(context, '{plan}', (context->'plan') || %s::jsonb), "
|
| 234 |
+
"'{followups}', to_jsonb(coalesce((context->>'followups')::int, 0) + 1)) "
|
| 235 |
+
"where id=%s and status='in_progress' and coalesce((context->>'followups')::int, 0) < %s",
|
| 236 |
+
[dumps([{"text": fu, "kind": "followup", "skill": question.get("skill", ""), "rubric": "",
|
| 237 |
+
"is_followup": True, "followup_of": idx}]), sid, MAX_FOLLOWUPS])
|
| 238 |
+
except Exception as e:
|
| 239 |
+
logger.exception("Answer processing failed")
|
| 240 |
+
q("update answers set feedback=%s where session_id=%s and idx=%s",
|
| 241 |
+
[{"error": str(e)[:300], "ai_generated": False}, sid, idx])
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@router.post("/sessions/{sid}/answers")
|
| 245 |
+
def upload_answer(sid: str, idx: int = Form(...), file: UploadFile = File(...), presence: str = Form(""),
|
| 246 |
+
user: Dict = Depends(current_user)):
|
| 247 |
+
s = _session(sid, user, owner_only=True)
|
| 248 |
+
if s["status"] != "in_progress":
|
| 249 |
+
raise HTTPException(400, "This interview is already finished")
|
| 250 |
+
plan = s["context"]["plan"]
|
| 251 |
+
if idx < 0 or idx >= len(plan):
|
| 252 |
+
raise HTTPException(400, "Unknown question")
|
| 253 |
+
blob = file.file.read(MAX_AUDIO_MB * 1024 * 1024 + 1)
|
| 254 |
+
if len(blob) > MAX_AUDIO_MB * 1024 * 1024:
|
| 255 |
+
raise HTTPException(413, "Recording is too large")
|
| 256 |
+
suffix = os.path.splitext(file.filename or "")[1].lower() or ".webm"
|
| 257 |
+
path = put_file(f"sessions/{sid}/answer_{idx}{suffix}", blob, file.content_type or "audio/webm")
|
| 258 |
+
try:
|
| 259 |
+
pres = json.loads(presence) if presence else None
|
| 260 |
+
except ValueError:
|
| 261 |
+
pres = None
|
| 262 |
+
q("insert into answers (session_id, idx, question, kind, is_followup, audio_path, presence) values (%s,%s,%s,%s,%s,%s,%s) "
|
| 263 |
+
"on conflict (session_id, idx) do update set audio_path=excluded.audio_path, presence=excluded.presence, "
|
| 264 |
+
"transcript=null, feedback=null, score=null",
|
| 265 |
+
[sid, idx, plan[idx]["text"], plan[idx].get("kind"), bool(plan[idx].get("is_followup")), path, pres])
|
| 266 |
+
_workers.submit(_process_answer, sid, idx, blob, suffix)
|
| 267 |
+
return {"ok": True, "idx": idx}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@router.get("/sessions/{sid}/answers/{idx}/audio")
|
| 271 |
+
def answer_audio(sid: str, idx: int, user: Dict = Depends(current_user)):
|
| 272 |
+
_session(sid, user)
|
| 273 |
+
a = q1("select audio_path from answers where session_id=%s and idx=%s", [sid, idx])
|
| 274 |
+
if not a or not a["audio_path"]:
|
| 275 |
+
raise HTTPException(404)
|
| 276 |
+
ext = os.path.splitext(a["audio_path"])[1].lstrip(".") or "webm"
|
| 277 |
+
mime = {"m4a": "audio/mp4", "mp4": "audio/mp4", "ogg": "audio/ogg", "mp3": "audio/mpeg", "wav": "audio/wav"}.get(ext, "audio/webm")
|
| 278 |
+
return Response(get_file(a["audio_path"]), media_type=mime)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _finish(sid: str):
|
| 282 |
+
try:
|
| 283 |
+
deadline = time.time() + 240
|
| 284 |
+
while time.time() < deadline:
|
| 285 |
+
pending = q1("select count(*) as n from answers where session_id=%s and feedback is null", [sid])["n"]
|
| 286 |
+
if pending == 0:
|
| 287 |
+
break
|
| 288 |
+
time.sleep(3)
|
| 289 |
+
s = q1("select * from sessions where id=%s", [sid])
|
| 290 |
+
answers = q("select * from answers where session_id=%s order by idx", [sid])
|
| 291 |
+
lang = s["language"]
|
| 292 |
+
role = s["context"].get("role", "")
|
| 293 |
+
|
| 294 |
+
# voice + calibrated scores over all answers
|
| 295 |
+
audio = ai.session_audio([get_file(a["audio_path"]) for a in answers if a.get("audio_path") and a.get("transcript")])
|
| 296 |
+
voice, calibrated, y_dur = {"error": "No recorded answers"}, None, 0
|
| 297 |
+
texts = [a["transcript"] for a in answers if a.get("transcript")]
|
| 298 |
+
if audio:
|
| 299 |
+
y, sr, utts = audio
|
| 300 |
+
y_dur = len(y) / sr
|
| 301 |
+
for u, t in zip(utts, texts):
|
| 302 |
+
u["text"] = t
|
| 303 |
+
u["prosodic_features"] = pi.extract_prosodic_features(y, sr, u["start"], u["end"])
|
| 304 |
+
voice = pi.analyze_interviewee_voice(y, sr, utts)
|
| 305 |
+
try:
|
| 306 |
+
calibrated = cal.predict(cal.extract_features(y, sr, utts, texts), lang)
|
| 307 |
+
except Exception:
|
| 308 |
+
logger.exception("Calibrated scoring failed")
|
| 309 |
+
|
| 310 |
+
scored = [a["score"] for a in answers if a.get("score") is not None]
|
| 311 |
+
content = round(sum(scored) / len(scored) * 10, 1) if scored else None
|
| 312 |
+
delivery = None
|
| 313 |
+
if calibrated:
|
| 314 |
+
pick = [t["percentile"] for t in calibrated["traits"] if t["trait"] in ("Overall", "EngagingTone", "Excited", "NoFillers", "Calm")]
|
| 315 |
+
delivery = round(sum(pick) / len(pick), 1) if pick else None
|
| 316 |
+
if delivery is None and "error" not in voice:
|
| 317 |
+
delivery = pi.calculate_acceptance_probability(voice, None)
|
| 318 |
+
overall = round(0.65 * content + 0.35 * delivery, 1) if content is not None and delivery is not None else (content or delivery)
|
| 319 |
+
|
| 320 |
+
summary = ai.summarize_session(role, s["level"] or "junior", lang, answers, voice, calibrated, s["mode"] == "job") or {}
|
| 321 |
+
report = {"overall": overall, "content_score": content, "delivery_score": delivery, "calibrated": calibrated,
|
| 322 |
+
"voice": voice, "summary": summary, "duration_s": round(y_dur, 1)}
|
| 323 |
+
|
| 324 |
+
# PDF (reuses the interview report layout)
|
| 325 |
+
pdf_path = None
|
| 326 |
+
try:
|
| 327 |
+
pdf_path = _build_pdf(sid, s, answers, report)
|
| 328 |
+
except Exception:
|
| 329 |
+
logger.exception("PDF build failed")
|
| 330 |
+
q("update sessions set status='completed', overall_score=%s, report=%s, pdf_path=%s, completed_at=now() where id=%s",
|
| 331 |
+
[overall, report, pdf_path, sid])
|
| 332 |
+
except Exception as e:
|
| 333 |
+
logger.exception("Finishing session failed")
|
| 334 |
+
q("update sessions set status='failed', error=%s where id=%s", [str(e)[:500], sid])
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _build_pdf(sid: str, s: Dict, answers: List[Dict], report: Dict) -> str:
|
| 338 |
+
lang = s["language"]
|
| 339 |
+
summ = report["summary"] or {}
|
| 340 |
+
transcript, qa, t = [], [], 0
|
| 341 |
+
for i, a in enumerate(answers):
|
| 342 |
+
dur = int((a.get("duration_s") or 0) * 1000)
|
| 343 |
+
transcript.append({"role": "Interviewer", "start": t, "end": t + 4000, "text": a["question"]})
|
| 344 |
+
transcript.append({"role": "Interviewee", "start": t + 4000, "end": t + 4000 + dur, "text": a.get("transcript") or ""})
|
| 345 |
+
fb = a.get("feedback") or {}
|
| 346 |
+
qa.append({"index": i + 1, "question": a["question"], "answer": a.get("transcript") or "(no answer)",
|
| 347 |
+
"score": a.get("score"), "what_went_well": " ".join(fb.get("strengths", [])),
|
| 348 |
+
"what_to_improve": " ".join(fb.get("improvements", [])), "improved_answer": fb.get("improved_answer", ""),
|
| 349 |
+
"answer_start": t + 4000})
|
| 350 |
+
t += 4000 + dur + 1000
|
| 351 |
+
voice = report["voice"]
|
| 352 |
+
analysis = {
|
| 353 |
+
"user_id": (q1("select coalesce(full_name, email) as n from profiles where id=%s", [s["user_id"]]) or {}).get("n") or "candidate",
|
| 354 |
+
"generated_at": time.strftime("%Y-%m-%d"), "language": lang,
|
| 355 |
+
"interview": {"duration_seconds": report.get("duration_s") or 0, "speaker_turns": len(transcript), "language": "en"},
|
| 356 |
+
"speakers": {"A": {"speaker_name": "EvalBot", "role": "Interviewer"}, "B": {"speaker_name": "Candidate", "role": "Interviewee"}},
|
| 357 |
+
"voice_analysis": voice, "transcript": transcript, "qa_pairs": qa,
|
| 358 |
+
"evaluation": {"content_score": report.get("content_score"), "executive_summary": summ.get("executive_summary", []),
|
| 359 |
+
"communication": [], "communication_tip": "", "strengths": summ.get("strengths", []),
|
| 360 |
+
"weaknesses": summ.get("weaknesses", []), "role_fit": summ.get("role_fit", []),
|
| 361 |
+
"recommendations": summ.get("recommendations", []), "next_steps": summ.get("next_steps", []),
|
| 362 |
+
"ai_generated": bool(summ)},
|
| 363 |
+
"suitability_score": report.get("overall") or 0,
|
| 364 |
+
"verdict": summ.get("headline") or pi.verdict_for(report.get("overall") or 0, lang),
|
| 365 |
+
"calibrated": report.get("calibrated"),
|
| 366 |
+
}
|
| 367 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
|
| 368 |
+
out = tmp.name
|
| 369 |
+
try:
|
| 370 |
+
pi.create_pdf_report(analysis, out, lang)
|
| 371 |
+
with open(out, "rb") as f:
|
| 372 |
+
return put_file(f"sessions/{sid}/report.pdf", f.read(), "application/pdf")
|
| 373 |
+
finally:
|
| 374 |
+
os.remove(out)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@router.post("/sessions/{sid}/finish")
|
| 378 |
+
def finish(sid: str, user: Dict = Depends(current_user)):
|
| 379 |
+
s = _session(sid, user, owner_only=True)
|
| 380 |
+
if s["status"] == "in_progress":
|
| 381 |
+
if not q1("select 1 from answers where session_id=%s", [sid]):
|
| 382 |
+
raise HTTPException(400, "Answer at least one question first")
|
| 383 |
+
q("update sessions set status='processing' where id=%s", [sid])
|
| 384 |
+
_workers.submit(_finish, sid)
|
| 385 |
+
return {"ok": True}
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
@router.get("/sessions/{sid}/pdf")
|
| 389 |
+
def session_pdf(sid: str, user: Dict = Depends(current_user)):
|
| 390 |
+
s = _session(sid, user)
|
| 391 |
+
if not s.get("pdf_path"):
|
| 392 |
+
raise HTTPException(404, "The report is not ready")
|
| 393 |
+
return Response(get_file(s["pdf_path"]), media_type="application/pdf",
|
| 394 |
+
headers={"Content-Disposition": f'inline; filename="evalbot-report-{sid[:8]}.pdf"'})
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
@router.delete("/sessions/{sid}")
|
| 398 |
+
def delete_session(sid: str, user: Dict = Depends(current_user)):
|
| 399 |
+
_session(sid, user, owner_only=True)
|
| 400 |
+
q("delete from sessions where id=%s", [sid])
|
| 401 |
+
return {"ok": True}
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
@router.get("/stats")
|
| 405 |
+
def stats(user: Dict = Depends(current_user)):
|
| 406 |
+
done = q("select id, overall_score, created_at, track, report->'calibrated' as calibrated, report->>'content_score' as content "
|
| 407 |
+
"from sessions where user_id=%s and status='completed' order by created_at", [user["id"]])
|
| 408 |
+
skills = q("select a.feedback->>'skill' as skill, avg(a.score) as avg, count(*) as n from answers a "
|
| 409 |
+
"join sessions s on s.id=a.session_id where s.user_id=%s and a.score is not null and coalesce(a.feedback->>'skill','') <> '' "
|
| 410 |
+
"group by 1 order by n desc limit 8", [user["id"]])
|
| 411 |
+
answered = q1("select count(*) as n, coalesce(sum(duration_s),0) as secs from answers a join sessions s on s.id=a.session_id "
|
| 412 |
+
"where s.user_id=%s", [user["id"]])
|
| 413 |
+
return {"interviews": len(done), "answers": answered["n"], "speaking_minutes": round(float(answered["secs"]) / 60, 1),
|
| 414 |
+
"average": round(sum(d["overall_score"] or 0 for d in done) / len(done), 1) if done else None,
|
| 415 |
+
"best": max((d["overall_score"] or 0 for d in done), default=None),
|
| 416 |
+
"trend": [{"date": d["created_at"].strftime("%Y-%m-%d"), "score": d["overall_score"], "track": d["track"]} for d in done[-20:]],
|
| 417 |
+
"skills": [{"skill": r["skill"], "avg": round(float(r["avg"]), 1), "n": r["n"]} for r in skills]}
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
# --------------------------------------------------------------------------------------
|
| 421 |
+
# Recruiters: jobs, candidates, reviews
|
| 422 |
+
# --------------------------------------------------------------------------------------
|
| 423 |
+
class JobIn(BaseModel):
|
| 424 |
+
title: str = Field(min_length=2, max_length=140)
|
| 425 |
+
track: str = "general"
|
| 426 |
+
level: str = "junior"
|
| 427 |
+
description: str = ""
|
| 428 |
+
questions: List[Dict] = Field(min_length=1, max_length=15)
|
| 429 |
+
answer_seconds: int = Field(120, ge=30, le=600)
|
| 430 |
+
status: str = "open"
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def _clean_questions(qs: List[Dict]) -> List[Dict]:
|
| 434 |
+
return [{"text": x["text"].strip()[:500], "kind": x.get("kind", "custom"), "skill": x.get("skill", ""),
|
| 435 |
+
"rubric": x.get("rubric", "")} for x in qs if x.get("text", "").strip()]
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@router.get("/jobs")
|
| 439 |
+
def list_jobs(user: Dict = Depends(recruiter)):
|
| 440 |
+
return q("select j.*, (select count(*) from sessions s where s.job_id=j.id) as applicants, "
|
| 441 |
+
"(select count(*) from sessions s where s.job_id=j.id and s.status='completed') as completed "
|
| 442 |
+
"from jobs j where j.company_id=%s order by j.created_at desc", [user["company_id"]])
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
@router.post("/jobs")
|
| 446 |
+
def create_job(body: JobIn, user: Dict = Depends(recruiter)):
|
| 447 |
+
return q1("insert into jobs (company_id, created_by, title, track, level, description, questions, answer_seconds, status) "
|
| 448 |
+
"values (%s,%s,%s,%s,%s,%s,%s,%s,%s) returning *",
|
| 449 |
+
[user["company_id"], user["id"], body.title, body.track, body.level, body.description,
|
| 450 |
+
_clean_questions(body.questions), body.answer_seconds, body.status if body.status in ("draft", "open", "closed") else "open"])
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def _job(jid: str, user: Dict) -> Dict:
|
| 454 |
+
j = q1("select * from jobs where id=%s and company_id=%s", [jid, user["company_id"]])
|
| 455 |
+
if not j:
|
| 456 |
+
raise HTTPException(404, "Job not found")
|
| 457 |
+
return j
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
@router.get("/jobs/{jid}")
|
| 461 |
+
def get_job(jid: str, user: Dict = Depends(recruiter)):
|
| 462 |
+
return _job(jid, user)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
@router.put("/jobs/{jid}")
|
| 466 |
+
def update_job(jid: str, body: JobIn, user: Dict = Depends(recruiter)):
|
| 467 |
+
_job(jid, user)
|
| 468 |
+
return q1("update jobs set title=%s, track=%s, level=%s, description=%s, questions=%s, answer_seconds=%s, status=%s "
|
| 469 |
+
"where id=%s returning *", [body.title, body.track, body.level, body.description, _clean_questions(body.questions),
|
| 470 |
+
body.answer_seconds, body.status, jid])
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@router.get("/jobs/{jid}/candidates")
|
| 474 |
+
def job_candidates(jid: str, user: Dict = Depends(recruiter)):
|
| 475 |
+
_job(jid, user)
|
| 476 |
+
return q("select s.id, s.status, s.overall_score, s.created_at, s.completed_at, "
|
| 477 |
+
"s.report->>'content_score' as content_score, s.report->>'delivery_score' as delivery_score, "
|
| 478 |
+
"s.report->'summary'->>'hiring_signal' as hiring_signal, s.report->'summary'->>'headline' as headline, "
|
| 479 |
+
"p.full_name, p.email, coalesce(r.status, 'new') as review_status, r.rating, r.notes "
|
| 480 |
+
"from sessions s join profiles p on p.id=s.user_id left join reviews r on r.session_id=s.id "
|
| 481 |
+
"where s.job_id=%s order by s.overall_score desc nulls last, s.created_at", [jid])
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
class ReviewIn(BaseModel):
|
| 485 |
+
status: str = "new"
|
| 486 |
+
rating: Optional[int] = Field(None, ge=1, le=5)
|
| 487 |
+
notes: Optional[str] = None
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
@router.put("/reviews/{sid}")
|
| 491 |
+
def review(sid: str, body: ReviewIn, user: Dict = Depends(recruiter)):
|
| 492 |
+
s = _session(sid, user)
|
| 493 |
+
if not s.get("job_id"):
|
| 494 |
+
raise HTTPException(400, "Only job interviews can be reviewed")
|
| 495 |
+
if body.status not in ("new", "shortlisted", "rejected", "hired"):
|
| 496 |
+
raise HTTPException(400, "Invalid status")
|
| 497 |
+
return q1("insert into reviews (session_id, reviewer_id, status, rating, notes) values (%s,%s,%s,%s,%s) "
|
| 498 |
+
"on conflict (session_id) do update set status=excluded.status, rating=excluded.rating, notes=excluded.notes, "
|
| 499 |
+
"reviewer_id=excluded.reviewer_id, updated_at=now() returning *",
|
| 500 |
+
[sid, user["id"], body.status, body.rating, body.notes])
|
platform_app/schema.sql
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- EvalBot platform schema (PostgreSQL / Supabase). Idempotent: safe to run on every start.
|
| 2 |
+
|
| 3 |
+
create extension if not exists pgcrypto;
|
| 4 |
+
|
| 5 |
+
create table if not exists companies (
|
| 6 |
+
id uuid primary key default gen_random_uuid(),
|
| 7 |
+
name text not null,
|
| 8 |
+
website text,
|
| 9 |
+
about text,
|
| 10 |
+
created_by uuid not null,
|
| 11 |
+
created_at timestamptz not null default now()
|
| 12 |
+
);
|
| 13 |
+
|
| 14 |
+
create table if not exists profiles (
|
| 15 |
+
id uuid primary key, -- = auth.users.id
|
| 16 |
+
email text,
|
| 17 |
+
full_name text,
|
| 18 |
+
role text not null default 'candidate' check (role in ('candidate', 'recruiter')),
|
| 19 |
+
company_id uuid references companies(id) on delete set null,
|
| 20 |
+
headline text,
|
| 21 |
+
target_track text,
|
| 22 |
+
locale text not null default 'en',
|
| 23 |
+
created_at timestamptz not null default now()
|
| 24 |
+
);
|
| 25 |
+
|
| 26 |
+
create table if not exists jobs (
|
| 27 |
+
id uuid primary key default gen_random_uuid(),
|
| 28 |
+
company_id uuid not null references companies(id) on delete cascade,
|
| 29 |
+
created_by uuid not null,
|
| 30 |
+
title text not null,
|
| 31 |
+
track text not null,
|
| 32 |
+
level text not null,
|
| 33 |
+
description text,
|
| 34 |
+
questions jsonb not null default '[]'::jsonb, -- [{"text": "...", "kind": "technical|behavioral|custom"}]
|
| 35 |
+
answer_seconds int not null default 120,
|
| 36 |
+
status text not null default 'open' check (status in ('draft', 'open', 'closed')),
|
| 37 |
+
share_token text not null unique default encode(gen_random_bytes(9), 'hex'),
|
| 38 |
+
created_at timestamptz not null default now()
|
| 39 |
+
);
|
| 40 |
+
create index if not exists jobs_company_idx on jobs(company_id);
|
| 41 |
+
|
| 42 |
+
create table if not exists sessions (
|
| 43 |
+
id uuid primary key default gen_random_uuid(),
|
| 44 |
+
user_id uuid not null,
|
| 45 |
+
job_id uuid references jobs(id) on delete set null,
|
| 46 |
+
mode text not null check (mode in ('mock', 'job', 'upload')),
|
| 47 |
+
track text,
|
| 48 |
+
level text,
|
| 49 |
+
interview_type text,
|
| 50 |
+
language text not null default 'en',
|
| 51 |
+
status text not null default 'in_progress' check (status in ('in_progress', 'processing', 'completed', 'failed')),
|
| 52 |
+
context jsonb not null default '{}'::jsonb, -- cv / job description summary used for questions
|
| 53 |
+
overall_score real,
|
| 54 |
+
report jsonb,
|
| 55 |
+
pdf_path text,
|
| 56 |
+
error text,
|
| 57 |
+
created_at timestamptz not null default now(),
|
| 58 |
+
completed_at timestamptz
|
| 59 |
+
);
|
| 60 |
+
create index if not exists sessions_user_idx on sessions(user_id, created_at desc);
|
| 61 |
+
create index if not exists sessions_job_idx on sessions(job_id);
|
| 62 |
+
|
| 63 |
+
create table if not exists answers (
|
| 64 |
+
id uuid primary key default gen_random_uuid(),
|
| 65 |
+
session_id uuid not null references sessions(id) on delete cascade,
|
| 66 |
+
idx int not null,
|
| 67 |
+
question text not null,
|
| 68 |
+
kind text,
|
| 69 |
+
is_followup boolean not null default false,
|
| 70 |
+
audio_path text,
|
| 71 |
+
duration_s real,
|
| 72 |
+
transcript text,
|
| 73 |
+
voice jsonb,
|
| 74 |
+
presence jsonb, -- camera metrics computed in the browser (optional)
|
| 75 |
+
feedback jsonb,
|
| 76 |
+
score int,
|
| 77 |
+
created_at timestamptz not null default now(),
|
| 78 |
+
unique (session_id, idx)
|
| 79 |
+
);
|
| 80 |
+
|
| 81 |
+
create table if not exists reviews (
|
| 82 |
+
session_id uuid primary key references sessions(id) on delete cascade,
|
| 83 |
+
reviewer_id uuid not null,
|
| 84 |
+
status text not null default 'new' check (status in ('new', 'shortlisted', 'rejected', 'hired')),
|
| 85 |
+
rating int check (rating between 1 and 5),
|
| 86 |
+
notes text,
|
| 87 |
+
updated_at timestamptz not null default now()
|
| 88 |
+
);
|
process_interview.py
CHANGED
|
@@ -799,6 +799,9 @@ LABELS = {
|
|
| 799 |
"ai_unavailable": "Note: AI content evaluation was unavailable for this run, so sections that depend on it were omitted.",
|
| 800 |
"chart_vocal": "Vocal dynamics (0 = low, 1 = high)", "chart_talk": "Talk time",
|
| 801 |
"chart_q": "Score per question (0-10)",
|
|
|
|
|
|
|
|
|
|
| 802 |
"high": "High", "moderate": "Moderate", "low": "Low", "fluent": "Fluent", "disfluent": "Disfluent",
|
| 803 |
"Communication Skills": "Communication Skills", "Content Delivery": "Content Delivery",
|
| 804 |
"Professional Presentation": "Professional Presentation",
|
|
@@ -839,6 +842,9 @@ LABELS = {
|
|
| 839 |
"ai_unavailable": "ملاحظة: لم يكن تقييم المحتوى بالذكاء الاصطناعي متاحاً، فتم حذف الأقسام المعتمدة عليه.",
|
| 840 |
"chart_vocal": "الأداء الصوتي (0 = منخفض، 1 = مرتفع)", "chart_talk": "توزيع وقت الكلام",
|
| 841 |
"chart_q": "درجة كل سؤال (من 10)",
|
|
|
|
|
|
|
|
|
|
| 842 |
"high": "مرتفع", "moderate": "متوسط", "low": "منخفض", "fluent": "طليق", "disfluent": "متقطع",
|
| 843 |
"Communication Skills": "مهارات التواصل", "Content Delivery": "تقديم المحتوى",
|
| 844 |
"Professional Presentation": "الحضور المهني",
|
|
@@ -1185,6 +1191,16 @@ def create_pdf_report(analysis: Dict, output_path: str, lang: str = "en") -> Non
|
|
| 1185 |
story += [rb.table(rows, [2.3 * inch, W - 2.3 * inch]), Spacer(1, 0.2 * inch)]
|
| 1186 |
story.append(P(T("exec_summary"), "h1"))
|
| 1187 |
bullets(ev.get("executive_summary", []))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1188 |
story.append(PageBreak())
|
| 1189 |
|
| 1190 |
# ---- Communication & vocal dynamics ------------------------------------------------
|
|
@@ -1314,6 +1330,18 @@ def convert_to_serializable(obj):
|
|
| 1314 |
return obj
|
| 1315 |
|
| 1316 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1317 |
def process_interview(audio_path: str, user_id: str = "candidate", output_dir: str = OUTPUT_DIR,
|
| 1318 |
progress=None, lang: str = "en") -> Dict:
|
| 1319 |
"""Run the full pipeline. Returns paths to the PDF and JSON reports plus a short summary."""
|
|
@@ -1363,6 +1391,7 @@ def process_interview(audio_path: str, user_id: str = "candidate", output_dir: s
|
|
| 1363 |
"language": transcript.get("language_code", "en")},
|
| 1364 |
"speakers": speakers, "voice_analysis": voice, "transcript": clean_utts,
|
| 1365 |
"qa_pairs": build_qa_pairs(clean_utts),
|
|
|
|
| 1366 |
"models": {
|
| 1367 |
"transcription": "AssemblyAI universal-2",
|
| 1368 |
"speaker_embeddings": "nvidia/speakerverification_en_titanet_large",
|
|
|
|
| 799 |
"ai_unavailable": "Note: AI content evaluation was unavailable for this run, so sections that depend on it were omitted.",
|
| 800 |
"chart_vocal": "Vocal dynamics (0 = low, 1 = high)", "chart_talk": "Talk time",
|
| 801 |
"chart_q": "Score per question (0-10)",
|
| 802 |
+
"cal_title": "How a panel of interviewers would likely rate the candidate",
|
| 803 |
+
"cal_note": "Percent of {n} real interviews (each rated by nine people) that this candidate would score above. Reliability r is the model's agreement with the panel on people it never saw; a single human rater reaches about {h}.",
|
| 804 |
+
"cal_trait": "Trait", "cal_pct": "Better than", "cal_rel": "Reliability",
|
| 805 |
"high": "High", "moderate": "Moderate", "low": "Low", "fluent": "Fluent", "disfluent": "Disfluent",
|
| 806 |
"Communication Skills": "Communication Skills", "Content Delivery": "Content Delivery",
|
| 807 |
"Professional Presentation": "Professional Presentation",
|
|
|
|
| 842 |
"ai_unavailable": "ملاحظة: لم يكن تقييم المحتوى بالذكاء الاصطناعي متاحاً، فتم حذف الأقسام المعتمدة عليه.",
|
| 843 |
"chart_vocal": "الأداء الصوتي (0 = منخفض، 1 = مرتفع)", "chart_talk": "توزيع وقت الكلام",
|
| 844 |
"chart_q": "درجة كل سؤال (من 10)",
|
| 845 |
+
"cal_title": "كيف ستقيّم لجنة من المحاورين المرشّح على الأرجح",
|
| 846 |
+
"cal_note": "النسبة المئوية من {n} مقابلة حقيقية (قيّم كلاً منها تسعة أشخاص) التي يتفوق عليها المرشّح. ومعامل الموثوقية r هو مدى اتفاق النموذج مع اللجنة على أشخاص لم يرهم، ومقيّم بشري واحد يحقق نحو {h}.",
|
| 847 |
+
"cal_trait": "السمة", "cal_pct": "أفضل من", "cal_rel": "الموثوقية",
|
| 848 |
"high": "مرتفع", "moderate": "متوسط", "low": "منخفض", "fluent": "طليق", "disfluent": "متقطع",
|
| 849 |
"Communication Skills": "مهارات التواصل", "Content Delivery": "تقديم المحتوى",
|
| 850 |
"Professional Presentation": "الحضور المهني",
|
|
|
|
| 1191 |
story += [rb.table(rows, [2.3 * inch, W - 2.3 * inch]), Spacer(1, 0.2 * inch)]
|
| 1192 |
story.append(P(T("exec_summary"), "h1"))
|
| 1193 |
bullets(ev.get("executive_summary", []))
|
| 1194 |
+
|
| 1195 |
+
cal = analysis.get("calibrated")
|
| 1196 |
+
if cal and cal.get("traits"):
|
| 1197 |
+
story.append(P(T("cal_title"), "h2"))
|
| 1198 |
+
h = next((x["human_r"] for x in cal["traits"] if x["trait"] == "Overall"), 0.5)
|
| 1199 |
+
story.append(P(T("cal_note").format(n=cal["reference"]["interviews"], h=f"{h:.2f}"), "small"))
|
| 1200 |
+
rows = [[P(T("cal_trait"), "th"), P(T("cal_pct"), "th"), P(T("cal_rel"), "th")]]
|
| 1201 |
+
for x in cal["traits"]:
|
| 1202 |
+
rows.append([P(x["label"], "tdb"), P(f"{x['percentile']}%", "td"), P(f"r = {x['model_r']:.2f}", "td")])
|
| 1203 |
+
story += [rb.table(rows, [2.6 * inch, 2.2 * inch, W - 4.8 * inch]), Spacer(1, 0.1 * inch)]
|
| 1204 |
story.append(PageBreak())
|
| 1205 |
|
| 1206 |
# ---- Communication & vocal dynamics ------------------------------------------------
|
|
|
|
| 1330 |
return obj
|
| 1331 |
|
| 1332 |
|
| 1333 |
+
def _calibrated(y, sr, utterances, lang):
|
| 1334 |
+
"""Human-calibrated trait scores (see calibration.py); None if the model isn't available."""
|
| 1335 |
+
try:
|
| 1336 |
+
import calibration
|
| 1337 |
+
|
| 1338 |
+
texts = [u["text"] for u in utterances if u["role"] == "Interviewee"]
|
| 1339 |
+
return calibration.predict(calibration.extract_features(y, sr, utterances, texts), lang)
|
| 1340 |
+
except Exception as e:
|
| 1341 |
+
logger.warning("Calibrated scoring unavailable: %s", e)
|
| 1342 |
+
return None
|
| 1343 |
+
|
| 1344 |
+
|
| 1345 |
def process_interview(audio_path: str, user_id: str = "candidate", output_dir: str = OUTPUT_DIR,
|
| 1346 |
progress=None, lang: str = "en") -> Dict:
|
| 1347 |
"""Run the full pipeline. Returns paths to the PDF and JSON reports plus a short summary."""
|
|
|
|
| 1391 |
"language": transcript.get("language_code", "en")},
|
| 1392 |
"speakers": speakers, "voice_analysis": voice, "transcript": clean_utts,
|
| 1393 |
"qa_pairs": build_qa_pairs(clean_utts),
|
| 1394 |
+
"calibrated": _calibrated(y, sr, clean_utts, lang),
|
| 1395 |
"models": {
|
| 1396 |
"transcription": "AssemblyAI universal-2",
|
| 1397 |
"speaker_embeddings": "nvidia/speakerverification_en_titanet_large",
|
requirements.txt
CHANGED
|
@@ -26,3 +26,6 @@ python-multipart
|
|
| 26 |
requests
|
| 27 |
arabic-reshaper
|
| 28 |
python-bidi
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
requests
|
| 27 |
arabic-reshaper
|
| 28 |
python-bidi
|
| 29 |
+
psycopg[binary]>=3.2
|
| 30 |
+
psycopg-pool
|
| 31 |
+
httpx
|
research/README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Research scripts
|
| 2 |
+
|
| 3 |
+
How the calibrated models were trained. They need a local copy of the MIT Interview Dataset (not included; see its license).
|
| 4 |
+
|
| 5 |
+
1. Convert the recordings to 16 kHz mono FLAC (`ffmpeg -i P1.wav -ac 1 -ar 16000 P1.flac`).
|
| 6 |
+
2. `python diarize.py` separates the candidate from the interviewer (writes `diar/*.json`).
|
| 7 |
+
3. `python train_calibration.py` extracts features with `calibration.py`, cross-validates per-trait models and writes `assets/models/calibrated_scores.joblib`.
|
| 8 |
+
4. `python benchmark.py` is the research benchmark using the dataset's own facial, smile and PRAAT features.
|
| 9 |
+
|
| 10 |
+
Put `turker_scores_full_interview.csv` and `interview_transcripts_by_turkers.csv` from the dataset next to the scripts.
|
research/benchmark.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv, re, warnings
|
| 2 |
+
import numpy as np, pandas as pd
|
| 3 |
+
from sklearn.linear_model import RidgeCV
|
| 4 |
+
from sklearn.preprocessing import StandardScaler
|
| 5 |
+
from sklearn.pipeline import make_pipeline
|
| 6 |
+
from sklearn.impute import SimpleImputer
|
| 7 |
+
from sklearn.ensemble import ExtraTreesRegressor
|
| 8 |
+
from sklearn.model_selection import GroupKFold, cross_val_predict
|
| 9 |
+
from text_features import interviewee_turns, text_features
|
| 10 |
+
warnings.filterwarnings("ignore")
|
| 11 |
+
|
| 12 |
+
feat = pd.read_csv("evalbot_features.csv").set_index("interview")
|
| 13 |
+
tx = {}
|
| 14 |
+
for row in csv.reader(open("interview_transcripts_by_turkers.csv", encoding="utf-8", errors="replace")):
|
| 15 |
+
if len(row) >= 2:
|
| 16 |
+
tx[row[0].strip().lower()] = text_features(interviewee_turns(row[1]))
|
| 17 |
+
feat = feat.join(pd.DataFrame(tx).T)
|
| 18 |
+
s = pd.read_csv("turker_scores_full_interview.csv")
|
| 19 |
+
y = s[s.Worker == "AGGR"].assign(Participant=lambda d: d.Participant.str.lower()).set_index("Participant")
|
| 20 |
+
traits = ["Overall", "RecommendHiring", "Excited", "EngagingTone", "Friendly", "Smiled", "EyeContact", "NoFillers",
|
| 21 |
+
"StructuredAnswers", "Calm", "NotAwkward", "Engaged", "Focused"]
|
| 22 |
+
data = feat.join(y[traits], how="inner")
|
| 23 |
+
groups = data.index.str.extract(r"(\d+)")[0].astype(int).values
|
| 24 |
+
sets = {
|
| 25 |
+
"prosody": [c for c in feat.columns if c.startswith("pros_")],
|
| 26 |
+
"face": [c for c in feat.columns if c.startswith("face_")],
|
| 27 |
+
"smile": [c for c in feat.columns if c.startswith("smile_")],
|
| 28 |
+
"text": [c for c in feat.columns if c.startswith("txt_")],
|
| 29 |
+
}
|
| 30 |
+
sets["all"] = sum(sets.values(), [])
|
| 31 |
+
cv = GroupKFold(n_splits=10)
|
| 32 |
+
|
| 33 |
+
def model(kind):
|
| 34 |
+
if kind == "ridge":
|
| 35 |
+
return make_pipeline(SimpleImputer(), StandardScaler(), RidgeCV(alphas=np.logspace(-1, 4, 30)))
|
| 36 |
+
return make_pipeline(SimpleImputer(), ExtraTreesRegressor(n_estimators=400, min_samples_leaf=3, max_features=0.3, random_state=0, n_jobs=-1))
|
| 37 |
+
|
| 38 |
+
res = {}
|
| 39 |
+
for name, cols in sets.items():
|
| 40 |
+
X = data[cols].replace([np.inf, -np.inf], np.nan).values
|
| 41 |
+
for t in traits:
|
| 42 |
+
best = -1
|
| 43 |
+
for kind in ("ridge", "trees"):
|
| 44 |
+
pred = cross_val_predict(model(kind), X, data[t].values, cv=cv, groups=groups)
|
| 45 |
+
r = np.corrcoef(pred, data[t].values)[0, 1]
|
| 46 |
+
res[(t, name, kind)] = r
|
| 47 |
+
print("n =", len(data))
|
| 48 |
+
tab = pd.Series(res).unstack([1, 2]).round(2)
|
| 49 |
+
best = tab.T.groupby(level=0).max().T
|
| 50 |
+
print(best[["prosody", "face", "smile", "text", "all"]].to_string())
|
| 51 |
+
tab.to_csv("benchmark_results.csv")
|
| 52 |
+
data.to_csv("training_table.csv")
|
research/diarize.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local 2-speaker diarization: energy VAD -> ~1.5 s chunks -> TitaNet embeddings -> 2 clusters."""
|
| 2 |
+
import json, os, sys, time
|
| 3 |
+
import numpy as np, librosa, torch
|
| 4 |
+
from sklearn.cluster import AgglomerativeClustering
|
| 5 |
+
from nemo.collections.asr.models import EncDecSpeakerLabelModel
|
| 6 |
+
import logging; logging.getLogger("nemo_logger").setLevel(logging.ERROR)
|
| 7 |
+
|
| 8 |
+
SR = 16000
|
| 9 |
+
model = EncDecSpeakerLabelModel.from_pretrained("nvidia/speakerverification_en_titanet_large", map_location="cpu").eval()
|
| 10 |
+
torch.set_num_threads(os.cpu_count())
|
| 11 |
+
|
| 12 |
+
def chunks(y):
|
| 13 |
+
out = []
|
| 14 |
+
for s, e in librosa.effects.split(y, top_db=32, frame_length=1024, hop_length=256):
|
| 15 |
+
s_ms, e_ms = s * 1000 // SR, e * 1000 // SR
|
| 16 |
+
if e_ms - s_ms < 400:
|
| 17 |
+
continue
|
| 18 |
+
t = s_ms
|
| 19 |
+
while t < e_ms:
|
| 20 |
+
end = min(t + 1500, e_ms)
|
| 21 |
+
if end - t >= 400:
|
| 22 |
+
out.append((int(t), int(end)))
|
| 23 |
+
t = end
|
| 24 |
+
return out
|
| 25 |
+
|
| 26 |
+
@torch.no_grad()
|
| 27 |
+
def embed(y, segs, batch=64):
|
| 28 |
+
embs = []
|
| 29 |
+
for i in range(0, len(segs), batch):
|
| 30 |
+
part = segs[i:i + batch]
|
| 31 |
+
sigs = [torch.tensor(y[s * SR // 1000: e * SR // 1000]) for s, e in part]
|
| 32 |
+
lens = torch.tensor([len(x) for x in sigs])
|
| 33 |
+
pad = torch.nn.utils.rnn.pad_sequence(sigs, batch_first=True)
|
| 34 |
+
_, emb = model.forward(input_signal=pad, input_signal_length=lens)
|
| 35 |
+
embs.append(torch.nn.functional.normalize(emb, dim=1).numpy())
|
| 36 |
+
return np.vstack(embs)
|
| 37 |
+
|
| 38 |
+
def diarize(path):
|
| 39 |
+
y, _ = librosa.load(path, sr=SR)
|
| 40 |
+
segs = chunks(y)
|
| 41 |
+
E = embed(y, segs)
|
| 42 |
+
lab = AgglomerativeClustering(n_clusters=2, metric="cosine", linkage="average").fit_predict(E)
|
| 43 |
+
# smooth isolated labels (a single chunk between two of the other speaker)
|
| 44 |
+
for i in range(1, len(lab) - 1):
|
| 45 |
+
if lab[i - 1] == lab[i + 1] != lab[i] and segs[i + 1][0] - segs[i - 1][1] < 3000:
|
| 46 |
+
lab[i] = lab[i - 1]
|
| 47 |
+
dur = {k: sum(e - s for (s, e), l in zip(segs, lab) if l == k) for k in (0, 1)}
|
| 48 |
+
cand = max(dur, key=dur.get) # the candidate does most of the talking in these interviews
|
| 49 |
+
return {"duration_s": len(y) / SR, "segments": [[s, e, int(l == cand)] for (s, e), l in zip(segs, lab)],
|
| 50 |
+
"candidate_share": dur[cand] / max(sum(dur.values()), 1)}
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
src = "/mnt/user-data/uploads/data/processed/audio16k"
|
| 54 |
+
files = sys.argv[1:] or sorted(os.listdir(src))
|
| 55 |
+
for f in files:
|
| 56 |
+
out = f"diar/{os.path.splitext(f)[0].lower()}.json"
|
| 57 |
+
if os.path.exists(out):
|
| 58 |
+
continue
|
| 59 |
+
t = time.time()
|
| 60 |
+
r = diarize(os.path.join(src, f))
|
| 61 |
+
json.dump(r, open(out, "w"))
|
| 62 |
+
print(f, f"{r['duration_s']/60:.1f} min", len(r["segments"]), "chunks", f"cand share {r['candidate_share']:.2f}", f"{time.time()-t:.1f}s", flush=True)
|
research/text_features.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lexical features from the interviewee's words (computable from any transcript)."""
|
| 2 |
+
import re
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
FILLERS = re.compile(r"\b(um+|uh+|uhm+|er+|ah+|hmm+|like|you know|i mean|kind of|sort of|basically|actually)\b")
|
| 6 |
+
POS = set("good great love enjoy excited happy interesting passion passionate fun amazing excellent best success successful proud glad".split())
|
| 7 |
+
NEG = set("bad hard difficult problem problems stress stressed worried hate fail failed failure wrong sorry unfortunately".split())
|
| 8 |
+
TENTATIVE = set("maybe perhaps guess probably possibly somewhat seems".split())
|
| 9 |
+
WE = {"we", "us", "our", "team", "together"}
|
| 10 |
+
I = {"i", "me", "my", "i'm", "i've", "myself"}
|
| 11 |
+
|
| 12 |
+
def interviewee_turns(transcript: str):
|
| 13 |
+
turns = []
|
| 14 |
+
for t in transcript.split("|"):
|
| 15 |
+
if ":" in t:
|
| 16 |
+
who, text = t.split(":", 1)
|
| 17 |
+
if who.strip().lower().startswith("interviewee"):
|
| 18 |
+
turns.append(re.sub(r"\[.*?\]", " ", text).strip())
|
| 19 |
+
return [t for t in turns if t]
|
| 20 |
+
|
| 21 |
+
def text_features(turns):
|
| 22 |
+
text = " ".join(turns).lower()
|
| 23 |
+
words = re.findall(r"[a-z']+", text)
|
| 24 |
+
n = max(len(words), 1)
|
| 25 |
+
sents = [s for s in re.split(r"[.!?]+", text) if s.strip()]
|
| 26 |
+
uniq = len(set(words))
|
| 27 |
+
return {
|
| 28 |
+
"txt_words": len(words),
|
| 29 |
+
"txt_words_per_turn": len(words) / max(len(turns), 1),
|
| 30 |
+
"txt_type_token": uniq / n,
|
| 31 |
+
"txt_unique_words": uniq,
|
| 32 |
+
"txt_filler_rate": len(FILLERS.findall(text)) / n,
|
| 33 |
+
"txt_i_rate": sum(w in I for w in words) / n,
|
| 34 |
+
"txt_we_rate": sum(w in WE for w in words) / n,
|
| 35 |
+
"txt_pos_rate": sum(w in POS for w in words) / n,
|
| 36 |
+
"txt_neg_rate": sum(w in NEG for w in words) / n,
|
| 37 |
+
"txt_tentative_rate": sum(w in TENTATIVE for w in words) / n,
|
| 38 |
+
"txt_number_rate": len(re.findall(r"\b\d+\b|\b(one|two|three|four|five|ten|hundred|percent)\b", text)) / n,
|
| 39 |
+
"txt_avg_word_len": float(np.mean([len(w) for w in words])) if words else 0,
|
| 40 |
+
"txt_avg_sentence_len": len(words) / max(len(sents), 1),
|
| 41 |
+
"txt_long_word_rate": sum(len(w) >= 7 for w in words) / n,
|
| 42 |
+
"txt_because_rate": len(re.findall(r"\b(because|so that|therefore|which meant|as a result)\b", text)) / n,
|
| 43 |
+
}
|
research/train_calibration.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train EvalBot's human-calibrated score models on the MIT Interview Dataset.
|
| 2 |
+
|
| 3 |
+
Steps: diarization JSON + 16 kHz audio + human transcripts -> calibration.extract_features
|
| 4 |
+
-> per-trait models evaluated with person-grouped 10-fold CV -> bundle saved for the app.
|
| 5 |
+
"""
|
| 6 |
+
import csv, json, os, sys, time, warnings
|
| 7 |
+
import numpy as np, pandas as pd, librosa, joblib
|
| 8 |
+
from sklearn.linear_model import RidgeCV
|
| 9 |
+
from sklearn.ensemble import ExtraTreesRegressor
|
| 10 |
+
from sklearn.impute import SimpleImputer
|
| 11 |
+
from sklearn.pipeline import make_pipeline
|
| 12 |
+
from sklearn.preprocessing import StandardScaler
|
| 13 |
+
from sklearn.model_selection import GroupKFold, cross_val_predict
|
| 14 |
+
|
| 15 |
+
warnings.filterwarnings("ignore")
|
| 16 |
+
APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 17 |
+
sys.path.insert(0, APP)
|
| 18 |
+
import calibration as cal # noqa: E402
|
| 19 |
+
from text_features import interviewee_turns # noqa: E402
|
| 20 |
+
|
| 21 |
+
AUDIO = os.getenv("EVALBOT_AUDIO_DIR", "audio16k")
|
| 22 |
+
FEAT_CACHE = "calibrated_features.csv"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def utterances_from_diar(d, gap_ms=1000):
|
| 26 |
+
utts = []
|
| 27 |
+
for s, e, c in d["segments"]:
|
| 28 |
+
role = "Interviewee" if c else "Interviewer"
|
| 29 |
+
if utts and utts[-1]["role"] == role and s - utts[-1]["end"] < gap_ms:
|
| 30 |
+
utts[-1]["end"] = e
|
| 31 |
+
else:
|
| 32 |
+
utts.append({"role": role, "start": s, "end": e})
|
| 33 |
+
return utts
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def build_features():
|
| 37 |
+
tx = {}
|
| 38 |
+
for row in csv.reader(open("interview_transcripts_by_turkers.csv", encoding="utf-8", errors="replace")):
|
| 39 |
+
if len(row) >= 2:
|
| 40 |
+
tx[row[0].strip().lower()] = interviewee_turns(row[1])
|
| 41 |
+
done = pd.read_csv(FEAT_CACHE).set_index("interview") if os.path.exists(FEAT_CACHE) else pd.DataFrame()
|
| 42 |
+
rows = [] if done.empty else [dict(r, interview=i) for i, r in done.iterrows()]
|
| 43 |
+
for f in sorted(os.listdir("diar")):
|
| 44 |
+
k = f[:-5]
|
| 45 |
+
if k in done.index or k not in tx:
|
| 46 |
+
continue
|
| 47 |
+
t = time.time()
|
| 48 |
+
d = json.load(open(f"diar/{f}"))
|
| 49 |
+
y, sr = librosa.load(os.path.join(AUDIO, k.upper() + ".flac"), sr=16000)
|
| 50 |
+
feats = cal.extract_features(y, sr, utterances_from_diar(d), tx[k])
|
| 51 |
+
feats["interview"] = k
|
| 52 |
+
rows.append(feats)
|
| 53 |
+
pd.DataFrame(rows).set_index("interview").to_csv(FEAT_CACHE)
|
| 54 |
+
print(k, f"{time.time() - t:.1f}s", flush=True)
|
| 55 |
+
return pd.read_csv(FEAT_CACHE).set_index("interview")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def human_agreement(scores, traits):
|
| 59 |
+
r = scores[scores.Worker != "AGGR"].copy()
|
| 60 |
+
out = {}
|
| 61 |
+
for t in traits:
|
| 62 |
+
vals = []
|
| 63 |
+
for w, g in r.groupby("Worker"):
|
| 64 |
+
if len(g) < 10:
|
| 65 |
+
continue
|
| 66 |
+
others = r[r.Worker != w].groupby("Participant")[t].mean()
|
| 67 |
+
m = g.set_index("Participant")[t].to_frame("me").join(others.rename("oth")).dropna()
|
| 68 |
+
if len(m) >= 10:
|
| 69 |
+
vals.append(m.me.corr(m.oth))
|
| 70 |
+
out[t] = float(np.nanmean(vals))
|
| 71 |
+
return out
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def candidates():
|
| 75 |
+
return {
|
| 76 |
+
"ridge": lambda: make_pipeline(SimpleImputer(), StandardScaler(), RidgeCV(alphas=np.logspace(-1, 4, 30))),
|
| 77 |
+
"trees": lambda: make_pipeline(SimpleImputer(), ExtraTreesRegressor(
|
| 78 |
+
n_estimators=500, min_samples_leaf=3, max_features=0.3, random_state=0, n_jobs=-1)),
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def main():
|
| 83 |
+
X = build_features()
|
| 84 |
+
s = pd.read_csv("turker_scores_full_interview.csv")
|
| 85 |
+
s["Participant"] = s.Participant.str.lower()
|
| 86 |
+
y = s[s.Worker == "AGGR"].set_index("Participant")
|
| 87 |
+
traits = ["Overall", "RecommendHiring", "Colleague", "Engaged", "Excited", "EngagingTone", "Friendly",
|
| 88 |
+
"NoFillers", "StructuredAnswers", "Calm", "NotStressed", "Focused", "Authentic", "NotAwkward",
|
| 89 |
+
"Paused", "SpeakingRate", "Smiled", "EyeContact"]
|
| 90 |
+
data = X.join(y[traits], how="inner")
|
| 91 |
+
# interviewer-dependent features are excluded: in EvalBot mock interviews the "interviewer" is the browser
|
| 92 |
+
feat_names = [c for c in X.columns if c not in ("voc_talk_share", "voc_turns_per_min")]
|
| 93 |
+
groups = data.index.str.extract(r"(\d+)")[0].astype(int).values
|
| 94 |
+
Xv = data[feat_names].replace([np.inf, -np.inf], np.nan).values
|
| 95 |
+
lo, hi = np.nanpercentile(Xv, 1, axis=0), np.nanpercentile(Xv, 99, axis=0)
|
| 96 |
+
Xv = np.where(np.isnan(Xv), Xv, np.clip(Xv, lo, hi))
|
| 97 |
+
human = human_agreement(s, traits)
|
| 98 |
+
cv = GroupKFold(n_splits=10)
|
| 99 |
+
|
| 100 |
+
results, models = [], {}
|
| 101 |
+
for t in traits:
|
| 102 |
+
yt = data[t].values
|
| 103 |
+
best = None
|
| 104 |
+
for name, make in candidates().items():
|
| 105 |
+
pred = cross_val_predict(make(), Xv, yt, cv=cv, groups=groups)
|
| 106 |
+
r = float(np.corrcoef(pred, yt)[0, 1])
|
| 107 |
+
mae = float(np.mean(np.abs(pred - yt)))
|
| 108 |
+
if best is None or r > best[1]:
|
| 109 |
+
best = (name, r, mae)
|
| 110 |
+
results.append({"trait": t, "model": best[0], "cv_r": round(best[1], 3), "cv_mae": round(best[2], 3),
|
| 111 |
+
"human_r": round(human[t], 3)})
|
| 112 |
+
if best[1] >= 0.35: # only ship traits the model predicts reliably
|
| 113 |
+
m = candidates()[best[0]]().fit(Xv, yt)
|
| 114 |
+
models[t] = {"model": m, "cv_r": best[1], "cv_mae": best[2], "human_r": human[t],
|
| 115 |
+
"ref_mean": float(yt.mean()), "ref_std": float(yt.std())}
|
| 116 |
+
res = pd.DataFrame(results).set_index("trait")
|
| 117 |
+
print(res.to_string())
|
| 118 |
+
res.to_csv("calibration_results.csv")
|
| 119 |
+
|
| 120 |
+
display = ["RecommendHiring", "Overall", "Excited", "EngagingTone", "Engaged", "Friendly", "StructuredAnswers",
|
| 121 |
+
"NoFillers", "Calm", "NotStressed", "Focused", "Colleague", "Authentic", "NotAwkward", "Paused",
|
| 122 |
+
"SpeakingRate", "Smiled", "EyeContact"]
|
| 123 |
+
bundle = {
|
| 124 |
+
"version": time.strftime("%Y-%m-%d"),
|
| 125 |
+
"feature_names": feat_names,
|
| 126 |
+
"feature_bounds": [lo.tolist(), hi.tolist()],
|
| 127 |
+
"models": models,
|
| 128 |
+
"display_order": display,
|
| 129 |
+
"reference": {"dataset": "MIT Interview Dataset (Naim et al., IEEE Trans. Affective Computing)",
|
| 130 |
+
"interviews": int(len(data)), "raters_per_interview": 9,
|
| 131 |
+
"validation": "10-fold cross-validation grouped by participant"},
|
| 132 |
+
}
|
| 133 |
+
os.makedirs(os.path.join(APP, "assets", "models"), exist_ok=True)
|
| 134 |
+
joblib.dump(bundle, os.path.join(APP, "assets", "models", "calibrated_scores.joblib"), compress=3)
|
| 135 |
+
print("shipped traits:", list(models))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__":
|
| 139 |
+
main()
|