Spaces:
Sleeping

Manoj Thapa commited on
Commit
4a9cd63
Β·
0 Parent(s):

Initial commit for NeuroArc AI-powered job assistant with CV optimization tools.

Browse files
Files changed (48) hide show
  1. .gitattributes +2 -0
  2. .gitignore +31 -0
  3. Dockerfile +41 -0
  4. README.md +75 -0
  5. backend/.env.example +5 -0
  6. backend/main.py +118 -0
  7. backend/requirements.txt +14 -0
  8. backend/routers/__init__.py +1 -0
  9. backend/routers/cv.py +279 -0
  10. backend/routers/jobs.py +69 -0
  11. backend/services/__init__.py +1 -0
  12. backend/services/ai_service.py +673 -0
  13. backend/services/cv_parser.py +375 -0
  14. backend/services/job_service.py +337 -0
  15. backend/services/pdf_generator.py +279 -0
  16. frontend/index.html +48 -0
  17. frontend/package-lock.json +0 -0
  18. frontend/package.json +39 -0
  19. frontend/public/bmc-icon.png +0 -0
  20. frontend/public/favicon.svg +11 -0
  21. frontend/public/textures/earth_clouds.png +3 -0
  22. frontend/public/textures/earth_daymap.jpg +3 -0
  23. frontend/public/textures/earth_normal.jpg +3 -0
  24. frontend/public/textures/earth_specular.jpg +3 -0
  25. frontend/public/textures/galaxy_bg.jpg +3 -0
  26. frontend/public/textures/iss_clean_texture.png +3 -0
  27. frontend/public/textures/jupiter_map.jpg +3 -0
  28. frontend/public/textures/mars_map.jpg +3 -0
  29. frontend/public/textures/mercury_map.jpg +3 -0
  30. frontend/public/textures/moon_bump.jpg +3 -0
  31. frontend/public/textures/moon_map.jpg +3 -0
  32. frontend/public/textures/neptune_map.jpg +3 -0
  33. frontend/public/textures/saturn_map.jpg +3 -0
  34. frontend/public/textures/sun_map.jpg +3 -0
  35. frontend/public/textures/uranus_map.jpg +3 -0
  36. frontend/public/textures/venus_map.jpg +3 -0
  37. frontend/src/App.jsx +698 -0
  38. frontend/src/components/AboutUs.jsx +119 -0
  39. frontend/src/components/Background3D.jsx +284 -0
  40. frontend/src/components/CVAnalysis.jsx +562 -0
  41. frontend/src/components/DocumentPreview.jsx +270 -0
  42. frontend/src/components/GenerationProgress.jsx +48 -0
  43. frontend/src/components/JobList.jsx +410 -0
  44. frontend/src/components/JobSearch.jsx +170 -0
  45. frontend/src/index.css +625 -0
  46. frontend/src/main.jsx +10 -0
  47. frontend/vite.config.js +15 -0
  48. run.sh +150 -0
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ frontend/public/textures/*.jpg filter=lfs diff=lfs merge=lfs -text
2
+ frontend/public/textures/*.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dependencies
2
+ node_modules/
3
+ venv/
4
+ __pycache__/
5
+ *.pyc
6
+ *.pyo
7
+
8
+ # Environment variables (IMPORTANT: Never commit API keys!)
9
+ .env
10
+ .env.local
11
+ .env.production
12
+
13
+ # Build outputs
14
+ dist/
15
+ build/
16
+ *.egg-info/
17
+
18
+ # IDE
19
+ .vscode/
20
+ .idea/
21
+ *.swp
22
+ *.swo
23
+ .DS_Store
24
+
25
+ # Logs
26
+ *.log
27
+ npm-debug.log*
28
+
29
+ # Test coverage
30
+ coverage/
31
+ .pytest_cache/
Dockerfile ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi-stage build for Hugging Face Spaces
2
+
3
+ # Stage 1: Build Frontend
4
+ FROM node:18-alpine as frontend-builder
5
+ WORKDIR /app/frontend
6
+ COPY frontend/package.json ./
7
+ # Use --legacy-peer-deps to avoid potential conflicts with older packages
8
+ RUN npm install --legacy-peer-deps
9
+ COPY frontend/ .
10
+ RUN npm run build
11
+
12
+ # Stage 2: Setup Backend & Run
13
+ FROM python:3.11-slim
14
+
15
+ # Set working directory
16
+ WORKDIR /app
17
+
18
+ # Install system dependencies (e.g., for PyMuPDF or OpenCV if needed)
19
+ # python-multipart needs no special system deps usually, but good to be safe
20
+ RUN apt-get update && apt-get install -y --no-install-recommends \
21
+ build-essential \
22
+ && rm -rf /var/lib/apt/lists/*
23
+
24
+ # Copy backend requirements
25
+ COPY backend/requirements.txt ./backend/requirements.txt
26
+
27
+ # Install Python dependencies
28
+ RUN pip install --no-cache-dir -r ./backend/requirements.txt
29
+
30
+ # Copy backend code
31
+ COPY backend/ ./backend/
32
+
33
+ # Copy built frontend from Stage 1
34
+ COPY --from=frontend-builder /app/frontend/dist ./frontend/dist
35
+
36
+ # Expose the port HF Spaces uses (7860)
37
+ EXPOSE 7860
38
+
39
+ # Run the application
40
+ # We use 'backend.main:app' and host 0.0.0.0 for Docker
41
+ CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NeuroArc <img src="frontend/public/favicon.svg" width="40" height="40" align="center" />
2
+
3
+ > **AI-Powered Job Application Assistant**
4
+ > Search jobs β†’ Match to your CV β†’ Generate tailored CV
5
+
6
+ ## ✨ Features
7
+
8
+
9
+ - **πŸ“„ CV Parsing** - Upload PDF/DOCX and automatically extract skills, experience, and contact info.
10
+ - **πŸ” Smart Job Search** - Search real jobs from Reed API (UK's largest job board).
11
+ - **🎯 Match Scoring** - Jobs ranked by how well they match your CV skills.
12
+ - **✍️ AI-Tailored CV** - Generate CVs optimized on the basis of ATS standards.
13
+
14
+ - **πŸ“₯ PDF Export** - Download professional documents ready to submit.
15
+
16
+ ---
17
+
18
+ ## πŸ› οΈ Tech Stack
19
+
20
+ | Layer | Technology |
21
+ |-------|------------|
22
+ | Frontend | React 18, Vite, Three.js (React Three Fiber) |
23
+ | Backend | FastAPI, Python 3.11+ |
24
+ | AI | GPT-4o (GitHub Models) |
25
+ | CV Parsing | PyMuPDF, python-docx |
26
+ | PDF Generation | ReportLab |
27
+ | Job Data | Reed UK API |
28
+
29
+ ---
30
+
31
+ ## πŸš€ Quick Start
32
+
33
+ ### Prerequisites
34
+
35
+ - Python 3.10+
36
+ - Node.js 18+
37
+
38
+ ### Installation
39
+
40
+ 1. **Clone the repository**
41
+ ```bash
42
+ git clone https://github.com/iammanoj807/cortexcv.git
43
+ cd cortexcv
44
+ ```
45
+
46
+ 2. **Configure API Keys**
47
+ You simply need to provide these API keys in `backend/.env`:
48
+ - `GITHUB_TOKEN`
49
+ - `REED_API_KEY`
50
+
51
+ 3. **Start the application**
52
+ ```bash
53
+ chmod +x run.sh
54
+ ./run.sh
55
+ ```
56
+
57
+ 4. **Open in browser**
58
+ - Frontend: http://localhost:5173
59
+ - API Docs: http://localhost:8000/docs
60
+
61
+ ---
62
+
63
+ ## 🀝 Contributing
64
+
65
+ Contributions are welcome! Please fork the repository and submit a Pull Request.
66
+
67
+ ---
68
+
69
+ ## πŸ“„ License
70
+
71
+ Distributed under the MIT License. See `LICENSE` for more information.
72
+
73
+ ---
74
+
75
+ Made with ❀️ by Manoj Kumar Thapa
backend/.env.example ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # GitHub Models API Token (for GPT-4o access)
2
+ GITHUB_TOKEN=your_github_token_here
3
+
4
+ # Reed API Key (UK's largest job board)
5
+ REED_API_KEY=your_reed_api_key_here
backend/main.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NeuroArc - FastAPI Backend
3
+ AI-powered job application assistant
4
+ """
5
+ from contextlib import asynccontextmanager
6
+ from fastapi import FastAPI, Request
7
+ from fastapi.staticfiles import StaticFiles
8
+ from fastapi.responses import FileResponse, JSONResponse
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from dotenv import load_dotenv
11
+ import os
12
+ import logging
13
+
14
+ # Configure logging
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
18
+ )
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # Load environment variables
22
+ load_dotenv()
23
+
24
+ # Import routers
25
+ from routers import jobs, cv
26
+
27
+ @asynccontextmanager
28
+ async def lifespan(app: FastAPI):
29
+ """Application lifespan handler"""
30
+ logger.info("πŸš€ NeuroArc Backend starting...")
31
+ yield
32
+ logger.info("πŸ‘‹ NeuroArc Backend shutting down...")
33
+
34
+ app = FastAPI(
35
+ title="NeuroArc",
36
+ description="AI-powered job application assistant - Find jobs, generate tailored CVs",
37
+ version="1.0.0",
38
+ lifespan=lifespan
39
+ )
40
+
41
+ # CORS configuration - Allow common development and production origins
42
+ allowed_origins = [
43
+ "http://localhost:5173",
44
+ "http://127.0.0.1:5173",
45
+ "http://localhost:3000",
46
+ "http://127.0.0.1:3000",
47
+ ]
48
+
49
+ # Add custom origins from environment if provided
50
+ custom_origins = os.getenv("CORS_ORIGINS", "").split(",")
51
+ allowed_origins.extend([origin.strip() for origin in custom_origins if origin.strip()])
52
+
53
+ app.add_middleware(
54
+ CORSMiddleware,
55
+ allow_origins=allowed_origins,
56
+ allow_credentials=True,
57
+ allow_methods=["*"],
58
+ allow_headers=["*"],
59
+ )
60
+
61
+ # Include routers
62
+ app.include_router(jobs.router, prefix="/api/jobs", tags=["Jobs"])
63
+ app.include_router(cv.router, prefix="/api/cv", tags=["CV"])
64
+
65
+ # Static Files & Frontend Serving
66
+ # Check if frontend build exists (Production/Docker mode)
67
+ frontend_dist = os.path.join(os.path.dirname(os.path.dirname(__file__)), "frontend", "dist")
68
+
69
+ if os.path.exists(frontend_dist):
70
+ # Serve assets (JS, CSS, Images)
71
+ app.mount("/assets", StaticFiles(directory=os.path.join(frontend_dist, "assets")), name="assets")
72
+
73
+ # Catch-all for React Router - serves index.html for non-API routes
74
+ @app.middleware("http")
75
+ async def spa_middleware(request: Request, call_next):
76
+ # Allow API calls to pass through
77
+ if request.url.path.startswith("/api") or request.url.path.startswith("/docs") or request.url.path.startswith("/openapi.json"):
78
+ return await call_next(request)
79
+
80
+ # Try to serve static file if it exists directly (e.g., favicon.svg)
81
+ full_path = os.path.join(frontend_dist, request.url.path.lstrip("/"))
82
+ if os.path.exists(full_path) and os.path.isfile(full_path):
83
+ return FileResponse(full_path)
84
+
85
+ # Otherwise serve index.html (SPA routing)
86
+ return FileResponse(os.path.join(frontend_dist, "index.html"))
87
+
88
+ else:
89
+ # Dev mode / API only
90
+ @app.get("/")
91
+ async def root():
92
+ return {
93
+ "name": "NeuroArc",
94
+ "version": "1.0.0",
95
+ "status": "running",
96
+ "mode": "api_only",
97
+ "message": "Frontend build not found. Run 'npm run build' in frontend/ directory to serve UI.",
98
+ "endpoints": {
99
+ "jobs": "/api/jobs",
100
+ "cv": "/api/cv",
101
+ "docs": "/docs"
102
+ }
103
+ }
104
+
105
+ @app.get("/health")
106
+ async def health_check():
107
+ """Health check endpoint with dependency status"""
108
+ github_token = bool(os.getenv("GITHUB_TOKEN", ""))
109
+ reed_api_key = bool(os.getenv("REED_API_KEY", ""))
110
+
111
+ return {
112
+ "status": "healthy",
113
+ "dependencies": {
114
+ "ai_service": "available" if github_token else "unavailable (no GITHUB_TOKEN)",
115
+ "job_search": "available" if reed_api_key else "mock mode (no REED_API_KEY)"
116
+ }
117
+ }
118
+
backend/requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Backend dependencies for NeuroArc
2
+ fastapi==0.115.6
3
+ uvicorn[standard]==0.34.0
4
+ python-multipart==0.0.6
5
+ httpx==0.28.1
6
+ python-dotenv==1.0.1
7
+ pymupdf==1.25.1
8
+ python-docx==1.1.2
9
+ azure-ai-inference==1.0.0b7
10
+ reportlab==4.2.5
11
+ pydantic==2.10.3
12
+ pytesseract==0.3.10
13
+ pdf2image==1.17.0
14
+ Pillow>=10.0.0
backend/routers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Routers package
backend/routers/cv.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CV Router - API endpoints for CV upload, parsing, and generation
3
+ """
4
+ from fastapi import APIRouter, UploadFile, File, HTTPException, Form
5
+ from fastapi.responses import Response
6
+ from pydantic import BaseModel
7
+ from typing import Optional, List, Dict, Any
8
+ from services.cv_parser import cv_parser
9
+ from services.ai_service import ai_service
10
+ from services.pdf_generator import pdf_generator
11
+ import hashlib
12
+ import time
13
+ import logging
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ router = APIRouter()
18
+
19
+ # Store CV data in memory with timestamps (in production, use database or session storage)
20
+ cv_store = {}
21
+ CV_STORE_MAX_AGE = 3600 # 1 hour in seconds
22
+
23
+ def cleanup_old_cvs():
24
+ """Remove CVs older than CV_STORE_MAX_AGE"""
25
+ current_time = time.time()
26
+ expired_keys = [
27
+ key for key, value in cv_store.items()
28
+ if current_time - value.get("timestamp", 0) > CV_STORE_MAX_AGE
29
+ ]
30
+ for key in expired_keys:
31
+ del cv_store[key]
32
+ logger.info(f"Cleaned up expired CV: {key}")
33
+
34
+ class CVGenerateRequest(BaseModel):
35
+ cv_id: str
36
+ job_title: str
37
+ job_description: str
38
+ company_name: str
39
+ ats_analysis: Optional[Dict[str, Any]] = None
40
+
41
+ @router.post("/upload")
42
+ async def upload_cv(file: UploadFile = File(...)):
43
+ """
44
+ Upload and parse a CV file (PDF or DOCX)
45
+
46
+ Returns extracted text, skills, and contact information.
47
+ """
48
+ # Cleanup old CVs periodically
49
+ cleanup_old_cvs()
50
+
51
+ try:
52
+ # Get filename
53
+ filename = file.filename or "unknown"
54
+
55
+ # Validate file type
56
+ if not any(filename.lower().endswith(ext) for ext in ['.pdf', '.docx', '.txt']):
57
+ raise HTTPException(
58
+ status_code=400,
59
+ detail="Unsupported file format. Please upload PDF, DOCX, or TXT."
60
+ )
61
+
62
+ # Read file content
63
+ content = await file.read()
64
+
65
+ # Check if we got any content
66
+ if not content or len(content) == 0:
67
+ raise HTTPException(
68
+ status_code=400,
69
+ detail="Empty file received. Please upload a valid file."
70
+ )
71
+
72
+ if len(content) > 10 * 1024 * 1024: # 10MB limit
73
+ raise HTTPException(
74
+ status_code=400,
75
+ detail="File too large. Maximum size is 10MB."
76
+ )
77
+
78
+ # Analyze the CV
79
+ result = cv_parser.analyze_cv(content, filename)
80
+
81
+ if not result["success"]:
82
+ raise HTTPException(
83
+ status_code=422,
84
+ detail=result.get("error", "Failed to parse CV")
85
+ )
86
+
87
+ # Generate a simple ID for the CV
88
+ cv_id = hashlib.md5(content).hexdigest()[:12]
89
+
90
+ # Store for later use with timestamp
91
+ result["timestamp"] = time.time()
92
+ cv_store[cv_id] = result
93
+
94
+ logger.info(f"CV uploaded successfully: {cv_id} ({result['skills_count']} skills detected)")
95
+
96
+ return {
97
+ "success": True,
98
+ "cv_id": cv_id,
99
+ "filename": result["filename"],
100
+ "format": result["format"],
101
+ "text_length": result["text_length"],
102
+ "skills": result["skills"],
103
+ "skills_count": result["skills_count"],
104
+ "contact": result["contact"],
105
+ "education": result["education"],
106
+ "name": result.get("name"),
107
+ "experience_years": result.get("experience_years"),
108
+ "detected_industry": result.get("detected_industry"),
109
+ "preview": result["text"][:500] + "..." if len(result["text"]) > 500 else result["text"]
110
+ }
111
+ except HTTPException:
112
+ raise
113
+ except Exception as e:
114
+ logger.error(f"Error processing CV upload: {str(e)}")
115
+ raise HTTPException(
116
+ status_code=500,
117
+ detail=f"Error processing file: {str(e)}"
118
+ )
119
+
120
+ @router.get("/{cv_id}")
121
+ async def get_cv(cv_id: str):
122
+ """Get stored CV data by ID"""
123
+ if cv_id not in cv_store:
124
+ raise HTTPException(status_code=404, detail="CV not found or expired. Please upload again.")
125
+
126
+ cv_data = cv_store[cv_id]
127
+ return {
128
+ "success": True,
129
+ "cv_id": cv_id,
130
+ "name": cv_data.get("name"), # NEW
131
+ "skills": cv_data["skills"],
132
+ "skills_count": cv_data["skills_count"],
133
+ "contact": cv_data["contact"],
134
+ "education": cv_data["education"],
135
+ "experience_years": cv_data.get("experience_years"), # NEW
136
+ "detected_industry": cv_data.get("detected_industry"), # NEW
137
+ "text_length": cv_data["text_length"],
138
+ "filename": cv_data.get("filename"), # NEW
139
+ "format": cv_data.get("format") # NEW
140
+ }
141
+
142
+ @router.post("/generate")
143
+ async def generate_tailored_cv(request: CVGenerateRequest):
144
+ """
145
+ Generate a tailored CV for a specific job
146
+
147
+ Uses AI to rewrite and optimize the CV based on the job description.
148
+ Returns the tailored CV content.
149
+ """
150
+ if request.cv_id not in cv_store:
151
+ raise HTTPException(status_code=404, detail="CV not found or expired. Please upload again.")
152
+
153
+ cv_data = cv_store[request.cv_id]
154
+
155
+ logger.info(f"Generating tailored CV for {request.job_title} at {request.company_name}")
156
+
157
+ # Generate tailored CV (JSON)
158
+ result = ai_service.generate_tailored_cv_json(
159
+ cv_text=cv_data["text"],
160
+ cv_skills=cv_data["skills"],
161
+ job_title=request.job_title,
162
+ job_description=request.job_description,
163
+ company_name=request.company_name,
164
+ ats_analysis_json=request.ats_analysis,
165
+ contact_info=cv_data.get("contact"),
166
+ candidate_name=cv_data.get("name")
167
+ )
168
+
169
+ if not result["success"]:
170
+ logger.error(f"CV generation failed: {result.get('error')}")
171
+ raise HTTPException(status_code=500, detail=result.get("error", "Generation failed"))
172
+
173
+ # usage of gap analysis for preview text
174
+ preview_text = result["data"].get("gap_analysis", "")
175
+ if not preview_text:
176
+ preview_text = "CV Optimized Successfully. Ready for PDF download."
177
+
178
+ # Also include the JSON structure as text if user wants?
179
+ # Let's just return gap analysis which is cleaner.
180
+
181
+ return {
182
+ "success": True,
183
+ "tailored_cv": preview_text,
184
+ "job_title": request.job_title,
185
+ "company": request.company_name
186
+ }
187
+
188
+ @router.post("/generate/pdf")
189
+ async def generate_cv_pdf(request: CVGenerateRequest):
190
+ """
191
+ Generate a tailored CV as a downloadable PDF using direct JSON->PDF generation
192
+ This is faster and more reliable than LaTeX compilation.
193
+ """
194
+ if request.cv_id not in cv_store:
195
+ raise HTTPException(status_code=404, detail="CV not found or expired. Please upload again.")
196
+
197
+ cv_data = cv_store[request.cv_id]
198
+
199
+ logger.info(f"Generating PDF CV (JSON method) for {request.job_title} at {request.company_name}")
200
+
201
+ # Generate tailored CV content as JSON
202
+ result = ai_service.generate_tailored_cv_json(
203
+ cv_text=cv_data["text"],
204
+ cv_skills=cv_data["skills"],
205
+ job_title=request.job_title,
206
+ job_description=request.job_description,
207
+ company_name=request.company_name,
208
+ ats_analysis_json=request.ats_analysis,
209
+ contact_info=cv_data.get("contact"),
210
+ candidate_name=cv_data.get("name")
211
+ )
212
+
213
+ if not result["success"]:
214
+ logger.error(f"CV generation failed: {result.get('error')}")
215
+ raise HTTPException(status_code=500, detail=result.get("error", "Generation failed"))
216
+
217
+ # Generate PDF directly from JSON (ReportLab)
218
+ pdf_bytes = pdf_generator.generate_cv_from_json(result["data"])
219
+
220
+ # Sanitize filename
221
+ safe_company = "".join(c if c.isalnum() or c in " -_" else "_" for c in request.company_name)
222
+ safe_title = "".join(c if c.isalnum() or c in " -_" else "_" for c in request.job_title)
223
+
224
+ filename = f"CV_{safe_company}_{safe_title}.pdf".replace(" ", "_")
225
+ logger.info(f"PDF generated successfully: {filename}")
226
+
227
+ # Extract improvement metrics
228
+ imp_report = result["data"].get("improvement_report", {})
229
+ new_score = imp_report.get("new_score", "")
230
+ skills_added = ",".join(imp_report.get("skills_added", []))
231
+
232
+ headers = {
233
+ "Content-Disposition": f"attachment; filename={filename}",
234
+ "Access-Control-Expose-Headers": "X-New-Score, X-Skills-Added", # Critical for CORS
235
+ "X-New-Score": str(new_score),
236
+ "X-Skills-Added": skills_added
237
+ }
238
+
239
+ return Response(
240
+ content=pdf_bytes,
241
+ media_type="application/pdf",
242
+ headers=headers
243
+ )
244
+
245
+ @router.post("/analyze")
246
+ async def analyze_cv_fit(request: CVGenerateRequest):
247
+ """
248
+ Analyze CV fit for a specific job
249
+
250
+ Returns detailed gap analysis including:
251
+ - Match score (0-100)
252
+ - Missing skills
253
+ - Matching skills
254
+ - Advice on how to fit
255
+ """
256
+ if request.cv_id not in cv_store:
257
+ raise HTTPException(status_code=404, detail="CV not found or expired. Please upload again.")
258
+
259
+ cv_data = cv_store[request.cv_id]
260
+
261
+ logger.info(f"Analyzing CV fit for {request.job_title} at {request.company_name}")
262
+
263
+ # Perform deep analysis
264
+ result = ai_service.analyze_fit(
265
+ cv_text=cv_data["text"],
266
+ cv_skills=cv_data["skills"],
267
+ job_title=request.job_title,
268
+ job_description=request.job_description
269
+ )
270
+
271
+ if not result["success"]:
272
+ logger.error(f"CV analysis failed: {result.get('error')}")
273
+ raise HTTPException(status_code=500, detail=result.get("error", "Analysis failed"))
274
+
275
+ return {
276
+ "success": True,
277
+ "analysis": result["data"],
278
+ "detected_industry": cv_data.get("detected_industry", "General")
279
+ }
backend/routers/jobs.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Jobs Router - API endpoints for job search
3
+ """
4
+ from fastapi import APIRouter, Query
5
+ from typing import Optional
6
+ from services.job_service import job_service
7
+
8
+ router = APIRouter()
9
+
10
+ from pydantic import BaseModel
11
+
12
+ class SearchFilters(BaseModel):
13
+ fullTime: bool = False
14
+ partTime: bool = False
15
+ permanent: bool = False
16
+ contract: bool = False
17
+
18
+ class SearchRequest(BaseModel):
19
+ query: str
20
+ location: Optional[str] = None
21
+ country: str = "gb"
22
+ filters: SearchFilters
23
+
24
+ @router.get("/search")
25
+ async def search_jobs_get(
26
+ q: str = Query(..., description="Search keywords"),
27
+ location: Optional[str] = Query(None),
28
+ country: str = Query("gb"),
29
+ page: int = Query(1, ge=1),
30
+ limit: int = Query(100, ge=1, le=200),
31
+ fullTime: Optional[bool] = Query(None),
32
+ partTime: Optional[bool] = Query(None),
33
+ permanent: Optional[bool] = Query(None),
34
+ contract: Optional[bool] = Query(None)
35
+ ):
36
+ """Legacy GET support for search"""
37
+ return await job_service.search_jobs(
38
+ query=q, location=location, country=country, page=page, results_per_page=limit,
39
+ full_time=fullTime, part_time=partTime, permanent=permanent, contract=contract
40
+ )
41
+
42
+ @router.post("/search")
43
+ async def search_jobs(request: SearchRequest):
44
+ """
45
+ Search for jobs using Reed API via POST request
46
+ """
47
+ result = await job_service.search_jobs(
48
+ query=request.query,
49
+ location=request.location,
50
+ country=request.country,
51
+ page=1, # Default to page 1 for new searches
52
+ results_per_page=100,
53
+ # Map filters
54
+ full_time=request.filters.fullTime,
55
+ part_time=request.filters.partTime,
56
+ permanent=request.filters.permanent,
57
+ contract=request.filters.contract
58
+ )
59
+ return result
60
+
61
+ @router.get("/countries")
62
+ async def get_supported_countries():
63
+ """Get list of supported countries for job search"""
64
+ return {
65
+ "countries": [
66
+ {"code": "gb", "name": "United Kingdom", "flag": "πŸ‡¬πŸ‡§"},
67
+ {"code": "us", "name": "United States", "flag": "πŸ‡ΊπŸ‡Έ"}
68
+ ]
69
+ }
backend/services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Services package
backend/services/ai_service.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI Service - LLM Integration for CV Tailoring
3
+ Uses Azure AI Inference SDK with GitHub Models
4
+ """
5
+ import os
6
+ import json
7
+ from typing import Dict, Any, Optional
8
+ from azure.ai.inference import ChatCompletionsClient
9
+ from azure.ai.inference.models import SystemMessage, UserMessage
10
+ from azure.core.credentials import AzureKeyCredential
11
+ import logging
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ class AIService:
16
+ """Service for AI-powered CV tailoring"""
17
+
18
+ def __init__(self):
19
+ self.token = os.getenv("GITHUB_TOKEN", "")
20
+ self.endpoint = "https://models.inference.ai.azure.com"
21
+ # Priority list: Try best model first, then fallback
22
+ self.models = ["gpt-4o", "gpt-4o-mini"]
23
+
24
+ if not self.token:
25
+ logger.warning("⚠️ GITHUB_TOKEN not found. AI features will be unavailable.")
26
+ self.client = None
27
+ else:
28
+ # Disable automatic retries - we handle fallback ourselves
29
+ self.client = ChatCompletionsClient(
30
+ endpoint=self.endpoint,
31
+ credential=AzureKeyCredential(self.token),
32
+ retry_total=0 # Don't wait on rate limits, fail fast
33
+ )
34
+
35
+ def _call_llm(self, system_prompt: str, user_prompt: str, json_mode: bool = False) -> Dict[str, Any]:
36
+ """
37
+ Make a call to the LLM with automatic fallback support
38
+ """
39
+ if not self.client:
40
+ return {
41
+ "success": False,
42
+ "error": "AI service not configured. Set GITHUB_TOKEN environment variable."
43
+ }
44
+
45
+ # Prepare the prompt once
46
+ full_user_prompt = user_prompt
47
+ if json_mode:
48
+ full_user_prompt += "\n\nIMPORTANT: Output ONLY valid JSON."
49
+
50
+ last_error = None
51
+
52
+ # Try models in order
53
+ for model in self.models:
54
+ logger.info(f"πŸ€– Attempting AI call with model: {model}...")
55
+ try:
56
+ response = self.client.complete(
57
+ messages=[
58
+ SystemMessage(content=system_prompt),
59
+ UserMessage(content=full_user_prompt)
60
+ ],
61
+ model=model,
62
+ temperature=0.7,
63
+ max_tokens=4000,
64
+ timeout=10 # Fail fast (10s)
65
+ )
66
+
67
+ content = response.choices[0].message.content
68
+ logger.info(f"βœ… Success with {model}")
69
+
70
+ # Parse JSON if requested
71
+ if json_mode:
72
+ try:
73
+ # Robust JSON extraction
74
+ clean_content = content.strip()
75
+
76
+ # specific fix for markdown code blocks
77
+ if "```json" in clean_content:
78
+ clean_content = clean_content.split("```json")[1].split("```")[0].strip()
79
+ elif "```" in clean_content:
80
+ clean_content = clean_content.split("```")[1].split("```")[0].strip()
81
+
82
+ # If deeper cleanup is needed (finding first { and last })
83
+ start_idx = clean_content.find('{')
84
+ end_idx = clean_content.rfind('}')
85
+
86
+ if start_idx != -1 and end_idx != -1:
87
+ clean_content = clean_content[start_idx:end_idx+1]
88
+
89
+ parsed_content = json.loads(clean_content)
90
+ return {
91
+ "success": True,
92
+ "data": parsed_content
93
+ }
94
+ except json.JSONDecodeError:
95
+ logger.error(f"❌ JSON Parse Error with {model}")
96
+ return {
97
+ "success": False,
98
+ "error": "Failed to parse AI response as JSON",
99
+ "raw_content": content
100
+ }
101
+
102
+ # Success (Text mode)
103
+ return {
104
+ "success": True,
105
+ "content": content,
106
+ "usage": {
107
+ "prompt_tokens": response.usage.prompt_tokens,
108
+ "completion_tokens": response.usage.completion_tokens
109
+ }
110
+ }
111
+
112
+ except Exception as e:
113
+ last_error = str(e)
114
+ logger.warning(f"⚠️ AI Error with {model}: {last_error}")
115
+
116
+ # Auth error - Stop immediately
117
+ if "401" in last_error or "unauthorized" in last_error.lower():
118
+ return {
119
+ "success": False,
120
+ "error": "Invalid API token. Please check your GITHUB_TOKEN."
121
+ }
122
+
123
+ # Rate limit or timeout - Continue to next model
124
+ continue
125
+
126
+ # If we get here, all models failed
127
+ logger.error("❌ All models failed.")
128
+ return {
129
+ "success": False,
130
+ "error": "Server is busy due to high demand. Please help keep the servers running: https://buymeacoffee.com/manojthapa",
131
+ "details": last_error
132
+ }
133
+
134
+ def analyze_fit(
135
+ self,
136
+ cv_text: str,
137
+ cv_skills: list,
138
+ job_title: str,
139
+ job_description: str
140
+ ) -> Dict[str, Any]:
141
+ """
142
+ Perform deep analysis of CV fit for a job
143
+ Returns score, missing skills, and advice
144
+ """
145
+ system_prompt = """You are an expert ATS (Applicant Tracking System) scoring engine and technical recruiter. Your task is to calculate a match score between a CV and a job description while checking domain/background compatibility.
146
+
147
+ ═══════════════════════════════════════════════════════════
148
+ STEP 0: CONTENT VALIDATION (CRITICAL FIRST STEP)
149
+ ═══════════════════════════════════════════════════════════
150
+
151
+ First, analyze the candidate input to ensure it is actually a professional CV/Resume.
152
+ A valid CV must contain:
153
+ - Professional experience or history
154
+ - Educational background
155
+ - Skills or qualifications
156
+ - Contact information (or placeholders for it)
157
+
158
+ REJECT the document if it appears to be:
159
+ - A recipe, lyrics, fan fiction, or creative writing
160
+ - Source code or logs (unless part of a portfolio in a CV context)
161
+ - A generic article, blog post, or essay
162
+ - Random incoherent text
163
+
164
+ IF REJECTED:
165
+ - Set "is_valid_cv": false
166
+ - Provide a polite "rejection_reason" explaining why.
167
+ - You can stop processing further steps.
168
+
169
+ IF VALID:
170
+ - Set "is_valid_cv": true
171
+ - Proceed to Step 1.
172
+
173
+ ═══════════════════════════════════════════════════════════
174
+ STEP 1: EXTRACT JOB-SPECIFIC REQUIREMENTS
175
+ ═══════════════════════════════════════════════════════════
176
+
177
+ Before scoring, you MUST first analyze the job description and extract:
178
+
179
+ a) JOB TITLE: What is the exact role? (e.g., "Senior Data Engineer", "Marketing Coordinator")
180
+
181
+ b) REQUIRED KEYWORDS (Hard Skills):
182
+ - Technical skills mentioned (e.g., Python, AWS, SQL, React, Excel)
183
+ - Tools/software explicitly named (e.g., Salesforce, Docker, Tableau)
184
+ - Certifications required (e.g., PMP, AWS Certified, CPA)
185
+ - Programming languages, frameworks, platforms
186
+ - Extract 15-25 keywords minimum
187
+
188
+ c) REQUIRED QUALIFICATIONS:
189
+ - Years of experience needed (e.g., "3-5 years", "entry-level")
190
+ - Education level (e.g., "Bachelor's in Computer Science", "MBA preferred")
191
+ - Industry experience (e.g., "fintech background", "healthcare experience")
192
+
193
+ d) SOFT SKILLS & COMPETENCIES:
194
+ - Leadership, communication, teamwork, problem-solving
195
+ - Methodologies (e.g., Agile, Scrum, Design Thinking)
196
+
197
+ e) KEYWORD FREQUENCY ANALYSIS:
198
+ - Count how many times each keyword appears in job description
199
+ - Keywords mentioned 3+ times are CRITICAL and weighted higher
200
+ - Mark keywords as "Must-Have" (in required section) vs "Nice-to-Have" (in preferred section)
201
+
202
+ ═══════════════════════════════════════════════════════════
203
+ STEP 2: DOMAIN & BACKGROUND MATCH CHECK (CRITICAL)
204
+ ═══════════════════════════════════════════════════════════
205
+
206
+ Determine if the candidate's educational/professional background is compatible with the target role:
207
+
208
+ CATEGORY: "complete_mismatch"
209
+ - The candidate's core field is FUNDAMENTALLY DIFFERENT from the job
210
+ - Examples:
211
+ * CS graduate β†’ Nursing role
212
+ * Mechanical Engineer β†’ Software Developer (no coding experience)
213
+ * Arts major β†’ Civil Engineering
214
+ * Marketing graduate β†’ Data Scientist (no technical background)
215
+ - ACTION: Set final score 15-29. Focus advice on applying for roles matching their actual background.
216
+
217
+ CATEGORY: "weak_match"
218
+ - The candidate's field is RELATED but lacks specific experience/projects
219
+ - Examples:
220
+ * CS graduate β†’ ML Engineer (but no ML projects)
221
+ * Fresh graduate β†’ Senior role
222
+ * Backend developer β†’ DevOps Engineer (no cloud/infrastructure experience)
223
+ * Junior developer β†’ Lead Engineer
224
+ - ACTION: Set final score 30-59. Provide specific project recommendations to build required skills.
225
+
226
+ CATEGORY: "good_match"
227
+ - The candidate's background aligns well with the role
228
+ - Examples:
229
+ * Software Engineer β†’ Senior Software Engineer
230
+ * Junior Data Analyst β†’ Data Analyst
231
+ * Frontend Developer β†’ React Developer
232
+ - ACTION: Calculate normal ATS score 60-100. Focus on optimization tips.
233
+
234
+ ═══════════════════════════════════════════════════════════
235
+ STEP 3: CALCULATE ATS MATCH SCORE
236
+ ═══════════════════════════════════════════════════════════
237
+
238
+ Now score the CV using these 6 factors:
239
+
240
+ 1. KEYWORD MATCH SCORE (Weight: 35%)
241
+
242
+ CRITICAL DISTINCTION:
243
+ - A skill is PRESENT if it appears ANYWHERE in the CV (skills section, experience, projects, education)
244
+ - Variants count as matches: "PostgreSQL" = "SQL", "React.js" = "React", "ML" = "Machine Learning"
245
+ - Do NOT require project experience to count a skill as present
246
+
247
+ SCORING LOGIC:
248
+ - If skill appears in CV = MATCHED (full points)
249
+ - If skill does NOT appear anywhere in CV = MISSING
250
+
251
+ Formula: (Matched Keywords / Total Extracted Keywords) Γ— 100
252
+ - Critical keywords (mentioned 3+ times) weighted 1.5x
253
+ - Keywords in Professional Summary or Skills section get 1.2x bonus
254
+
255
+ IMPORTANT:
256
+ - missing_skills array should ONLY contain skills NOT mentioned anywhere in CV
257
+ - If "SQL" is in CV skills but no SQL projects exist, it's still MATCHED (not missing)
258
+ - Project recommendations are SEPARATE from missing skills
259
+
260
+ 2. JOB TITLE ALIGNMENT SCORE (Weight: 20%)
261
+ - Compare CV's current/recent titles with extracted target role
262
+ - Exact match = 100%
263
+ - Similar title = 80%
264
+ - Related field = 50%
265
+ - Unrelated = 20%
266
+
267
+ 3. SKILLS COVERAGE SCORE (Weight: 25%)
268
+ - Must-have skills from job description = 2 points each
269
+ - Nice-to-have skills = 1 point each
270
+ - Calculate: (Points Earned / Max Points) Γ— 100
271
+ - Skill is counted if it appears ANYWHERE in CV
272
+
273
+ 4. EXPERIENCE LEVEL ALIGNMENT (Weight: 10%)
274
+ - Compare CV years vs job requirement
275
+ - Match or exceed = 100%
276
+ - Within 1 year = 80%
277
+ - 2+ years difference = 50%
278
+
279
+ 5. EDUCATION & CERTIFICATION MATCH (Weight: 5%)
280
+ - Required degree present = 100%
281
+ - Related degree = 70%
282
+ - Certifications match = +10% each
283
+
284
+ 6. FORMATTING & READABILITY SCORE (Weight: 5%)
285
+ - Standard sections = +20%
286
+ - Clean structure = +20%
287
+ - Contact info = +20%
288
+ - Bullet points = +20%
289
+ - Date formatting = +20%
290
+
291
+ OVERALL SCORE = Sum of weighted scores
292
+
293
+ IMPORTANT: Respect domain_match category limits:
294
+ - complete_mismatch: final score must be 15-29
295
+ - weak_match: final score must be 30-59
296
+ - good_match: final score can be 60-100
297
+
298
+ ═══════════════════════════════════════════════════════════
299
+ STEP 4: GENERATE RECOMMENDATIONS
300
+ ═══════════════════════════════════════════════════════════
301
+
302
+ Based on domain_match:
303
+
304
+ IF "complete_mismatch":
305
+ - Clearly state the field mismatch in summary
306
+ - Recommend roles matching their actual background
307
+ - NO project recommendations (wrong field entirely)
308
+
309
+ IF "weak_match":
310
+ - Provide 3-5 SPECIFIC, BUILDABLE projects ONLY for skills that are MISSING from CV
311
+ - Example: If CV has "SQL" listed but no projects, DON'T recommend SQL project
312
+ - Example: If CV lacks "Docker" entirely, THEN recommend "Build a Dockerized application"
313
+ - Suggest certifications for missing skills
314
+ - Recommend entry-level roles or internships
315
+
316
+ IF "good_match":
317
+ - Focus on keyword optimization
318
+ - Suggest rephrasing bullet points to emphasize existing skills more strongly
319
+ - Recommend adding quantifiable achievements for skills already present
320
+ - Highlight sections needing strengthening
321
+
322
+ PROJECT RECOMMENDATION RULES:
323
+ 1. ONLY recommend projects for skills in the "missing_skills" array
324
+ 2. Do NOT recommend projects for skills already listed in CV
325
+ 3. Instead, for present skills without strong evidence, recommend:
326
+ - "Add quantifiable achievements for your SQL work"
327
+ - "Highlight your React projects more prominently"
328
+ - "Include metrics for your AWS experience"
329
+ """
330
+
331
+ user_prompt = f"""Analyze this candidate for the role of {job_title}.
332
+
333
+ INPUTS PROVIDED:
334
+ 1. Candidate CV Content:
335
+ Skills: {', '.join(cv_skills)}
336
+ Experience Snippet: {cv_text[:3000]}
337
+
338
+ 2. Job Description:
339
+ {job_description[:4000]}
340
+
341
+ ═══════════════════════════════════════════════════════════
342
+ OUTPUT FORMAT (JSON)
343
+ ═══════════════════════════════════════════════════════════
344
+
345
+ {{
346
+ "is_valid_cv": true,
347
+ "rejection_reason": null,
348
+ "job_analysis": {{
349
+ "job_title": "extracted role title",
350
+ "required_experience": "e.g., 5+ years",
351
+ "required_education": "e.g., Bachelor's in Computer Science",
352
+ "extracted_keywords": {{
353
+ "must_have": ["keyword1", "keyword2"],
354
+ "nice_to_have": ["keyword3", "keyword4"],
355
+ "critical_keywords": ["keyword1"]
356
+ }},
357
+ "soft_skills": ["Agile", "Communication"]
358
+ }},
359
+ "domain_match": "complete_mismatch | weak_match | good_match",
360
+ "overall_ats_score": <number 0-100>,
361
+ "score_interpretation": "Brief explanation based on score and domain match",
362
+ "breakdown": {{
363
+ "keyword_match": {{
364
+ "score": 0-100,
365
+ "weight": 35,
366
+ "weighted_score": 0,
367
+ "matched_keywords": ["list of matched"],
368
+ "missing_critical_keywords": ["list of critical missing"]
369
+ }},
370
+ "job_title_alignment": {{
371
+ "score": 0-100,
372
+ "weight": 20,
373
+ "weighted_score": 0,
374
+ "details": "explanation of title match"
375
+ }},
376
+ "skills_coverage": {{
377
+ "score": 0-100,
378
+ "weight": 25,
379
+ "weighted_score": 0,
380
+ "must_have_present": 0,
381
+ "must_have_total": 0,
382
+ "nice_to_have_present": 0,
383
+ "nice_to_have_total": 0
384
+ }},
385
+ "experience_level": {{
386
+ "score": 0-100,
387
+ "weight": 10,
388
+ "weighted_score": 0,
389
+ "cv_experience": "extracted from CV",
390
+ "required_experience": "extracted from job"
391
+ }},
392
+ "education_certification": {{
393
+ "score": 0-100,
394
+ "weight": 5,
395
+ "weighted_score": 0,
396
+ "details": "explanation"
397
+ }},
398
+ "formatting_readability": {{
399
+ "score": 0-100,
400
+ "weight": 5,
401
+ "weighted_score": 0
402
+ }}
403
+ }},
404
+ "matching_skills": ["ONLY skills that appear BOTH in the job description AND in the CV - these are the overlapping skills"],
405
+ "missing_skills": ["Skills required by the job description that are NOT found in the CV"],
406
+ "advice": [
407
+ "tip1",
408
+ "tip2",
409
+ "tip3"
410
+ ],
411
+ "project_recommendations": [
412
+ "ONLY projects for skills in missing_skills array",
413
+ "Example: 'Build X using [missing skill] to demonstrate competency'",
414
+ "Do NOT recommend projects for skills already in CV"
415
+ ],
416
+ "summary": "1-2 sentence summary including domain match status and key takeaway",
417
+ "score_guide": {{
418
+ "80-100": "Excellent - strong ATS pass likelihood",
419
+ "60-79": "Moderate - optimization recommended",
420
+ "below_60": "Low - significant tailoring needed"
421
+ }}
422
+ }}
423
+
424
+ CRITICAL RULES:
425
+ 1. If domain_match is "complete_mismatch", summary MUST state: "Your background in [X] does not align with this [Y] role. We recommend applying for positions matching your [X] expertise."
426
+ 2. matching_skills = INTERSECTION of (job requirements AND CV skills) - ONLY skills that the job asks for AND the candidate has
427
+ 3. missing_skills = skills required by job description that are NOT found anywhere in the CV
428
+ 4. DO NOT put CV skills that are irrelevant to the job in matching_skills (e.g., Python skills for a teaching job)
429
+ 5. For complete_mismatch: matching_skills should be empty or only contain soft skills, missing_skills contains job requirements
430
+ 6. project_recommendations = ONLY for truly missing skills, NOT for skills already listed
431
+ 7. For skills present but without strong evidence, use advice array to suggest better highlighting
432
+ 8. Critical keywords (mentioned 3+ times) MUST be highlighted in recommendations
433
+ 9. Final score MUST respect domain_match limits (complete=15-29, weak=30-59, good=60-100)
434
+ 10. Skill variants count as matches across ALL domains:
435
+ - Tech: SQL/PostgreSQL/MySQL β†’ "SQL matched", JavaScript/TypeScript β†’ "JS matched"
436
+ - Healthcare: RN/Registered Nurse/Nursing License β†’ "Nursing matched"
437
+ - Finance: Excel/Google Sheets/Spreadsheets β†’ "Spreadsheet skills matched"
438
+ - Education: Teaching/Instruction/Training/Tutoring β†’ "Teaching matched"
439
+ - Marketing: SEO/SEM/Search Marketing β†’ "Search Marketing matched"
440
+ - General: Always treat synonyms and related certifications as matching skills
441
+ """
442
+
443
+ result = self._call_llm(system_prompt, user_prompt, json_mode=True)
444
+
445
+ if result.get("success") and result.get("data"):
446
+ # Validation Check
447
+ if result["data"].get("is_valid_cv") is False:
448
+ # User requested specific static message
449
+ return {
450
+ "success": False,
451
+ "error": "The provided document does not appear to be a CV or Resume. Please upload a valid CV or Resume."
452
+ }
453
+
454
+ # Ensure compatibility with frontend by mapping 'overall_ats_score' to 'score'
455
+ if result.get("success") and result.get("data") and "overall_ats_score" in result["data"]:
456
+ result["data"]["score"] = result["data"]["overall_ats_score"]
457
+
458
+ return result
459
+
460
+ def generate_tailored_cv_json(
461
+ self,
462
+ cv_text: str,
463
+ cv_skills: list,
464
+ job_title: str,
465
+ job_description: str,
466
+ company_name: str,
467
+ ats_analysis_json: Dict[str, Any] = None,
468
+ contact_info: Dict[str, Any] = None,
469
+ candidate_name: str = None
470
+ ) -> Dict[str, Any]:
471
+ """
472
+ Generate a tailored CV in structured JSON format for direct PDF generation
473
+ """
474
+ system_prompt = """You are an expert CV optimization specialist. Your task is to create a highly optimized, ATS-friendly CV in structured JSON format for PDF generation using Python ReportLab.
475
+
476
+ CONTEXT: You will receive ATS scoring results that identified missing keywords, domain match status, and recommendations. Use these insights to optimize the CV.
477
+
478
+ IMPORTANT CONSTRAINTS ABOUT EXPERIENCE AND PROJECTS:
479
+
480
+ - You must NOT invent or fabricate work experience, job titles, companies, dates, locations, or projects.
481
+ - You must NOT add artificial internships, freelance roles, or side projects not mentioned in the original CV.
482
+ - You must NOT fabricate certifications, degrees, or institutions.
483
+
484
+ WHEN EXPERIENCE/PROJECTS ARE WEAK OR LIMITED:
485
+
486
+ - Still optimize wording, structure, and clarity of existing content.
487
+ - Improve bullet points to be more outcome-focused using information already implied or present.
488
+ - Do NOT create new experience sections, projects, or roles to fill space.
489
+
490
+ HOW TO APPLY OPTIMIZATION:
491
+
492
+ - Only include roles, projects, and certifications from the original CV.
493
+ - You may:
494
+ * Reorder projects so most relevant appear first
495
+ * Merge or split bullets for clarity
496
+ * Strengthen language around real achievements
497
+ * Its very important to add all missing keywords from ATS analysis (if the skill/experience exists but wasn't mentioned)
498
+ - You may NOT:
499
+ * Add entirely new project entries or roles
500
+
501
+ If CV is under-experienced for the role, prioritize:
502
+ - Strong, honest Professional Summary highlighting learning mindset and real skills
503
+ - Well-structured Technical Skills section aligned with job description
504
+ - Clear education details and certifications
505
+
506
+ OPTIMIZATION REQUIREMENTS:
507
+
508
+ 1. Professional Summary:
509
+ - 2-3 sentences highlighting relevant skills and achievements
510
+ - CRITICAL: Do NOT use "seeking", "looking for", "aspiring to", "eager to apply", or mention company/role name
511
+ - State what the candidate IS, not what they WANT
512
+ - BAD: "Seeking a Software Engineer role at Company X..."
513
+ - GOOD: "Full-stack developer with 3+ years building scalable web applications using React and Node.js"
514
+
515
+ 2. Skills Section:
516
+ - REQUIRED: Keep ALL relevant skills from the original CV.
517
+ - PERMITTED: You MAY add critical missing keywords (e.g. "AWS", "CI/CD") to the list if they are standard for the role, effectively suggesting the user should list them.
518
+ - BUT: Do NOT invent Experience bullets to support them if the experience is missing. Just list the skill.
519
+ - Group into categories (Languages, Frameworks, Tools, Databases, Other)
520
+
521
+ 3. Experience Section:
522
+ - Use strong action verbs: "Engineered", "Optimized", "Architected", "Implemented", "Led"
523
+ - Add quantifiable achievements with metrics (%, numbers, timeframes)
524
+ - Incorporate job description keywords naturally
525
+ - Apply STAR method where possible
526
+
527
+ 4. Keywords:
528
+ - Strategically place job-specific keywords from ATS analysis
529
+ - Use 2-3 times throughout (natural distribution)
530
+ - Include both full forms and acronyms (e.g., "Machine Learning (ML)")
531
+
532
+ 5. ATS Compatibility:
533
+ - Standard section headings
534
+ - Clean structure, no complex formatting
535
+ - Bullet points concise (70-180 characters)
536
+ """
537
+
538
+ # Extract useful data from ATS analysis for the prompt
539
+ missing_critical = []
540
+ domain_match = "good_match"
541
+ if ats_analysis_json:
542
+ missing_critical = ats_analysis_json.get("breakdown", {}).get("keyword_match", {}).get("missing_critical_keywords", [])
543
+ domain_match = ats_analysis_json.get("domain_match", "good_match")
544
+
545
+ # Build explicit contact info section if provided
546
+ contact_section = ""
547
+ if contact_info or candidate_name:
548
+ contact_section = "\n\n4. EXTRACTED CONTACT INFORMATION (USE EXACTLY AS PROVIDED):\n"
549
+ if candidate_name:
550
+ contact_section += f" - Name: {candidate_name}\n"
551
+ if contact_info:
552
+ if contact_info.get("email"):
553
+ contact_section += f" - Email: {contact_info['email']}\n"
554
+ if contact_info.get("phone"):
555
+ contact_section += f" - Phone: {contact_info['phone']}\n"
556
+ if contact_info.get("linkedin"):
557
+ contact_section += f" - LinkedIn: {contact_info['linkedin']}\n"
558
+ contact_section += " IMPORTANT: Use the contact details above EXACTLY. Do NOT use placeholders.\n"
559
+
560
+ user_prompt = f"""INPUTS PROVIDED:
561
+
562
+ 1. ATS Scoring Results:
563
+ {str(ats_analysis_json)}
564
+
565
+ 2. Current CV:
566
+ {cv_text[:6000]}
567
+
568
+ 3. Target Job:
569
+ {job_title} at {company_name}
570
+ {job_description[:3000]}
571
+ {contact_section}
572
+
573
+ TASK: Using the ATS scoring results, optimize the CV to improve the score while maintaining honesty.
574
+
575
+ Pay special attention to:
576
+ - Missing critical keywords: {', '.join(missing_critical)}
577
+ - Domain match status: {domain_match}
578
+ - Recommendations from scoring analysis
579
+
580
+ OUTPUT JSON STRUCTURE (STANDARD CV ORDER):
581
+
582
+ {{
583
+ "header": {{
584
+ "name": "Full Name",
585
+ "email": "email@example.com",
586
+ "phone": "+XX-XXXXXXXXXX",
587
+ "location": "City, Country",
588
+ "linkedin": "LinkedIn URL (only if in original CV)",
589
+ "github": "GitHub URL (only if in original CV)"
590
+ }},
591
+ "summary": "2-3 sentence summary (NO 'seeking' or 'looking for' phrases)",
592
+ "education": [
593
+ {{
594
+ "degree": "Degree Title",
595
+ "institution": "University Name",
596
+ "location": "City, Country",
597
+ "dates": "Month Year - Month Year"
598
+ }}
599
+ ],
600
+ "skills": {{
601
+ // CHOOSE CATEGORIES BASED ON INDUSTRY. Examples:
602
+ // Tech: "languages", "frameworks", "tools", "databases", "cloud"
603
+ // Healthcare: "clinical_skills", "certifications", "software", "languages"
604
+ // Finance: "analytical", "software", "certifications", "languages"
605
+ // General: "technical", "software", "certifications", "soft_skills"
606
+
607
+ // Use 3-5 categories that fit the CV's industry. Omit empty categories.
608
+ "category_name": ["Skill1", "Skill2"]
609
+ }},
610
+ "experience": [
611
+ {{
612
+ "title": "Job Title",
613
+ "company": "Company Name",
614
+ "location": "City, Country",
615
+ "dates": "Month Year - Month Year",
616
+ "bullets": [
617
+ "Achievement with metrics and keywords",
618
+ "Achievement with quantifiable impact"
619
+ ]
620
+ }}
621
+ ],
622
+ "projects": [
623
+ {{
624
+ "name": "Project Name",
625
+ "technologies": "Tech1, Tech2",
626
+ "dates": "Month Year",
627
+ "description": "Description with impact and relevant technologies"
628
+ }}
629
+ ],
630
+ "certifications": [
631
+ {{
632
+ "name": "Certification Name",
633
+ "issuer": "Issuer Organization",
634
+ "year": "Year/Date"
635
+ }}
636
+ ],
637
+ "improvement_report": {{
638
+ "original_score": "Value from input",
639
+ "new_score": "Estimated new score (0-100) after adding missing keywords",
640
+ "skills_added": ["List of skills you successfully added to the CV"],
641
+ "remaining_gaps": ["List of skills/experience you could NOT add (e.g. requires specific project experience)"]
642
+ }}
643
+ }}
644
+
645
+ CRITICAL: HANDLING MISSING INFORMATION
646
+ - If original CV lacks a section, COMPLETELY OMIT that key
647
+ - NO empty arrays [], null values, or "N/A" placeholders
648
+ - Only include keys with real data
649
+
650
+ CRITICAL: CONSISTENCY CHECK
651
+ - Any skill listed in "skills_added" inside "improvement_report" MUST also be present in the relevant category within the "skills" object.
652
+ - Do NOT list a skill as added if you did not actually insert it into the CV content.
653
+ - If you cannot fit a skill naturally, do not list it as added.
654
+
655
+ SCORING RULES:
656
+ - If "missing_critical_keywords" was empty and you have optimized the phrasing/formatting, the new_score MUST be very high (95-100).
657
+ - Only deduct points if there are genuine gaps you could not fill.
658
+
659
+ Begin optimization now."""
660
+
661
+ result = self._call_llm(system_prompt, user_prompt, json_mode=True)
662
+
663
+ # Ensure compatibility with frontend
664
+ if result.get("success") and result.get("data") and ats_analysis_json:
665
+ # Inject the gap analysis summary for legacy frontend support
666
+ old_score = ats_analysis_json.get('overall_ats_score', 0)
667
+ new_score = result['data'].get('improvement_report', {}).get('new_score', 'N/A')
668
+ result["data"]["gap_analysis"] = f"Optimization Complete. Score improved from {old_score}% to {new_score}%."
669
+
670
+ return result
671
+
672
+ # Singleton instance
673
+ ai_service = AIService()
backend/services/cv_parser.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Universal CV Parser Service
3
+ Extracts text and skills from any domain/industry CV
4
+ """
5
+ import fitz # PyMuPDF
6
+ from docx import Document
7
+ import re
8
+ from typing import Dict, List, Any, Optional
9
+ import io
10
+ from datetime import datetime
11
+
12
+
13
+ import pytesseract
14
+ from pdf2image import convert_from_bytes
15
+
16
+ class CVParser:
17
+ """Service for parsing and extracting information from CVs (all industries)"""
18
+
19
+ # EXPANDED: Skills from ALL domains
20
+ UNIVERSAL_SKILLS = {
21
+ # === TECHNICAL/IT ===
22
+ # Programming
23
+ "python", "javascript", "typescript", "java", "c++", "c#", "go", "rust",
24
+ "ruby", "php", "swift", "kotlin", "scala", "r", "matlab", "sql",
25
+
26
+ # AI/ML
27
+ "machine learning", "deep learning", "neural networks", "nlp",
28
+ "computer vision", "tensorflow", "pytorch", "keras", "scikit-learn",
29
+ "transformers", "llm", "rag", "langchain",
30
+
31
+ # Web Dev
32
+ "react", "vue", "angular", "node.js", "express", "fastapi", "django",
33
+ "flask", "spring", "html", "css", "tailwind", "bootstrap",
34
+
35
+ # Cloud & DevOps
36
+ "aws", "azure", "gcp", "docker", "kubernetes", "terraform",
37
+ "jenkins", "ci/cd", "git", "github", "gitlab",
38
+
39
+ # Databases
40
+ "postgresql", "mysql", "mongodb", "redis", "elasticsearch",
41
+ "dynamodb", "firebase", "sqlite", "oracle",
42
+
43
+ # === HEALTHCARE ===
44
+ "patient care", "clinical documentation", "hipaa", "emr", "ehr",
45
+ "medical terminology", "vital signs", "cpr", "bls", "acls",
46
+ "patient assessment", "medication administration", "iv therapy",
47
+ "wound care", "electronic health records", "medical coding",
48
+ "icd-10", "healthcare compliance",
49
+
50
+ # === MARKETING ===
51
+ "seo", "google analytics", "content strategy", "social media marketing",
52
+ "email marketing", "ppc", "google ads", "facebook ads", "hubspot",
53
+ "marketing automation", "conversion optimization", "a/b testing",
54
+ "content creation", "copywriting", "brand management", "crm",
55
+ "salesforce", "market research",
56
+
57
+ # === FINANCE/ACCOUNTING ===
58
+ "financial modeling", "gaap", "ifrs", "financial analysis",
59
+ "budgeting", "forecasting", "excel", "quickbooks", "sap",
60
+ "accounts payable", "accounts receivable", "audit", "tax preparation",
61
+ "risk assessment", "bloomberg terminal", "financial reporting",
62
+ "variance analysis", "cost accounting", "cpa", "cfa",
63
+
64
+ # === SALES ===
65
+ "lead generation", "cold calling", "relationship building",
66
+ "negotiation", "sales pipeline", "quota achievement", "crm software",
67
+ "b2b sales", "b2c sales", "account management", "upselling",
68
+ "customer retention", "sales presentations",
69
+
70
+ # === HUMAN RESOURCES ===
71
+ "recruitment", "talent acquisition", "onboarding", "employee relations",
72
+ "performance management", "hris", "workday", "adp", "payroll",
73
+ "benefits administration", "training and development", "hr compliance",
74
+ "labor law", "employee engagement", "compensation analysis",
75
+
76
+ # === PROJECT MANAGEMENT ===
77
+ "agile", "scrum", "kanban", "waterfall", "project planning",
78
+ "risk management", "stakeholder management", "budget management",
79
+ "resource allocation", "jira", "confluence", "ms project",
80
+ "pmp", "prince2", "gantt charts",
81
+
82
+ # === DESIGN ===
83
+ "adobe photoshop", "adobe illustrator", "figma", "sketch",
84
+ "ui design", "ux design", "wireframing", "prototyping",
85
+ "user research", "visual design", "graphic design", "branding",
86
+ "typography", "color theory", "adobe xd",
87
+
88
+ # === EDUCATION ===
89
+ "curriculum development", "lesson planning", "classroom management",
90
+ "student assessment", "differentiated instruction", "educational technology",
91
+ "learning management systems", "google classroom", "canvas",
92
+ "special education", "tesol", "esl", "teaching certification",
93
+
94
+ # === LEGAL ===
95
+ "contract law", "litigation", "legal research", "legal writing",
96
+ "case management", "westlaw", "lexisnexis", "compliance",
97
+ "corporate law", "intellectual property", "employment law",
98
+ "regulatory compliance", "due diligence",
99
+
100
+ # === MANUFACTURING/ENGINEERING ===
101
+ "autocad", "solidworks", "cad", "lean manufacturing", "six sigma",
102
+ "quality control", "iso 9001", "osha", "process improvement",
103
+ "supply chain", "inventory management", "plc programming",
104
+ "cnc", "welding", "blueprint reading",
105
+
106
+ # === SOFT SKILLS (Universal) ===
107
+ "leadership", "communication", "problem solving", "teamwork",
108
+ "time management", "critical thinking", "adaptability",
109
+ "conflict resolution", "presentation skills", "analytical skills",
110
+ "attention to detail", "customer service", "multitasking",
111
+ "decision making", "collaboration", "interpersonal skills"
112
+ }
113
+
114
+ # Keep education keywords
115
+ EDUCATION_KEYWORDS = [
116
+ "bachelor", "master", "phd", "doctorate", "degree", "university",
117
+ "college", "bsc", "msc", "ba", "ma", "mba", "engineering",
118
+ "diploma", "certification", "associate", "graduate",
119
+ "a level", "a-level", "gcse", "school", "sixth form", "academy"
120
+ ]
121
+
122
+ def parse_pdf(self, file_content: bytes) -> Dict[str, Any]:
123
+ """Parse PDF with OCR fallback for image-only files"""
124
+ try:
125
+ doc = fitz.open(stream=file_content, filetype="pdf")
126
+ text = ""
127
+ for page in doc:
128
+ text += page.get_text()
129
+ page_count = len(doc)
130
+ doc.close()
131
+
132
+ # OCR Fallback: If text is minimal (<100 chars), try OCR
133
+ if len(text.strip()) < 100:
134
+ print("Low text density detected in PDF. Attempting OCR...")
135
+ try:
136
+ images = convert_from_bytes(file_content)
137
+ ocr_text = ""
138
+ for i, image in enumerate(images):
139
+ # Preprocessing: Convert to grayscale
140
+ gray_image = image.convert('L')
141
+ ocr_text += pytesseract.image_to_string(gray_image) + "\n"
142
+
143
+ if len(ocr_text.strip()) > len(text.strip()):
144
+ text = ocr_text
145
+ print(f"OCR successful. Extracted {len(text)} characters.")
146
+ except Exception as ocr_e:
147
+ print(f"OCR failed: {str(ocr_e)}")
148
+ # Continue with whatever text we found originally
149
+
150
+ return {
151
+ "success": True,
152
+ "text": text,
153
+ "page_count": page_count,
154
+ "format": "pdf"
155
+ }
156
+ except Exception as e:
157
+ return {
158
+ "success": False,
159
+ "error": str(e),
160
+ "text": "",
161
+ "format": "pdf"
162
+ }
163
+
164
+ def parse_docx(self, file_content: bytes) -> Dict[str, Any]:
165
+ """Parse DOCX - unchanged"""
166
+ try:
167
+ doc = Document(io.BytesIO(file_content))
168
+ text = ""
169
+ for paragraph in doc.paragraphs:
170
+ text += paragraph.text + "\n"
171
+ for table in doc.tables:
172
+ for row in table.rows:
173
+ for cell in row.cells:
174
+ text += cell.text + " "
175
+ text += "\n"
176
+ return {
177
+ "success": True,
178
+ "text": text,
179
+ "paragraph_count": len(doc.paragraphs),
180
+ "format": "docx"
181
+ }
182
+ except Exception as e:
183
+ return {
184
+ "success": False,
185
+ "error": str(e),
186
+ "text": "",
187
+ "format": "docx"
188
+ }
189
+
190
+ def parse_file(self, file_content: bytes, filename: str) -> Dict[str, Any]:
191
+ """Parse any file - unchanged"""
192
+ filename_lower = filename.lower()
193
+ if filename_lower.endswith(".pdf"):
194
+ return self.parse_pdf(file_content)
195
+ elif filename_lower.endswith(".docx"):
196
+ return self.parse_docx(file_content)
197
+ elif filename_lower.endswith(".txt"):
198
+ try:
199
+ text = file_content.decode("utf-8")
200
+ return {"success": True, "text": text, "format": "txt"}
201
+ except Exception as e:
202
+ return {"success": False, "error": str(e), "text": "", "format": "txt"}
203
+ else:
204
+ return {
205
+ "success": False,
206
+ "error": f"Unsupported file format: {filename}",
207
+ "text": "",
208
+ "format": "unknown"
209
+ }
210
+
211
+ def extract_skills(self, text: str) -> List[str]:
212
+ """
213
+ Extract skills from ANY domain CV
214
+ Now works for technical, healthcare, marketing, finance, etc.
215
+ """
216
+ text_lower = text.lower()
217
+ found_skills = []
218
+
219
+ for skill in self.UNIVERSAL_SKILLS:
220
+ if " " not in skill:
221
+ # Single-word skill: use word boundary
222
+ pattern = rf'\b{re.escape(skill)}\b'
223
+ if re.search(pattern, text_lower):
224
+ found_skills.append(skill.title())
225
+ else:
226
+ # Multi-word skill: substring match
227
+ if skill in text_lower:
228
+ found_skills.append(skill.title())
229
+
230
+ return sorted(set(found_skills))
231
+
232
+ def extract_contact_info(self, text: str) -> Dict[str, Optional[str]]:
233
+ """Extract contact info - unchanged"""
234
+ email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
235
+ email_match = re.search(email_pattern, text)
236
+
237
+ # Improved phone regex: supports +44-XXXX-XXXXXX, +1 (234) 567-8901, etc.
238
+ phone_pattern = r'(?:\+\d{1,3}[\s.-]?)?(?:\(?\d{2,4}\)?[\s.-]?)?\d{3,4}[\s.-]?\d{3,4}[\s.-]?\d{0,4}'
239
+ phone_match = re.search(phone_pattern, text)
240
+
241
+ linkedin_pattern = r'linkedin\.com/in/[\w-]+'
242
+ linkedin_match = re.search(linkedin_pattern, text.lower())
243
+
244
+ return {
245
+ "email": email_match.group() if email_match else None,
246
+ "phone": phone_match.group() if phone_match else None,
247
+ "linkedin": linkedin_match.group() if linkedin_match else None
248
+ }
249
+
250
+ def extract_education(self, text: str) -> List[str]:
251
+ """Extract education - unchanged"""
252
+ lines = text.split("\n")
253
+ education_lines = []
254
+
255
+ for line in lines:
256
+ line_lower = line.lower().strip()
257
+ if any(keyword in line_lower for keyword in self.EDUCATION_KEYWORDS):
258
+ if len(line.strip()) > 10:
259
+ education_lines.append(line.strip())
260
+
261
+ return education_lines[:5]
262
+
263
+ def extract_name(self, text: str) -> Optional[str]:
264
+ """
265
+ Extract candidate name from CV (usually in first 3 lines)
266
+ """
267
+ lines = [line.strip() for line in text.split("\n") if line.strip()]
268
+
269
+ for line in lines[:3]:
270
+ # Skip lines with email or phone numbers
271
+ if "@" in line or re.search(r'\d{3}[-.\s]?\d{3}', line):
272
+ continue
273
+
274
+ words = line.split()
275
+ # Name is typically 2-4 words, less than 50 chars
276
+ if 2 <= len(words) <= 4 and len(line) < 50:
277
+ # Check if mostly alphabetic characters
278
+ alpha_ratio = sum(c.isalpha() or c.isspace() for c in line) / len(line)
279
+ if alpha_ratio > 0.8:
280
+ return line
281
+
282
+ return None
283
+
284
+ def extract_experience_years(self, text: str) -> Optional[float]:
285
+ """
286
+ Calculate total years of work experience from date ranges
287
+ Looks for patterns like: "2020 - 2023" or "Jan 2020 - Present"
288
+ """
289
+ # Pattern matches: 2020 - 2023, 2020 - Present, etc.
290
+ date_pattern = r'(\d{4})\s*[-–—]\s*(?:(\d{4})|present|current)'
291
+ matches = re.findall(date_pattern, text.lower())
292
+
293
+ if not matches:
294
+ return None
295
+
296
+ current_year = datetime.now().year
297
+ total_years = 0
298
+
299
+ for match in matches:
300
+ start_year = int(match[0])
301
+ end_year = int(match[1]) if match[1] else current_year
302
+ years = end_year - start_year
303
+
304
+ # Sanity check: experience should be 0-50 years
305
+ if 0 <= years <= 50:
306
+ total_years += years
307
+
308
+ return round(total_years, 1) if total_years > 0 else None
309
+
310
+ def detect_industry(self, skills: List[str], text: str) -> str:
311
+ """
312
+ Detect primary industry/domain based on skills and CV content
313
+ """
314
+ text_lower = text.lower()
315
+
316
+ industry_keywords = {
317
+ "Software Engineering": ["python", "javascript", "react", "api", "git", "docker", "programming"],
318
+ "Data Science/AI": ["machine learning", "tensorflow", "data analysis", "statistics", "data science"],
319
+ "Healthcare": ["patient care", "clinical", "medical", "hipaa", "emr", "nursing", "healthcare"],
320
+ "Marketing": ["seo", "marketing", "content", "social media", "google analytics", "campaign"],
321
+ "Finance": ["financial", "accounting", "gaap", "audit", "excel", "budgeting", "finance"],
322
+ "Design": ["photoshop", "figma", "ui", "ux", "design", "visual", "graphic"],
323
+ "HR": ["recruitment", "hr", "hiring", "onboarding", "employee", "human resources"],
324
+ "Sales": ["sales", "crm", "lead generation", "b2b", "negotiation", "revenue"],
325
+ "Education": ["teaching", "curriculum", "classroom", "student", "education", "instructor"]
326
+ }
327
+
328
+ scores = {}
329
+ for industry, keywords in industry_keywords.items():
330
+ score = sum(1 for keyword in keywords if keyword in text_lower)
331
+ scores[industry] = score
332
+
333
+ # Return industry with highest score, or "General" if score too low
334
+ detected = max(scores, key=scores.get)
335
+ return detected if scores[detected] >= 2 else "General"
336
+
337
+ def analyze_cv(self, file_content: bytes, filename: str) -> Dict[str, Any]:
338
+ """
339
+ Fully analyze a CV file
340
+ NOW INCLUDES: name, experience years, and industry detection
341
+ """
342
+ parse_result = self.parse_file(file_content, filename)
343
+
344
+ if not parse_result["success"]:
345
+ return {
346
+ "success": False,
347
+ "error": parse_result.get("error", "Failed to parse file")
348
+ }
349
+
350
+ text = parse_result["text"]
351
+ skills = self.extract_skills(text)
352
+ contact = self.extract_contact_info(text)
353
+ education = self.extract_education(text)
354
+ name = self.extract_name(text)
355
+ experience_years = self.extract_experience_years(text)
356
+ industry = self.detect_industry(skills, text)
357
+
358
+ return {
359
+ "success": True,
360
+ "filename": filename,
361
+ "format": parse_result["format"],
362
+ "text": text,
363
+ "text_length": len(text),
364
+ "name": name,
365
+ "skills": skills,
366
+ "skills_count": len(skills),
367
+ "contact": contact,
368
+ "education": education,
369
+ "experience_years": experience_years,
370
+ "detected_industry": industry
371
+ }
372
+
373
+
374
+ # Singleton
375
+ cv_parser = CVParser()
backend/services/job_service.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Job Service - Reed API Integration
3
+ Searches jobs from Reed.co.uk API (UK's largest job board)
4
+ """
5
+ import httpx
6
+ import os
7
+ import base64
8
+ from typing import Optional, List, Dict, Any
9
+ from datetime import datetime
10
+ import logging
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class JobService:
16
+ """Service for fetching jobs from Reed API"""
17
+
18
+ BASE_URL = "https://www.reed.co.uk/api/1.0"
19
+
20
+ def __init__(self):
21
+ self.api_key = os.getenv("REED_API_KEY", "")
22
+
23
+ if not self.api_key:
24
+ logger.warning("⚠️ REED_API_KEY not found. Job search will not work.")
25
+
26
+ credentials = f"{self.api_key}:"
27
+ self.auth_header = base64.b64encode(credentials.encode()).decode()
28
+
29
+ def _check_api_key(self) -> Optional[Dict[str, Any]]:
30
+ """Check if API key exists, return error dict if not"""
31
+ if not self.api_key:
32
+ return {
33
+ "success": False,
34
+ "error": "API Key missing. Please set REED_API_KEY in environment variables.",
35
+ "jobs": []
36
+ }
37
+ return None
38
+
39
+ async def search_jobs(
40
+ self,
41
+ query: str,
42
+ location: Optional[str] = None,
43
+ country: str = "gb",
44
+ page: int = 1,
45
+ results_per_page: int = 100,
46
+ full_time: Optional[bool] = None,
47
+ part_time: Optional[bool] = None,
48
+ permanent: Optional[bool] = None,
49
+ contract: Optional[bool] = None
50
+ ) -> Dict[str, Any]:
51
+ """
52
+ Search for jobs using Reed API
53
+
54
+ Args:
55
+ query: Search keywords (e.g., "Machine Learning Engineer")
56
+ location: Location filter (e.g., "London", "Manchester")
57
+ country: Country code (Reed is UK only)
58
+ page: Page number
59
+ results_per_page: Number of results per page (max 100)
60
+ full_time: Filter for full-time positions
61
+ part_time: Filter for part-time positions
62
+ permanent: Filter for permanent roles
63
+ contract: Filter for contract positions
64
+
65
+ Returns:
66
+ Dictionary with job results and metadata
67
+ """
68
+ # Validate API key first
69
+ error_check = self._check_api_key()
70
+ if error_check:
71
+ return error_check
72
+
73
+ # Reed API has a hard limit of 100 results per request
74
+ MAX_PER_REQUEST = 100
75
+
76
+ # Calculate how many requests we need
77
+ # If user asks for 200, we need 2 requests of 100
78
+ total_needed = results_per_page
79
+
80
+ all_jobs = []
81
+ seen_job_ids = set() # Track IDs to prevent duplicates
82
+ total_found = 0
83
+
84
+ # Current offset
85
+ # e.g. Page 1, limit 200 -> start at 0
86
+ current_skip = (page - 1) * results_per_page
87
+
88
+ fetched_count = 0
89
+
90
+ try:
91
+ async with httpx.AsyncClient(timeout=30.0) as client:
92
+ while fetched_count < total_needed:
93
+ # Determine how many to take in this batch
94
+ remaining = total_needed - fetched_count
95
+ take = min(remaining, MAX_PER_REQUEST)
96
+
97
+ params = {
98
+ "keywords": query,
99
+ "resultsToTake": take,
100
+ "resultsToSkip": current_skip + fetched_count
101
+ }
102
+
103
+ if location:
104
+ params["locationName"] = location
105
+ params["distanceFromLocation"] = "0" # Strict location search (must be string for some APIs)
106
+
107
+ # Add Reed API filters
108
+ if full_time is not None:
109
+ params["fullTime"] = str(full_time).lower()
110
+ if part_time is not None:
111
+ params["partTime"] = str(part_time).lower()
112
+ if permanent is not None:
113
+ params["permanent"] = str(permanent).lower()
114
+ if contract is not None:
115
+ params["contract"] = str(contract).lower()
116
+
117
+ headers = {
118
+ "Authorization": f"Basic {self.auth_header}"
119
+ }
120
+
121
+ response = await client.get(
122
+ f"{self.BASE_URL}/search",
123
+ params=params,
124
+ headers=headers
125
+ )
126
+ response.raise_for_status()
127
+ data = response.json()
128
+
129
+ batch_jobs = data.get("results", [])
130
+ total_found = data.get("totalResults", 0) # This is the global total
131
+
132
+ if not batch_jobs:
133
+ break # No more jobs available
134
+
135
+ # Deduplicate and add
136
+ for job in batch_jobs:
137
+ job_id = str(job.get("jobId"))
138
+
139
+ # Strict filtering: Reed API can be fuzzy
140
+
141
+ # Strict location filtering: Reed API is fuzzy, so we verify client-side
142
+ if location:
143
+ job_location = job.get("locationName", "").lower()
144
+ search_location = location.lower()
145
+ # If the job's location does NOT contain the search term, skip it
146
+ if search_location not in job_location:
147
+ continue
148
+
149
+ if job_id and job_id not in seen_job_ids:
150
+ seen_job_ids.add(job_id)
151
+ all_jobs.append(job)
152
+
153
+ fetched_count += len(batch_jobs)
154
+
155
+ # If we got fewer than we asked for, we've reached the end
156
+ if len(batch_jobs) < take:
157
+ break
158
+
159
+ logger.info(f"Reed API: Fetched {len(all_jobs)} unique jobs (Total available: {total_found})")
160
+
161
+ return {
162
+ "success": True,
163
+ "count": total_found,
164
+ "page": page,
165
+ "results_per_page": results_per_page,
166
+ "jobs": [self._normalize_job(job) for job in all_jobs]
167
+ }
168
+
169
+ except httpx.HTTPStatusError as e:
170
+ logger.error(f"Reed API HTTP Error: {e.response.status_code}")
171
+ return {
172
+ "success": False,
173
+ "error": f"Reed API Error: {e.response.status_code}",
174
+ "jobs": []
175
+ }
176
+ except httpx.TimeoutException:
177
+ logger.error("Reed API timeout")
178
+ return {
179
+ "success": False,
180
+ "error": "Request timeout. Please try again.",
181
+ "jobs": []
182
+ }
183
+ except Exception as e:
184
+ logger.error(f"Reed API error: {str(e)}")
185
+ return {
186
+ "success": False,
187
+ "error": f"Error fetching jobs: {str(e)}",
188
+ "jobs": []
189
+ }
190
+
191
+ async def get_job_details(self, job_id: str) -> Dict[str, Any]:
192
+ """
193
+ Get detailed information about a specific job
194
+
195
+ Args:
196
+ job_id: Reed job ID
197
+
198
+ Returns:
199
+ Dictionary with full job details
200
+ """
201
+ # FIX: Check API key
202
+ error_check = self._check_api_key()
203
+ if error_check:
204
+ return error_check
205
+
206
+ headers = {
207
+ "Authorization": f"Basic {self.auth_header}"
208
+ }
209
+
210
+ try:
211
+ async with httpx.AsyncClient(timeout=30.0) as client:
212
+ response = await client.get(
213
+ f"{self.BASE_URL}/jobs/{job_id}",
214
+ headers=headers
215
+ )
216
+ response.raise_for_status()
217
+ job = response.json()
218
+
219
+ logger.info(f"Reed API: Fetched details for job {job_id}")
220
+
221
+ return {
222
+ "success": True,
223
+ "job": self._normalize_job(job, full_details=True)
224
+ }
225
+ except httpx.HTTPStatusError as e:
226
+ logger.error(f"Reed API error fetching job {job_id}: {e.response.status_code}")
227
+ return {
228
+ "success": False,
229
+ "error": f"Job not found or API error: {e.response.status_code}"
230
+ }
231
+ except Exception as e:
232
+ logger.error(f"Error fetching job details: {str(e)}")
233
+ return {
234
+ "success": False,
235
+ "error": f"Error: {str(e)}"
236
+ }
237
+
238
+ def _normalize_job(self, job: Dict[str, Any], full_details: bool = False) -> Dict[str, Any]:
239
+ """Normalize Reed job data to our standard format"""
240
+
241
+ salary_min = job.get("minimumSalary")
242
+ salary_max = job.get("maximumSalary")
243
+ salary_display = self._format_salary(salary_min, salary_max)
244
+
245
+ raw_date = job.get("date", "")
246
+ formatted_date = self._format_date(raw_date)
247
+
248
+ contract_time = "Unknown"
249
+ if job.get("fullTime") and job.get("partTime"):
250
+ contract_time = "Full Time / Part Time"
251
+ elif job.get("fullTime"):
252
+ contract_time = "Full Time"
253
+ elif job.get("partTime"):
254
+ contract_time = "Part Time"
255
+
256
+ normalized = {
257
+ "id": str(job.get("jobId", "")),
258
+ "title": job.get("jobTitle", "Unknown Title"),
259
+ "company": job.get("employerName", "Unknown Company"),
260
+ "location": job.get("locationName", "Unknown Location"),
261
+ "description": job.get("jobDescription", ""),
262
+ "salary_min": salary_min,
263
+ "salary_max": salary_max,
264
+ "salary_display": salary_display,
265
+ "contract_type": job.get("contractType", ""),
266
+ "contract_time": contract_time,
267
+ "category": job.get("jobType", ""),
268
+ "redirect_url": job.get("jobUrl", ""),
269
+ "created": formatted_date,
270
+ "date_display": raw_date,
271
+ "expiration_date": job.get("expirationDate", ""),
272
+ "posted_by": job.get("employerName", ""),
273
+ "source": "Reed.co.uk"
274
+ }
275
+
276
+ if full_details:
277
+ normalized["applications"] = job.get("applications", 0)
278
+ normalized["employer_profile_url"] = job.get("employerProfileUrl", "")
279
+
280
+ return normalized
281
+
282
+ def _format_date(self, date_str: str) -> str:
283
+ """Convert Reed date format (DD/MM/YYYY) to ISO format"""
284
+ if not date_str:
285
+ return ""
286
+ try:
287
+ parsed = datetime.strptime(date_str, "%d/%m/%Y")
288
+ return parsed.isoformat()
289
+ except ValueError:
290
+ try:
291
+ parsed = datetime.strptime(date_str, "%Y-%m-%d")
292
+ return parsed.isoformat()
293
+ except ValueError:
294
+ return date_str
295
+
296
+ def _format_salary(
297
+ self,
298
+ salary_min: Optional[float],
299
+ salary_max: Optional[float]
300
+ ) -> str:
301
+ """Format salary range for display"""
302
+ if not salary_min and not salary_max:
303
+ return "Salary not specified"
304
+
305
+ if salary_min and salary_max:
306
+ # Heuristics for salary duration
307
+ if salary_min < 100:
308
+ unit = "per hour"
309
+ elif salary_min < 1000:
310
+ unit = "per day"
311
+ else:
312
+ unit = "per annum"
313
+
314
+ if salary_min == salary_max:
315
+ return f"Β£{salary_min:,.2f} {unit}" if unit == "per hour" else f"Β£{salary_min:,.0f} {unit}"
316
+ return f"Β£{salary_min:,.2f} - Β£{salary_max:,.2f} {unit}" if unit == "per hour" else f"Β£{salary_min:,.0f} - Β£{salary_max:,.0f} {unit}"
317
+ elif salary_min:
318
+ if salary_min < 100:
319
+ unit = "per hour"
320
+ elif salary_min < 1000:
321
+ unit = "per day"
322
+ else:
323
+ unit = "per annum"
324
+ return f"From Β£{salary_min:,.0f} {unit}"
325
+ else:
326
+ # If only max is present, we guess based on max
327
+ if salary_max < 100:
328
+ unit = "per hour"
329
+ elif salary_max < 1000:
330
+ unit = "per day"
331
+ else:
332
+ unit = "per annum"
333
+ return f"Up to Β£{salary_max:,.0f} {unit}"
334
+
335
+
336
+ # Singleton instance
337
+ job_service = JobService()
backend/services/pdf_generator.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PDF Generator Service
3
+ Creates professional PDF documents for CVs and cover letters
4
+ """
5
+ from reportlab.lib.pagesizes import A4
6
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
7
+ from reportlab.lib.units import inch
8
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Flowable, Table, TableStyle
9
+ from reportlab.lib.colors import HexColor, black
10
+ from reportlab.lib.enums import TA_LEFT, TA_JUSTIFY, TA_RIGHT
11
+ import io
12
+ from typing import Optional
13
+
14
+ class HorizontalLine(Flowable):
15
+ """Draws a horizontal line"""
16
+ def __init__(self, width=450):
17
+ Flowable.__init__(self)
18
+ self.width = width
19
+
20
+ def draw(self):
21
+ self.canv.setStrokeColor(HexColor('#000000'))
22
+ self.canv.setLineWidth(0.5)
23
+ self.canv.line(0, 0, self.width, 0)
24
+
25
+ class PDFGenerator:
26
+ """Service for generating PDF documents"""
27
+
28
+ def __init__(self):
29
+ self.styles = getSampleStyleSheet()
30
+
31
+ # Custom styles - Latex-like
32
+ self.styles.add(ParagraphStyle(
33
+ name='CVTitle',
34
+ parent=self.styles['Heading1'],
35
+ fontName='Times-Bold',
36
+ fontSize=24,
37
+ leading=28,
38
+ textColor=black,
39
+ alignment=TA_LEFT,
40
+ spaceAfter=6
41
+ ))
42
+
43
+ self.styles.add(ParagraphStyle(
44
+ name='CVSection',
45
+ parent=self.styles['Heading2'],
46
+ fontName='Times-Bold',
47
+ fontSize=12,
48
+ leading=14,
49
+ textColor=black,
50
+ alignment=TA_LEFT,
51
+ spaceBefore=12,
52
+ spaceAfter=4,
53
+ textTransform='uppercase'
54
+ ))
55
+
56
+ self.styles.add(ParagraphStyle(
57
+ name='CVBody',
58
+ parent=self.styles['Normal'],
59
+ fontName='Times-Roman',
60
+ fontSize=10,
61
+ leading=12,
62
+ textColor=black,
63
+ alignment=TA_LEFT
64
+ ))
65
+
66
+ self.styles.add(ParagraphStyle(
67
+ name='CVBullet',
68
+ parent=self.styles['Normal'],
69
+ fontName='Times-Roman',
70
+ fontSize=10,
71
+ leading=12,
72
+ textColor=black,
73
+ alignment=TA_LEFT,
74
+ leftIndent=15,
75
+ firstLineIndent=0,
76
+ spaceAfter=2
77
+ ))
78
+
79
+ # Right aligned style for dates
80
+ self.styles.add(ParagraphStyle(
81
+ name='CVDate',
82
+ parent=self.styles['Normal'],
83
+ fontName='Times-Roman',
84
+ fontSize=10,
85
+ leading=12,
86
+ textColor=black,
87
+ alignment=TA_RIGHT
88
+ ))
89
+
90
+ def generate_cv_from_json(self, data: dict) -> bytes:
91
+ """
92
+ Generate a professional CV PDF for ANY domain/industry.
93
+ Adapts section titles and structure based on content.
94
+ """
95
+ buffer = io.BytesIO()
96
+
97
+ doc = SimpleDocTemplate(
98
+ buffer,
99
+ pagesize=A4,
100
+ rightMargin=0.4*inch,
101
+ leftMargin=0.4*inch,
102
+ topMargin=0.4*inch,
103
+ bottomMargin=0.4*inch
104
+ )
105
+
106
+ flowables = []
107
+ styles = self.styles
108
+ available_width = 7.27 * inch
109
+
110
+ # Helper functions
111
+ def add_split_header(left_text, right_text, is_bold_left=True):
112
+ p_left = Paragraph(left_text, styles['CVBody'])
113
+ p_right = Paragraph(right_text if right_text else "", styles['CVDate'])
114
+
115
+ t = Table(
116
+ [[p_left, p_right]],
117
+ colWidths=[available_width * 0.75, available_width * 0.25]
118
+ )
119
+ t.setStyle(TableStyle([
120
+ ('VALIGN', (0,0), (-1,-1), 'TOP'),
121
+ ('LEFTPADDING', (0,0), (-1,-1), 0),
122
+ ('RIGHTPADDING', (0,0), (-1,-1), 0),
123
+ ('BOTTOMPADDING', (0,0), (-1,-1), 0),
124
+ ('TOPPADDING', (0,0), (-1,-1), 0),
125
+ ]))
126
+ flowables.append(t)
127
+
128
+ def add_section(title):
129
+ flowables.append(Paragraph(title.upper(), styles['CVSection']))
130
+ flowables.append(HorizontalLine(width=510))
131
+ flowables.append(Spacer(1, 4))
132
+
133
+ # 1. HEADER
134
+ header = data.get("header", {})
135
+ if header.get("name"):
136
+ name_style = ParagraphStyle(
137
+ 'HeaderName', parent=styles['CVTitle'], alignment=1, fontSize=24, spaceAfter=4
138
+ )
139
+ flowables.append(Paragraph(header["name"], name_style))
140
+
141
+ contact_parts = []
142
+ if header.get("email"): contact_parts.append(header["email"])
143
+ if header.get("phone"): contact_parts.append(header["phone"])
144
+ if header.get("location"): contact_parts.append(header["location"])
145
+ if header.get("linkedin"): contact_parts.append("LinkedIn")
146
+ if header.get("github"): contact_parts.append("GitHub")
147
+
148
+ contact_info = " | ".join(contact_parts)
149
+ contact_style = ParagraphStyle(
150
+ 'HeaderContact', parent=styles['Normal'], alignment=1, fontSize=10
151
+ )
152
+ flowables.append(Paragraph(contact_info, contact_style))
153
+ flowables.append(Spacer(1, 8))
154
+
155
+ # 2. PROFESSIONAL SUMMARY
156
+ if data.get("summary"):
157
+ add_section("Professional Summary")
158
+ flowables.append(Paragraph(data["summary"], styles['CVBody']))
159
+ flowables.append(Spacer(1, 6))
160
+
161
+ # 3. EDUCATION (Moved up as standard for all CVs)
162
+ education = data.get("education", [])
163
+ if education:
164
+ add_section("Education")
165
+ for edu in education:
166
+ uni_text = f"<b>{edu.get('institution', '')}</b>"
167
+ if edu.get('location'):
168
+ uni_text += f", {edu['location']}"
169
+
170
+ flowables.append(Paragraph(uni_text, styles['CVBody']))
171
+
172
+ degree_text = f"<i>{edu.get('degree', '')}</i>"
173
+ date_text = edu.get('dates', '')
174
+ add_split_header(degree_text, date_text)
175
+ flowables.append(Spacer(1, 6))
176
+
177
+ # 4. SKILLS (UNIVERSAL - adapts to any skill categories)
178
+ skills = data.get("skills", {})
179
+ if skills:
180
+ # Dynamic section title based on content
181
+ add_section("Core Competencies")
182
+
183
+ # Handle ANY skill category names (not just technical)
184
+ for category, skill_list in skills.items():
185
+ if skill_list: # Only show non-empty categories
186
+ # Capitalize category name nicely
187
+ category_display = category.replace("_", " ").title()
188
+ skill_text = f"<b>{category_display}:</b> {', '.join(skill_list)}"
189
+ flowables.append(Paragraph(skill_text, styles['CVBody']))
190
+
191
+ flowables.append(Spacer(1, 6))
192
+
193
+ # 5. WORK EXPERIENCE
194
+ experience = data.get("experience", [])
195
+ if experience:
196
+ add_section("Professional Experience")
197
+ for job in experience:
198
+ title_text = f"<b>{job.get('title', '')}</b>"
199
+ date_text = job.get('dates', '')
200
+ add_split_header(title_text, date_text)
201
+
202
+ company_text = job.get('company', '')
203
+ if job.get('location'):
204
+ company_text += f" | <i>{job['location']}</i>"
205
+
206
+ flowables.append(Paragraph(company_text, styles['CVBody']))
207
+
208
+ bullets = job.get("bullets", [])
209
+ for bullet in bullets:
210
+ flowables.append(Paragraph(f"β€’ {bullet}", styles['CVBullet']))
211
+
212
+ flowables.append(Spacer(1, 8))
213
+
214
+ # 6. PROJECTS (OPTIONAL - only include if present)
215
+ projects = data.get("projects", [])
216
+ if projects:
217
+ add_section("Projects")
218
+ for proj in projects:
219
+ name_text = f"<b>{proj.get('name', '')}</b>"
220
+ if proj.get('technologies'):
221
+ name_text += f" | <i>{proj['technologies']}</i>"
222
+
223
+ date_text = proj.get('dates', '')
224
+ add_split_header(name_text, date_text)
225
+
226
+ if proj.get('description'):
227
+ flowables.append(Paragraph(f"β€’ {proj['description']}", styles['CVBullet']))
228
+
229
+ flowables.append(Spacer(1, 4))
230
+
231
+ # 7. CERTIFICATIONS & LICENSES
232
+ certifications = data.get("certifications", [])
233
+ if certifications:
234
+ add_section("Certifications & Licenses")
235
+ # Logic to handle both Strings (Legacy) and Objects (New)
236
+ for cert in certifications:
237
+ if isinstance(cert, dict):
238
+ # Format: "Name - Issuer" (Left, No Bold) ... "Date" (Right)
239
+ name = cert.get('name', '')
240
+ issuer = cert.get('issuer', '')
241
+ year = cert.get('year', '')
242
+
243
+ # Construct Left Side: "Name - Issuer"
244
+ if issuer:
245
+ left_text = f"{name} - {issuer}"
246
+ else:
247
+ left_text = name
248
+
249
+ # Construct Right Side: just the date
250
+ right_text = year
251
+
252
+ add_split_header(left_text, right_text)
253
+ else:
254
+ # Fallback for strings
255
+ flowables.append(Paragraph(f"β€’ {cert}", styles['CVBody']))
256
+ flowables.append(Spacer(1, 4))
257
+
258
+ # 8. ADDITIONAL SECTIONS (if present in JSON)
259
+ # Allows for custom sections like "Publications", "Volunteer Work", etc.
260
+ additional_sections = data.get("additional_sections", {})
261
+ for section_title, section_content in additional_sections.items():
262
+ add_section(section_title)
263
+ if isinstance(section_content, list):
264
+ for item in section_content:
265
+ flowables.append(Paragraph(f"β€’ {item}", styles['CVBody']))
266
+ else:
267
+ flowables.append(Paragraph(section_content, styles['CVBody']))
268
+ flowables.append(Spacer(1, 4))
269
+
270
+ # Remove trailing spacers to prevent blank pages
271
+ while flowables and isinstance(flowables[-1], Spacer):
272
+ flowables.pop()
273
+
274
+ doc.build(flowables)
275
+ buffer.seek(0)
276
+ return buffer.getvalue()
277
+
278
+ # Singleton instance
279
+ pdf_generator = PDFGenerator()
frontend/index.html ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
8
+
9
+ <!-- Primary Meta Tags -->
10
+ <title>NeuroArc</title>
11
+ <meta name="title" content="NeuroArc - Smart Job Application Assistant" />
12
+ <meta name="description"
13
+ content="AI-powered job application assistant. Search jobs, analyze your CV fit, generate tailored resumes and cover letters in seconds." />
14
+ <meta name="keywords"
15
+ content="job search, CV generator, resume builder, cover letter, AI, career, job application" />
16
+ <meta name="author" content="Manoj Kumar Thapa" />
17
+
18
+ <!-- Theme Color -->
19
+ <meta name="theme-color" content="#0f0f1a" />
20
+ <meta name="color-scheme" content="dark" />
21
+
22
+ <!-- Open Graph / Facebook -->
23
+ <meta property="og:type" content="website" />
24
+ <meta property="og:url" content="https://cortexcv.vercel.app/" />
25
+ <meta property="og:title" content="NeuroArc - Smart Job Application Assistant" />
26
+ <meta property="og:description"
27
+ content="AI-powered job application assistant. Search jobs, analyze your CV fit, generate tailored resumes and cover letters." />
28
+ <meta property="og:image" content="/og-image.png" />
29
+
30
+ <!-- Twitter -->
31
+ <meta property="twitter:card" content="summary_large_image" />
32
+ <meta property="twitter:url" content="https://cortexcv.vercel.app/" />
33
+ <meta property="twitter:title" content="NeuroArc - Smart Job Application Assistant" />
34
+ <meta property="twitter:description"
35
+ content="AI-powered job application assistant. Search jobs, analyze your CV fit, generate tailored resumes and cover letters." />
36
+
37
+ <!-- Fonts -->
38
+ <link rel="preconnect" href="https://fonts.googleapis.com">
39
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
40
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
41
+ </head>
42
+
43
+ <body>
44
+ <div id="root"></div>
45
+ <script type="module" src="/src/main.jsx"></script>
46
+ </body>
47
+
48
+ </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,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "cortexcv-frontend",
3
+ "private": true,
4
+ "version": "1.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "preview": "vite preview"
10
+ },
11
+ "dependencies": {
12
+ "@react-spring/three": "^10.0.3",
13
+ "@react-three/drei": "^9.122.0",
14
+ "@react-three/fiber": "^8.18.0",
15
+ "@types/three": "^0.182.0",
16
+ "canvas-confetti": "^1.9.4",
17
+ "clsx": "^2.1.1",
18
+ "framer-motion": "^12.23.26",
19
+ "gsap": "^3.14.2",
20
+ "lucide-react": "^0.468.0",
21
+ "maath": "^0.10.8",
22
+ "react": "^18.3.1",
23
+ "react-countup": "^6.5.3",
24
+ "react-dom": "^18.3.1",
25
+ "react-dropzone": "^14.3.8",
26
+ "react-router-dom": "^7.11.0",
27
+ "tailwind-merge": "^3.4.0",
28
+ "three": "^0.160.1"
29
+ },
30
+ "devDependencies": {
31
+ "@types/react": "^18.3.12",
32
+ "@types/react-dom": "^18.3.1",
33
+ "@vitejs/plugin-react": "^4.3.4",
34
+ "autoprefixer": "^10.4.23",
35
+ "postcss": "^8.5.6",
36
+ "tailwindcss": "^3.4.16",
37
+ "vite": "^6.0.3"
38
+ }
39
+ }
frontend/public/bmc-icon.png ADDED
frontend/public/favicon.svg ADDED
frontend/public/textures/earth_clouds.png ADDED

Git LFS Details

  • SHA256: 7d3b82ef6b3feb506fc06f02a744aed3d864e23e7417075005f4082a7ff935a4
  • Pointer size: 131 Bytes
  • Size of remote file: 260 kB
frontend/public/textures/earth_daymap.jpg ADDED

Git LFS Details

  • SHA256: 2faa400d1eade3bc44caf6750d1b772bd9bbb6d87362c02bc7c3304e78fa0a9d
  • Pointer size: 131 Bytes
  • Size of remote file: 513 kB
frontend/public/textures/earth_normal.jpg ADDED

Git LFS Details

  • SHA256: 3fc43e9639c34e8223c4a871e3bdf5b2d52ee79f7e89ce3f28cba45d4cac031a
  • Pointer size: 131 Bytes
  • Size of remote file: 337 kB
frontend/public/textures/earth_specular.jpg ADDED

Git LFS Details

  • SHA256: 2df48906732d7a458b2d0a7cdec51a829262307c6bdee4cfdf079a4dd7c71c69
  • Pointer size: 131 Bytes
  • Size of remote file: 223 kB
frontend/public/textures/galaxy_bg.jpg ADDED

Git LFS Details

  • SHA256: 2faa400d1eade3bc44caf6750d1b772bd9bbb6d87362c02bc7c3304e78fa0a9d
  • Pointer size: 131 Bytes
  • Size of remote file: 513 kB
frontend/public/textures/iss_clean_texture.png ADDED

Git LFS Details

  • SHA256: 0a5a8221df11210e2bcc06ebc989ac1c99b12328ba7a13dde05f9febc04a2a2f
  • Pointer size: 131 Bytes
  • Size of remote file: 258 kB
frontend/public/textures/jupiter_map.jpg ADDED

Git LFS Details

  • SHA256: c40306b066f21da214e171f076aea57dedfdecff57dbffe095d01850a63c0581
  • Pointer size: 131 Bytes
  • Size of remote file: 144 kB
frontend/public/textures/mars_map.jpg ADDED

Git LFS Details

  • SHA256: 28caf896640bc4ce4ebb850da91eb335440e71aa7477bcf210c29c947faf5cf9
  • Pointer size: 132 Bytes
  • Size of remote file: 1.28 MB
frontend/public/textures/mercury_map.jpg ADDED

Git LFS Details

  • SHA256: 6cfa9244f703e177b605a4a959f7957269416af95a38e29d54662a4dfdafd1aa
  • Pointer size: 131 Bytes
  • Size of remote file: 418 kB
frontend/public/textures/moon_bump.jpg ADDED

Git LFS Details

  • SHA256: fcb0f1f5548e6e18d40063dd55c6aacd3daedf2407b181dab85b61e22bf9fe57
  • Pointer size: 131 Bytes
  • Size of remote file: 238 kB
frontend/public/textures/moon_map.jpg ADDED

Git LFS Details

  • SHA256: fcb0f1f5548e6e18d40063dd55c6aacd3daedf2407b181dab85b61e22bf9fe57
  • Pointer size: 131 Bytes
  • Size of remote file: 238 kB
frontend/public/textures/neptune_map.jpg ADDED

Git LFS Details

  • SHA256: 69beee1c505c3eee2e5765249c7b6357cdd4135075095ff682daca0bdbd785df
  • Pointer size: 132 Bytes
  • Size of remote file: 2 MB
frontend/public/textures/saturn_map.jpg ADDED

Git LFS Details

  • SHA256: 94610a6e483d8b6a1206d3a7929e12055537cd085f4247eaccd17fb9920562cf
  • Pointer size: 132 Bytes
  • Size of remote file: 2.31 MB
frontend/public/textures/sun_map.jpg ADDED

Git LFS Details

  • SHA256: 34436626c960da21d44df941b67d1f49ef680f732df9bda3ba26bb43935596a4
  • Pointer size: 131 Bytes
  • Size of remote file: 812 kB
frontend/public/textures/uranus_map.jpg ADDED

Git LFS Details

  • SHA256: 63709b92276037afa00e46129a8284aa38fef60ccbdaa18f4ade4f7411956709
  • Pointer size: 131 Bytes
  • Size of remote file: 100 kB
frontend/public/textures/venus_map.jpg ADDED

Git LFS Details

  • SHA256: f53eff50e0de2c0ffae02efa4f713ac9dca6e1a070b398f14dafa03982301d1c
  • Pointer size: 130 Bytes
  • Size of remote file: 15.5 kB
frontend/src/App.jsx ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useCallback, useEffect } from 'react';
2
+ import {
3
+ Brain,
4
+ CheckCircle,
5
+ AlertCircle,
6
+ Sparkles,
7
+ Loader2,
8
+ Coffee,
9
+ FileText,
10
+ Hammer,
11
+ RotateCcw
12
+ } from 'lucide-react';
13
+ import { motion, AnimatePresence } from 'framer-motion';
14
+ import JobSearch from './components/JobSearch';
15
+ import JobList from './components/JobList';
16
+ import CVAnalysis from './components/CVAnalysis';
17
+ import DocumentPreview from './components/DocumentPreview';
18
+ import Background3D from './components/Background3D';
19
+ import GenerationProgress from './components/GenerationProgress'; // Added this import based on the instruction's intent
20
+ import AboutUs from './components/AboutUs';
21
+
22
+ const API_BASE = '/api';
23
+
24
+ // Generation Progress Component
25
+ // Moved to its own file, but keeping the definition here for context if it's not yet moved.
26
+ // If GenerationProgress is imported from './components/GenerationProgress', this local definition should be removed.
27
+ // Assuming for now it's still defined here and the import instruction was a hint for future refactoring or a mistake.
28
+ // Based on the instruction's "Code Edit" snippet, it seems the user intended to import it.
29
+ // I will remove the local definition and assume it's imported.
30
+ // Generation Progress Component
31
+ // Moved to its own file.
32
+
33
+
34
+
35
+ function App() {
36
+ // Application state
37
+ // Steps: 'search', 'analysis', 'preview'
38
+ const [currentStep, setCurrentStep] = useState('search');
39
+
40
+ // Data states
41
+ const [jobs, setJobs] = useState([]);
42
+ const [selectedJob, setSelectedJob] = useState(null);
43
+ const [cvData, setCvData] = useState(null);
44
+ const [analysisResult, setAnalysisResult] = useState(null);
45
+ const [generatedDocs, setGeneratedDocs] = useState({ cv: null, coverLetter: null });
46
+
47
+ // UI states
48
+ const [loading, setLoading] = useState(false);
49
+ const [loadingType, setLoadingType] = useState('cv'); // 'cv' or 'cover_letter'
50
+ const [error, setError] = useState(null);
51
+ const [searchKey, setSearchKey] = useState(0); // Add key to force reset JobSearch
52
+ const [postedFilter, setPostedFilter] = useState('all'); // Lifted state for persistence
53
+ const [hasSearched, setHasSearched] = useState(false);
54
+
55
+ // Handle job search
56
+ // Initial load - fetch default jobs
57
+ useEffect(() => {
58
+ if (!hasSearched) {
59
+ handleJobSearch('', '', 'gb');
60
+ }
61
+ }, []);
62
+
63
+ // Handle job search
64
+ const handleJobSearch = useCallback(async (query, location, country, filters = {}) => {
65
+ setLoading(true);
66
+ setError(null);
67
+ setHasSearched(true); // Always set to true as we are searching
68
+
69
+ // If query is empty, we still fetch, but just clear the previous jobs first
70
+ setJobs([]);
71
+
72
+ try {
73
+ const params = new URLSearchParams({
74
+ q: query, // Can be empty string now
75
+ country: country,
76
+ limit: '200'
77
+ });
78
+
79
+ if (location) {
80
+ params.append('location', location);
81
+ }
82
+
83
+ // Add filter parameters
84
+ if (filters.fullTime) params.append('fullTime', 'true');
85
+ if (filters.partTime) params.append('partTime', 'true');
86
+ if (filters.permanent) params.append('permanent', 'true');
87
+ if (filters.contract) params.append('contract', 'true');
88
+ if (filters.graduate) params.append('graduate', 'true');
89
+
90
+ const response = await fetch(`${API_BASE}/jobs/search?${params}`);
91
+
92
+ if (!response.ok) {
93
+ const err = await response.json();
94
+ throw new Error(err.detail || 'Failed to search jobs');
95
+ }
96
+
97
+ const data = await response.json();
98
+ setJobs(data.jobs);
99
+ } catch (err) {
100
+ setError(err.message);
101
+ } finally {
102
+ setLoading(false);
103
+ }
104
+ }, []);
105
+
106
+ // Handle job selection
107
+ const handleSelectJob = useCallback((job) => {
108
+ setSelectedJob(job);
109
+ setCurrentStep('analysis');
110
+ }, []);
111
+
112
+ // Handle CV Analysis (Upload + Analyze)
113
+ const handleAnalysis = useCallback(async (file, job) => {
114
+ setError(null);
115
+
116
+ const formData = new FormData();
117
+ formData.append('file', file);
118
+
119
+ try {
120
+ // 1. Upload CV
121
+ const uploadRes = await fetch(`${API_BASE}/cv/upload`, {
122
+ method: 'POST',
123
+ body: formData
124
+ });
125
+
126
+ if (!uploadRes.ok) {
127
+ const err = await uploadRes.json();
128
+ throw new Error(err.detail || 'Failed to upload CV');
129
+ }
130
+
131
+ const uploadData = await uploadRes.json();
132
+ setCvData(uploadData);
133
+
134
+ // 2. Analyze Fit
135
+ const analyzeRes = await fetch(`${API_BASE}/cv/analyze`, {
136
+ method: 'POST',
137
+ headers: { 'Content-Type': 'application/json' },
138
+ body: JSON.stringify({
139
+ cv_id: uploadData.cv_id,
140
+ job_title: job.title,
141
+ job_description: job.description,
142
+ company_name: job.company
143
+ })
144
+ });
145
+
146
+ if (!analyzeRes.ok) {
147
+ const err = await analyzeRes.json();
148
+ throw new Error(err.detail || 'Analysis failed');
149
+ }
150
+
151
+ const analyzeData = await analyzeRes.json();
152
+ // Merge detected_industry into the analysis result for UI logic
153
+ setAnalysisResult({
154
+ ...analyzeData.analysis,
155
+ detected_industry: analyzeData.detected_industry
156
+ });
157
+ return analyzeData.analysis;
158
+
159
+ } catch (err) {
160
+ // setError(err.message); // Lets CVAnalysis handle the error locally
161
+ throw err;
162
+ }
163
+ }, []);
164
+
165
+ // Generate optimized CV
166
+ const handleOptimize = useCallback(async () => {
167
+ if (!cvData || !selectedJob) return;
168
+
169
+ setLoading(true);
170
+ setLoadingType('cv');
171
+ setError(null);
172
+ setCurrentStep('preview');
173
+
174
+ try {
175
+ // Generate PDF directly
176
+ const response = await fetch(`${API_BASE}/cv/generate/pdf`, {
177
+ method: 'POST',
178
+ headers: { 'Content-Type': 'application/json' },
179
+ body: JSON.stringify({
180
+ cv_id: cvData.cv_id,
181
+ job_title: selectedJob.title,
182
+ job_description: selectedJob.description,
183
+ company_name: selectedJob.company,
184
+ ats_analysis: analysisResult
185
+ })
186
+ });
187
+
188
+ if (!response.ok) {
189
+ const err = await response.json().catch(() => ({ detail: 'Failed to generate PDF' }));
190
+ throw new Error(err.detail || 'Failed to generate PDF');
191
+ }
192
+
193
+ // Extract improvement metrics from headers
194
+ const newScoreHeader = response.headers.get('X-New-Score');
195
+ const skillsAddedHeader = response.headers.get('X-Skills-Added');
196
+
197
+ if (newScoreHeader) {
198
+ const newScore = parseInt(newScoreHeader, 10);
199
+ const addedSkills = skillsAddedHeader ? skillsAddedHeader.split(',').map(s => s.trim()) : [];
200
+
201
+ // Update analysis result to reflect optimization
202
+ setAnalysisResult(prev => {
203
+ if (!prev) return null;
204
+
205
+ // Filter out added skills from missing list
206
+ const newMissing = prev.missing_skills.filter(
207
+ missing => !addedSkills.some(added => added.toLowerCase() === missing.toLowerCase())
208
+ );
209
+
210
+ // Add to matching list
211
+ const newMatching = [...prev.matching_skills, ...addedSkills];
212
+
213
+ return {
214
+ ...prev,
215
+ score: newScore,
216
+ summary: `Optimized! Score improved to ${newScore}%.`,
217
+ missing_skills: newMissing,
218
+ matching_skills: newMatching
219
+ };
220
+ });
221
+ }
222
+
223
+ const contentType = response.headers.get('content-type');
224
+
225
+ if (contentType && contentType.includes('application/pdf')) {
226
+ const blob = await response.blob();
227
+ const url = window.URL.createObjectURL(blob);
228
+ setGeneratedDocs(prev => ({ ...prev, cv: url, isPdf: true, textContent: null }));
229
+ } else {
230
+ const text = await response.text();
231
+ setGeneratedDocs(prev => ({ ...prev, cv: null, isPdf: false, textContent: text }));
232
+ }
233
+ } catch (err) {
234
+ setError(err.message);
235
+ setCurrentStep('analysis');
236
+ } finally {
237
+ setLoading(false);
238
+ }
239
+ }, [cvData, selectedJob, analysisResult]);
240
+
241
+ // Generate cover letter
242
+ const handleGenerateCoverLetter = useCallback(async () => {
243
+ if (!cvData || !selectedJob) return;
244
+
245
+ setLoading(true);
246
+ setLoadingType('cover_letter');
247
+ setError(null);
248
+
249
+ try {
250
+ const response = await fetch(`${API_BASE}/cv/cover-letter/pdf`, {
251
+ method: 'POST',
252
+ headers: { 'Content-Type': 'application/json' },
253
+ body: JSON.stringify({
254
+ cv_id: cvData.cv_id,
255
+ job_title: selectedJob.title,
256
+ job_description: selectedJob.description,
257
+ company_name: selectedJob.company
258
+ })
259
+ });
260
+
261
+ if (!response.ok) {
262
+ const err = await response.json().catch(() => ({ detail: 'Failed to generate cover letter' }));
263
+ throw new Error(err.detail || 'Failed to generate cover letter');
264
+ }
265
+
266
+ const blob = await response.blob();
267
+ const url = window.URL.createObjectURL(blob);
268
+ setGeneratedDocs(prev => ({ ...prev, coverLetter: url }));
269
+
270
+ } catch (err) {
271
+ setError(err.message);
272
+ } finally {
273
+ setLoading(false);
274
+ }
275
+ }, [cvData, selectedJob]);
276
+
277
+ // Download CV Handler
278
+ const handleDownloadCV = useCallback(() => {
279
+ if (!selectedJob) return;
280
+
281
+ try {
282
+ const a = document.createElement('a');
283
+
284
+ if (generatedDocs.isPdf && generatedDocs.cv) {
285
+ a.href = generatedDocs.cv;
286
+ a.download = `CV_${selectedJob.company.replace(/\s+/g, '_')}_${selectedJob.title.replace(/\s+/g, '_')}.pdf`;
287
+ } else if (generatedDocs.textContent) {
288
+ const blob = new Blob([generatedDocs.textContent], { type: 'application/x-tex' });
289
+ const url = window.URL.createObjectURL(blob);
290
+ a.href = url;
291
+ a.download = `CV_${selectedJob.company.replace(/\s+/g, '_')}_${selectedJob.title.replace(/\s+/g, '_')}.tex`;
292
+ } else {
293
+ return;
294
+ }
295
+
296
+ document.body.appendChild(a);
297
+ a.click();
298
+ document.body.removeChild(a);
299
+ } catch (err) {
300
+ setError(err.message);
301
+ }
302
+ }, [generatedDocs, selectedJob]);
303
+
304
+ // Reset to start
305
+ const handleReset = useCallback(() => {
306
+ setCvData(null);
307
+ setAnalysisResult(null);
308
+ setJobs([]);
309
+ setSelectedJob(null);
310
+ setGeneratedDocs({ cv: null, coverLetter: null });
311
+ setCurrentStep('search');
312
+ setError(null);
313
+ setSearchKey(prev => prev + 1); // Force re-mount of JobSearch
314
+ setPostedFilter('all');
315
+ setHasSearched(false);
316
+ }, []);
317
+
318
+ const handleBackToSearch = useCallback(() => {
319
+ setSelectedJob(null);
320
+ setAnalysisResult(null);
321
+ setCvData(null);
322
+ setAnalysisResult(null);
323
+ setCvData(null);
324
+ setCurrentStep('search');
325
+ }, []);
326
+
327
+ // 6. About Us View
328
+ if (currentStep === 'about') {
329
+ return (
330
+ <div className="app">
331
+ <Background3D />
332
+ <main className="main-content" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', padding: '2rem' }}>
333
+ <AboutUs onBack={handleBackToSearch} />
334
+ </main>
335
+ </div>
336
+ );
337
+ }
338
+
339
+ return (
340
+ <div className="app">
341
+ <Background3D />
342
+
343
+ {/* Header */}
344
+ <header style={{
345
+ padding: '2rem 3rem',
346
+ display: 'flex',
347
+ justifyContent: 'space-between',
348
+ alignItems: 'center',
349
+ position: 'relative',
350
+ zIndex: 10
351
+ }}>
352
+ <div onClick={handleReset} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '1rem' }}>
353
+ <Brain size={64} color="var(--color-primary)" />
354
+ <div>
355
+ <h1 style={{
356
+ fontSize: '2.2rem',
357
+ fontWeight: 800,
358
+ margin: 0,
359
+ background: 'linear-gradient(to right, #fff, var(--color-primary-light))',
360
+ WebkitBackgroundClip: 'text',
361
+ WebkitTextFillColor: 'transparent',
362
+ backgroundClip: 'text',
363
+ letterSpacing: '-0.02em',
364
+ lineHeight: 1.2
365
+ }}>NeuroArc</h1>
366
+ <p style={{
367
+ margin: 0,
368
+ color: 'var(--color-text-muted)',
369
+ fontSize: '1.1rem',
370
+ fontWeight: 500
371
+ }}>AI Career Architect</p>
372
+ </div>
373
+ </div>
374
+
375
+ <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
376
+
377
+
378
+ <div className="tooltip-container">
379
+ <a href="https://www.buymeacoffee.com/manojthapa" target="_blank" rel="noopener noreferrer" className="hide-mobile">
380
+ <img
381
+ src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"
382
+ alt="Buy Me A Coffee"
383
+ style={{ height: '50px', width: 'auto' }}
384
+ />
385
+ </a>
386
+
387
+ <a href="https://www.buymeacoffee.com/manojthapa" target="_blank" rel="noopener noreferrer" className="show-mobile">
388
+ <img
389
+ src="/bmc-icon.png"
390
+ alt="Buy Me A Coffee"
391
+ style={{ height: '36px', width: 'auto', borderRadius: '50%', boxShadow: '0 4px 12px rgba(255, 221, 0, 0.3)' }}
392
+ />
393
+ </a>
394
+ <span className="tooltip-text">Support Manoj</span>
395
+ </div>
396
+ </div>
397
+ </header>
398
+
399
+ {/* Main Content */}
400
+ <main className="main" style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
401
+ {/* Steps Indicator */}
402
+ {/* Dynamic Step Indicator */}
403
+ {/* Dynamic Step Indicator - Visuals Hidden, kept for spacing */}
404
+ {/* Dynamic Step Indicator - Visuals Hidden, kept for spacing */}
405
+ <div className="steps-container" style={{
406
+ marginBottom: currentStep === 'search' ? '11rem' : '2rem',
407
+ height: '80px',
408
+ visibility: 'hidden',
409
+ transition: 'margin-bottom 0.5s ease-in-out'
410
+ }}>
411
+ {/* Visual elements removed to rely on 3D background */}
412
+ </div>
413
+
414
+ {/* Error Alert */}
415
+ <AnimatePresence>
416
+ {error && currentStep !== 'analysis' && (
417
+ <motion.div
418
+ initial={{ opacity: 0, y: -50, x: '-50%' }}
419
+ animate={{ opacity: 1, y: 0, x: '-50%' }}
420
+ exit={{ opacity: 0, y: -50, x: '-50%' }}
421
+ className="alert"
422
+ style={{
423
+ position: 'fixed',
424
+ top: '2rem',
425
+ left: '50%',
426
+ transform: 'translateX(-50%)',
427
+ zIndex: 100,
428
+ width: 'auto',
429
+ maxWidth: '90%',
430
+ display: 'flex',
431
+ alignItems: 'center',
432
+ gap: '1rem',
433
+ padding: '1rem 1.5rem',
434
+ background: 'rgba(23, 23, 23, 0.95)',
435
+ backdropFilter: 'blur(12px)',
436
+ border: '1px solid var(--color-error)',
437
+ borderRadius: '12px',
438
+ boxShadow: '0 10px 40px rgba(0,0,0,0.5)',
439
+ color: 'var(--color-text-primary)'
440
+ }}
441
+ >
442
+ <AlertCircle size={24} color="var(--color-error)" />
443
+ {error.includes('buymeacoffee') ? (
444
+ <span style={{ fontSize: '0.95rem' }}>
445
+ Server is busy due to high demand. Please help keep the servers running β€” {' '}
446
+ <a
447
+ href="https://buymeacoffee.com/manojthapa"
448
+ target="_blank"
449
+ rel="noopener noreferrer"
450
+ style={{ color: 'var(--color-warning)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: '0.25rem', textDecoration: 'none' }}
451
+ >
452
+ <Coffee size={16} /> Buy me a coffee
453
+ </a>
454
+ </span>
455
+ ) : (
456
+ <span>{error}</span>
457
+ )}
458
+ <button
459
+ onClick={() => setError(null)}
460
+ style={{
461
+ marginLeft: '1rem',
462
+ background: 'none',
463
+ border: 'none',
464
+ color: 'var(--color-text-muted)',
465
+ cursor: 'pointer',
466
+ display: 'flex',
467
+ alignItems: 'center',
468
+ padding: '4px',
469
+ borderRadius: '50%',
470
+ transition: 'all 0.2s'
471
+ }}
472
+ onMouseEnter={(e) => { e.currentTarget.style.color = 'white'; e.currentTarget.style.background = 'rgba(255,255,255,0.1)'; }}
473
+ onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; }}
474
+ >
475
+ Γ—
476
+ </button>
477
+ </motion.div>
478
+ )}
479
+ </AnimatePresence>
480
+
481
+ <AnimatePresence mode="wait">
482
+ {/* Step 1: Job Search */}
483
+ {currentStep === 'search' && (
484
+ <motion.div
485
+ key="search"
486
+ initial={{ opacity: 0, y: 20 }}
487
+ animate={{ opacity: 1, y: 0 }}
488
+ exit={{ opacity: 0, y: -20 }}
489
+ transition={{ duration: 0.5 }}
490
+ >
491
+ <div style={{ marginBottom: '3rem', textAlign: 'center' }}>
492
+ <h1 className="hero-title">Find Your Next Role</h1>
493
+ <p className="hero-subtitle">Search for jobs, analyze your fit, and get a tailored application in seconds.</p>
494
+ </div>
495
+
496
+ <JobSearch key={searchKey} onSearch={handleJobSearch} loading={loading} />
497
+
498
+ {/* Loading Animation for Job Search */}
499
+ {loading && currentStep === 'search' && (
500
+ <motion.div
501
+ className="loading"
502
+ initial={{ opacity: 0 }}
503
+ animate={{ opacity: 1 }}
504
+ style={{
505
+ marginTop: '3rem',
506
+ textAlign: 'center',
507
+ minHeight: '50vh',
508
+ display: 'flex',
509
+ flexDirection: 'column',
510
+ justifyContent: 'center',
511
+ alignItems: 'center'
512
+ }}
513
+ >
514
+ <Loader2 size={64} className="spinner" />
515
+ <h2 className="hero-title" style={{ marginTop: '1.5rem', fontSize: '2.5rem' }}>Looking for jobs...</h2>
516
+ </motion.div>
517
+ )}
518
+
519
+ {!loading && (
520
+ <motion.div
521
+ style={{ marginTop: '2rem' }}
522
+ initial={{ opacity: 0 }}
523
+ animate={{ opacity: 1 }}
524
+ >
525
+ <JobList
526
+ jobs={jobs}
527
+ selectedJob={selectedJob}
528
+ onSelectJob={handleSelectJob}
529
+ cvSkills={[]}
530
+ postedFilter={postedFilter}
531
+ setPostedFilter={setPostedFilter}
532
+ hasSearched={hasSearched}
533
+ />
534
+ </motion.div>
535
+ )}
536
+ </motion.div>
537
+ )}
538
+
539
+ {/* Step 2: CV Analysis */}
540
+ {currentStep === 'analysis' && selectedJob && (
541
+ <motion.div
542
+ key="analysis"
543
+ initial={{ opacity: 0, x: 20 }}
544
+ animate={{ opacity: 1, x: 0 }}
545
+ exit={{ opacity: 0, x: -20 }}
546
+ transition={{ duration: 0.5 }}
547
+ >
548
+ <CVAnalysis
549
+ job={selectedJob}
550
+ onAnalyze={handleAnalysis}
551
+ onNext={handleOptimize}
552
+ onBack={handleBackToSearch}
553
+ upstreamError={error}
554
+ />
555
+ </motion.div>
556
+ )}
557
+
558
+ {/* Step 3: Preview & Apply */}
559
+ {currentStep === 'preview' && (
560
+ <motion.div
561
+ key="preview"
562
+ initial={{ opacity: 0 }}
563
+ animate={{ opacity: 1 }}
564
+ exit={{ opacity: 0 }}
565
+ >
566
+ {loading ? (
567
+ <div className="loading" style={{ textAlign: 'center', padding: '0', perspective: '1000px', marginTop: '3rem', minHeight: '50vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
568
+ {/* 3D Renovation Animation */}
569
+ <div style={{ position: 'relative' }}>
570
+ <motion.div
571
+ animate={{ rotateY: 360 }}
572
+ transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
573
+ style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}
574
+ >
575
+ <FileText size={80} color="var(--color-primary)" strokeWidth={1.5} />
576
+ </motion.div>
577
+ <motion.div
578
+ animate={{ y: [-5, 5, -5] }}
579
+ transition={{ duration: 1.5, repeat: Infinity, ease: "easeInOut" }}
580
+ style={{
581
+ position: 'absolute',
582
+ bottom: -10,
583
+ right: -25
584
+ }}
585
+ >
586
+ <Hammer size={36} color="var(--color-primary)" />
587
+ </motion.div>
588
+ </div>
589
+ <GenerationProgress type="cv" />
590
+ </div>
591
+ ) : (
592
+ <div>
593
+ <div className="card fade-in" style={{
594
+ marginBottom: '2rem',
595
+ background: 'rgba(16, 185, 129, 0.1)',
596
+ border: '1px solid rgba(16, 185, 129, 0.3)',
597
+ padding: '1.5rem',
598
+ display: 'flex',
599
+ alignItems: 'center',
600
+ gap: '1.5rem',
601
+ boxShadow: '0 8px 32px rgba(16, 185, 129, 0.15)',
602
+ position: 'relative',
603
+ overflow: 'hidden'
604
+ }}>
605
+ <div style={{
606
+ width: '4px',
607
+ height: '100%',
608
+ background: 'var(--color-success)',
609
+ position: 'absolute',
610
+ left: 0,
611
+ top: 0
612
+ }}></div>
613
+ <div style={{
614
+ background: 'var(--color-success)',
615
+ borderRadius: '50%',
616
+ width: '48px',
617
+ height: '48px',
618
+ display: 'flex',
619
+ alignItems: 'center',
620
+ justifyContent: 'center',
621
+ flexShrink: 0,
622
+ boxShadow: '0 0 20px rgba(16, 185, 129, 0.4)'
623
+ }}>
624
+ <CheckCircle size={28} color="#050b14" strokeWidth={3} />
625
+ </div>
626
+ <div>
627
+ <h3 style={{ margin: 0, color: 'var(--color-success)', fontSize: '1.25rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
628
+ Optimization Complete! <Sparkles size={18} />
629
+ </h3>
630
+ <p style={{ margin: '0.25rem 0 0', color: 'var(--color-text-primary)' }}>
631
+ Your documents are ready for <strong style={{ color: 'white' }}>{selectedJob?.title}</strong> at {selectedJob?.company}.
632
+ </p>
633
+ </div>
634
+ </div>
635
+
636
+ <DocumentPreview
637
+ cv={generatedDocs.cv}
638
+ textContent={generatedDocs.textContent}
639
+ isPdf={generatedDocs.isPdf}
640
+ onDownloadCV={handleDownloadCV}
641
+ analysisResult={analysisResult}
642
+ job={selectedJob}
643
+ onBack={handleBackToSearch}
644
+ />
645
+ </div>
646
+ )}
647
+ </motion.div>
648
+ )}
649
+ </AnimatePresence>
650
+ </main>
651
+
652
+ {/* Footer - hidden on preview step */}
653
+ {
654
+ currentStep !== 'preview' && <footer className="footer-responsive">
655
+ {/* Left: About Us */}
656
+ <div className="footer-left">
657
+ <a
658
+ href="#"
659
+ onClick={(e) => { e.preventDefault(); setCurrentStep('about'); }}
660
+ style={{ color: 'var(--color-text-muted)', textDecoration: 'none', fontWeight: 600, opacity: 0.8 }}
661
+ >
662
+ About Us
663
+ </a>
664
+ </div>
665
+
666
+ {/* Center: Copyright */}
667
+ <div className="footer-center">
668
+ <p style={{ color: 'var(--color-text-muted)', margin: 0, opacity: 0.8, fontWeight: 600 }}>
669
+ &copy; NeuroArc 2025
670
+ </p>
671
+
672
+ <p style={{ color: 'var(--color-text-muted)', margin: 0, opacity: 0.8, fontSize: '0.8rem' }}>
673
+ Privacy Notice: No data is stored. All CV analysis and optimization are processed in-memory.
674
+ </p>
675
+ </div>
676
+
677
+ {/* Right: BMC */}
678
+ <div className="footer-right">
679
+ <div className="tooltip-container footer-bmc">
680
+ <a href="https://www.buymeacoffee.com/manojthapa" target="_blank" rel="noopener noreferrer">
681
+ <img
682
+ src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"
683
+ alt="Buy Me A Coffee"
684
+ style={{ height: '32px', width: 'auto' }}
685
+ />
686
+ </a>
687
+ <span className="tooltip-text">Support Manoj</span>
688
+ </div>
689
+ </div>
690
+ </footer>
691
+ }
692
+
693
+
694
+ </div >
695
+ );
696
+ }
697
+
698
+ export default App;
frontend/src/components/AboutUs.jsx ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { motion } from 'framer-motion';
3
+ import { ArrowLeft, Coffee, Heart } from 'lucide-react';
4
+
5
+ const AboutUs = ({ onBack }) => {
6
+ return (
7
+ <motion.div
8
+ initial={{ opacity: 0, y: 20 }}
9
+ animate={{ opacity: 1, y: 0 }}
10
+ exit={{ opacity: 0, y: -20 }}
11
+ className="card about-us-card"
12
+ style={{
13
+ maxWidth: '800px',
14
+ width: '100%',
15
+ margin: '2rem auto',
16
+ textAlign: 'center',
17
+ position: 'relative'
18
+ }}
19
+ >
20
+ {/* Header / Back Button */}
21
+ <button
22
+ className="btn btn-ghost"
23
+ onClick={onBack}
24
+ style={{
25
+ position: 'absolute',
26
+ top: '1.5rem',
27
+ left: '1.5rem',
28
+ color: 'var(--color-text-muted)',
29
+ display: 'flex',
30
+ alignItems: 'center',
31
+ gap: '0.5rem',
32
+ padding: '0.5rem 1rem',
33
+ borderRadius: '20px',
34
+ fontSize: '0.9rem',
35
+ zIndex: 10
36
+ }}
37
+ >
38
+ <ArrowLeft size={18} /> Back
39
+ </button>
40
+
41
+ <div style={{ marginBottom: '2rem' }}>
42
+ <div className="show-mobile" style={{ height: '3rem' }}></div>
43
+ <h2 className="hero-title" style={{ fontSize: '2.5rem', marginBottom: '1rem' }}>About NeuroArc</h2>
44
+ <div style={{ width: '60px', height: '4px', background: 'var(--color-primary)', margin: '0 auto', borderRadius: '2px' }}></div>
45
+ </div>
46
+
47
+ <div style={{ marginBottom: '3rem', textAlign: 'left', lineHeight: '1.8' }}>
48
+ <p style={{ fontSize: '1.1rem', marginBottom: '1.5rem', color: 'var(--color-text-primary)' }}>
49
+ <strong>Who am I?</strong><br />
50
+ NeuroArc was built with a single mission: to help students and job seekers land their dream rolesβ€”whether part-time or full-time.
51
+ </p>
52
+ <p style={{ fontSize: '1.1rem', marginBottom: '1.5rem', color: 'var(--color-text-muted)' }}>
53
+ I understand that the job market is tough. ATS (Applicant Tracking Systems) often filter out great candidates before a human even sees them. That's why I created this toolβ€”to give you the edge you need by optimizing your CV on the basis of ATS.
54
+ </p>
55
+
56
+ <div style={{
57
+ background: 'rgba(45, 212, 191, 0.1)',
58
+ border: '1px solid var(--color-primary-dark)',
59
+ borderRadius: '16px',
60
+ padding: '1.5rem',
61
+ marginBottom: '1.5rem'
62
+ }}>
63
+ <p style={{ margin: 0, color: 'var(--color-text-primary)', display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
64
+ <Heart size={20} color="var(--color-primary)" fill="var(--color-primary)" style={{ flexShrink: 0 }} />
65
+ <span>
66
+ <strong>NeuroArc is completely free to use.</strong> I believe access to career tools shouldn't be behind a paywall.
67
+ </span>
68
+ </p>
69
+ </div>
70
+
71
+ <p style={{ fontSize: '1.1rem', color: 'var(--color-text-muted)' }}>
72
+ However, running the website and high-performance servers that power these optimizations does come with a cost. I keep this running out of passion, but I am a student developer.
73
+ </p>
74
+ </div>
75
+
76
+ <div style={{
77
+ borderTop: '1px solid var(--color-border)',
78
+ paddingTop: '2.5rem',
79
+ display: 'flex',
80
+ flexDirection: 'column',
81
+ alignItems: 'center',
82
+ gap: '1rem'
83
+ }}>
84
+ <p style={{ fontSize: '1.2rem', fontWeight: 600, color: 'var(--color-text-primary)' }}>
85
+ Your support creates opportunities.
86
+ </p>
87
+ <p style={{ maxWidth: '600px', margin: '0 auto 1.5rem', color: 'var(--color-text-muted)' }}>
88
+ If this tool has helped you, or if you simply believe in my mission, consider supporting me. Your contribution helps keep the servers running and the service free for everyone. I am deeply grateful for any support.
89
+ </p>
90
+
91
+ <div style={{ marginBottom: '1.5rem' }}>
92
+ <a href="https://github.com/iammanoj807" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--color-primary)', textDecoration: 'none', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.5rem', justifyContent: 'center' }}>
93
+ Connect on GitHub
94
+ </a>
95
+ </div>
96
+
97
+ <a
98
+ href="https://www.buymeacoffee.com/manojthapa"
99
+ target="_blank"
100
+ rel="noopener noreferrer"
101
+ style={{
102
+ display: 'inline-block',
103
+ transition: 'transform 0.2s ease'
104
+ }}
105
+ onMouseOver={(e) => e.currentTarget.style.transform = 'translateY(-2px)'}
106
+ onMouseOut={(e) => e.currentTarget.style.transform = 'translateY(0)'}
107
+ >
108
+ <img
109
+ src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"
110
+ alt="Buy Me A Coffee"
111
+ style={{ height: '50px', width: 'auto' }}
112
+ />
113
+ </a>
114
+ </div>
115
+ </motion.div>
116
+ );
117
+ };
118
+
119
+ export default AboutUs;
frontend/src/components/Background3D.jsx ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useRef, useState, useMemo, useEffect } from 'react';
2
+ import { Canvas, useFrame, useLoader } from '@react-three/fiber';
3
+ import { Points, PointMaterial, Sphere } from '@react-three/drei';
4
+ import * as THREE from 'three';
5
+
6
+
7
+
8
+
9
+ function Moon({ earthRadius }) {
10
+ const moonRef = useRef();
11
+ const distance = 8;
12
+ const [colorMap, bumpMap] = useLoader(THREE.TextureLoader, [
13
+ '/textures/moon_map.jpg',
14
+ '/textures/moon_bump.jpg'
15
+ ]);
16
+
17
+ useFrame(({ clock }) => {
18
+ const t = clock.getElapsedTime() * 0.05; // Orbital speed
19
+
20
+ // Orbit
21
+ moonRef.current.position.x = Math.cos(t) * distance;
22
+ moonRef.current.position.z = Math.sin(t) * distance;
23
+
24
+ // Tidal locking (rotation matches orbit)
25
+ moonRef.current.rotation.y = -t;
26
+ });
27
+
28
+ return (
29
+ <mesh ref={moonRef} position={[distance, 0, 0]}>
30
+ <sphereGeometry args={[0.8, 32, 32]} />
31
+ <meshStandardMaterial
32
+ map={colorMap}
33
+ bumpMap={bumpMap}
34
+ bumpScale={0.02}
35
+ metalness={0.1}
36
+ roughness={0.8}
37
+ emissive="#666666"
38
+ emissiveIntensity={0.4}
39
+ />
40
+ </mesh>
41
+ );
42
+ }
43
+
44
+ function Earth() {
45
+ const earthRef = useRef();
46
+ const cloudsRef = useRef();
47
+ const groupRef = useRef();
48
+
49
+ const [colorMap, normalMap, specularMap, cloudsMap] = useLoader(THREE.TextureLoader, [
50
+ '/textures/earth_daymap.jpg',
51
+ '/textures/earth_normal.jpg',
52
+ '/textures/earth_specular.jpg',
53
+ '/textures/earth_clouds.png'
54
+ ]);
55
+
56
+ useFrame(({ clock }) => {
57
+ const t = clock.getElapsedTime();
58
+ // Earth rotation
59
+ earthRef.current.rotation.y = t * 0.05;
60
+ // Clouds rotation (slightly faster)
61
+ cloudsRef.current.rotation.y = t * 0.055;
62
+ });
63
+
64
+ return (
65
+ <group ref={groupRef} position={[0, 4, -30]} rotation={[0, 0, 23.5 * Math.PI / 180]}>
66
+ {/* Main Earth Sphere */}
67
+ <mesh ref={earthRef}>
68
+ <sphereGeometry args={[3, 64, 64]} />
69
+ <meshStandardMaterial
70
+ map={colorMap}
71
+ normalMap={normalMap}
72
+ roughnessMap={specularMap}
73
+ metalness={0.1}
74
+ roughness={0.7}
75
+ emissive={new THREE.Color('#2060c0')}
76
+ emissiveIntensity={0.3}
77
+ />
78
+ </mesh>
79
+
80
+ {/* Clouds Layer */}
81
+ <mesh ref={cloudsRef}>
82
+ <sphereGeometry args={[3.05, 64, 64]} />
83
+ <meshPhongMaterial
84
+ map={cloudsMap}
85
+ transparent
86
+ opacity={0.8}
87
+ blending={THREE.AdditiveBlending}
88
+ side={THREE.DoubleSide}
89
+ depthWrite={false}
90
+ />
91
+ </mesh>
92
+
93
+ <ISS />
94
+ <Moon earthRadius={3} />
95
+ </group>
96
+ );
97
+ }
98
+
99
+ function SpaceDebris() {
100
+ const count = 80;
101
+ const meshRef = useRef();
102
+ const [texture] = useLoader(THREE.TextureLoader, ['/textures/moon_map.jpg']);
103
+
104
+ const particles = useMemo(() => {
105
+ const temp = [];
106
+ for (let i = 0; i < count; i++) {
107
+ const time = Math.random() * 100;
108
+ const factor = 15 + Math.random() * 30; // Radius spread
109
+ const speed = 0.01 + Math.random() / 200;
110
+ // Restrict Y to above (5 to 15) or below (-15 to -5)
111
+ const isUpper = Math.random() > 0.5;
112
+ const y = isUpper ? (5 + Math.random() * 10) : (-15 + Math.random() * 10);
113
+
114
+ // Random x, z based on factor
115
+ const x = Math.cos(time) * factor;
116
+ const z = Math.sin(time) * factor;
117
+
118
+ const scale = 0.15 + Math.random() * 0.3; // Small size
119
+ const rotationSpeed = Math.random() * 0.02;
120
+
121
+ temp.push({ time, factor, speed, x, y, z, scale, rotationSpeed });
122
+ }
123
+ return temp;
124
+ }, []);
125
+
126
+ const dummy = useMemo(() => new THREE.Object3D(), []);
127
+
128
+ useFrame((state) => {
129
+ particles.forEach((particle, i) => {
130
+ // Update rotation (orbit around Y)
131
+ const t = particle.time + state.clock.getElapsedTime() * particle.speed;
132
+ const x = Math.cos(t) * particle.factor;
133
+ const z = Math.sin(t) * particle.factor;
134
+
135
+ // Apply slight vertical "falling" / drift for dynamic feel
136
+ // We'll just make them rotate for now as 'falling' usually implies moving down which clears screen.
137
+ // Orbiting covers "flying/moving".
138
+
139
+ dummy.position.set(x, particle.y, z);
140
+
141
+ // Random tumbling
142
+ dummy.rotation.x += particle.rotationSpeed;
143
+ dummy.rotation.y += particle.rotationSpeed;
144
+ dummy.scale.set(particle.scale, particle.scale, particle.scale);
145
+
146
+ dummy.updateMatrix();
147
+ meshRef.current.setMatrixAt(i, dummy.matrix);
148
+ });
149
+ meshRef.current.instanceMatrix.needsUpdate = true;
150
+ });
151
+
152
+ return (
153
+ <instancedMesh ref={meshRef} args={[null, null, count]}>
154
+ <dodecahedronGeometry args={[0.2, 0]} />
155
+ <meshStandardMaterial map={texture} color="#666666" roughness={0.8} />
156
+ </instancedMesh>
157
+ );
158
+ }
159
+
160
+ function GalaxyBackground() {
161
+ const [texture] = useLoader(THREE.TextureLoader, ['/textures/galaxy_bg.jpg']);
162
+ return (
163
+ <mesh position={[0, 0, -100]}>
164
+ <planeGeometry args={[200, 100]} />
165
+ <meshBasicMaterial map={texture} transparent opacity={0.6} depthWrite={false} blending={THREE.AdditiveBlending} />
166
+ </mesh>
167
+ );
168
+ }
169
+
170
+ const MOBILE_BREAKPOINT = 1140;
171
+
172
+ function Sun({ isMobile }) {
173
+ const sunRef = useRef();
174
+ const [texture] = useLoader(THREE.TextureLoader, ['/textures/sun_map.jpg']);
175
+
176
+ useFrame(() => {
177
+ // Sun rotation (very slow)
178
+ if (sunRef.current) {
179
+ sunRef.current.rotation.y += 0.0005;
180
+ }
181
+ });
182
+
183
+ // Desktop: [-80, 40, -150], Mobile: Center, higher up, further back
184
+ const position = isMobile ? [-50, 60, -250] : [-80, 40, -150];
185
+ const scale = isMobile ? 0.6 : 1;
186
+
187
+ return (
188
+ <group position={position} scale={scale}>
189
+ {/* Sun sphere */}
190
+ <mesh ref={sunRef}>
191
+ <sphereGeometry args={[2.5, 64, 64]} />
192
+ <meshBasicMaterial map={texture} color="#ffffff" toneMapped={false} fog={false} />
193
+ </mesh>
194
+
195
+ <pointLight intensity={2} distance={500} decay={1} color="#ffffff" />
196
+ </group>
197
+ );
198
+ }
199
+
200
+ function ISS() {
201
+ const issRef = useRef();
202
+ const [texture] = useLoader(THREE.TextureLoader, ['/textures/iss_clean_texture.png']);
203
+
204
+ useFrame((state) => {
205
+ const t = state.clock.getElapsedTime() * 0.1;
206
+ const radius = 4.2;
207
+ const inclination = 51.6 * (Math.PI / 180);
208
+
209
+ // Calculate position in tilted orbit
210
+ const x = Math.cos(t) * radius;
211
+ const y = Math.sin(t) * Math.sin(inclination) * radius;
212
+ const z = Math.sin(t) * Math.cos(inclination) * radius;
213
+
214
+ if (issRef.current) {
215
+ issRef.current.position.set(x, y, z);
216
+ // Billboard effect: Make visible side always face the camera
217
+ issRef.current.lookAt(state.camera.position);
218
+ }
219
+ });
220
+
221
+ return (
222
+ <mesh ref={issRef}>
223
+ <planeGeometry args={[1.2, 1.2]} />
224
+ <meshBasicMaterial
225
+ map={texture}
226
+ transparent
227
+ opacity={1}
228
+ blending={THREE.AdditiveBlending}
229
+ side={THREE.DoubleSide}
230
+ depthWrite={false}
231
+ toneMapped={false}
232
+ color="#ffffff"
233
+ />
234
+ </mesh>
235
+ );
236
+ }
237
+
238
+ function Lights({ isMobile }) {
239
+ const sunPosition = isMobile ? [-50, 60, -250] : [-80, 40, -150];
240
+
241
+ return (
242
+ <>
243
+ <ambientLight intensity={0.7} color="#ffffff" />
244
+ <directionalLight
245
+ position={sunPosition}
246
+ intensity={5}
247
+ castShadow
248
+ color="#ffffff"
249
+ />
250
+ <spotLight position={[10, 0, -20]} intensity={2} color="#0099ff" angle={0.5} />
251
+ </>
252
+ );
253
+ }
254
+
255
+ export default function Background3D() {
256
+ const [isMobile, setIsMobile] = useState(false);
257
+
258
+ // Track window resize to update Sun position
259
+ useEffect(() => {
260
+ const handleResize = () => {
261
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
262
+ };
263
+
264
+ // Initial check
265
+ handleResize();
266
+
267
+ window.addEventListener('resize', handleResize);
268
+ return () => window.removeEventListener('resize', handleResize);
269
+ }, []);
270
+
271
+ return (
272
+ <div className="background-3d">
273
+ <Canvas camera={{ position: [0, 0, 10], fov: 45 }}>
274
+ <Lights isMobile={isMobile} />
275
+ <GalaxyBackground />
276
+ <SpaceDebris />
277
+
278
+ <Sun isMobile={isMobile} />
279
+ <Earth />
280
+ <fog attach="fog" args={['#050b14', 10, 60]} />
281
+ </Canvas>
282
+ </div>
283
+ );
284
+ }
frontend/src/components/CVAnalysis.jsx ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useCallback, useEffect } from 'react';
2
+ import { Upload, FileText, CheckCircle, AlertCircle, Loader2, ArrowLeft, ArrowRight, Wrench, Briefcase, Search, Coffee, Trash2, X, BrainCircuit, FileSearch, Sparkles, ScanLine } from 'lucide-react';
3
+ import { motion } from 'framer-motion';
4
+
5
+ function CVAnalysis({ job, onAnalyze, onNext, onBack, upstreamError }) {
6
+ const [isDragging, setIsDragging] = useState(false);
7
+ const [file, setFile] = useState(null);
8
+ const [analyzing, setAnalyzing] = useState(false);
9
+ const [result, setResult] = useState(null);
10
+ const [error, setError] = useState(null);
11
+ const [dismissedError, setDismissedError] = useState(false);
12
+ const [isSmallScreen, setIsSmallScreen] = useState(window.innerWidth < 1020);
13
+
14
+ useEffect(() => {
15
+ const handleResize = () => setIsSmallScreen(window.innerWidth < 1020);
16
+ window.addEventListener('resize', handleResize);
17
+ return () => window.removeEventListener('resize', handleResize);
18
+ }, []);
19
+
20
+ // Combine local and upstream errors (unless dismissed)
21
+ const displayError = dismissedError ? null : (error || upstreamError);
22
+
23
+ // Auto-analyze when file is set
24
+ const startAnalysis = async (selectedFile) => {
25
+ setFile(selectedFile);
26
+ setError(null);
27
+ setDismissedError(false); // Reset dismissed state
28
+ setAnalyzing(true);
29
+
30
+ try {
31
+ const analysis = await onAnalyze(selectedFile, job);
32
+ setResult(analysis);
33
+ } catch (err) {
34
+ setError(err.message || 'Analysis failed. Please try again.');
35
+ } finally {
36
+ setAnalyzing(false);
37
+ }
38
+ };
39
+
40
+ const handleDrag = useCallback((e) => {
41
+ e.preventDefault();
42
+ e.stopPropagation();
43
+ if (e.type === 'dragenter' || e.type === 'dragover') {
44
+ setIsDragging(true);
45
+ } else if (e.type === 'dragleave') {
46
+ setIsDragging(false);
47
+ }
48
+ }, []);
49
+
50
+ const handleDrop = useCallback((e) => {
51
+ e.preventDefault();
52
+ e.stopPropagation();
53
+ setIsDragging(false);
54
+
55
+ if (e.dataTransfer.files && e.dataTransfer.files[0]) {
56
+ const selectedFile = e.dataTransfer.files[0];
57
+ if (selectedFile.type === 'application/pdf' || selectedFile.name.endsWith('.pdf') || selectedFile.name.endsWith('.docx')) {
58
+ startAnalysis(selectedFile);
59
+ } else {
60
+ setError('Please upload a PDF or DOCX file.');
61
+ setDismissedError(false);
62
+ }
63
+ }
64
+ }, [job, onAnalyze]);
65
+
66
+ const handleFileSelect = (e) => {
67
+ if (e.target.files && e.target.files[0]) {
68
+ startAnalysis(e.target.files[0]);
69
+ }
70
+ };
71
+
72
+ const handleAnalyzeClick = async () => {
73
+ if (!file) return;
74
+
75
+ setAnalyzing(true);
76
+ setError(null);
77
+ setDismissedError(false);
78
+
79
+ try {
80
+ const analysis = await onAnalyze(file, job);
81
+ setResult(analysis);
82
+ } catch (err) {
83
+ setError(err.message || 'Analysis failed. Please try again.');
84
+ } finally {
85
+ setAnalyzing(false);
86
+ }
87
+ };
88
+
89
+ if (result) {
90
+ return (
91
+ <div className="analysis-results fade-in">
92
+ <div className="results-navigation" style={{ marginBottom: '2rem' }}>
93
+ <button
94
+ className="btn btn-ghost"
95
+ onClick={onBack}
96
+ style={{
97
+ color: 'var(--color-text-muted)',
98
+ display: 'flex',
99
+ alignItems: 'center',
100
+ gap: '0.5rem',
101
+ padding: '0.5rem 1rem',
102
+ borderRadius: '20px',
103
+ fontSize: '0.9rem',
104
+ width: 'fit-content'
105
+ }}
106
+ >
107
+ <ArrowLeft size={18} /> Back to Search
108
+ </button>
109
+ </div>
110
+
111
+ {/* Show upstream error (e.g. optimization failed) */}
112
+ {displayError && result && (
113
+ <div className="alert alert-error" style={{ marginBottom: '2rem', textAlign: 'left', display: 'flex', alignItems: 'flex-start', gap: '0.75rem', position: 'relative' }}>
114
+ <AlertCircle size={20} style={{ flexShrink: 0, marginTop: '2px' }} />
115
+ <div style={{ fontSize: '0.95rem', lineHeight: 1.5, flex: 1 }}>
116
+ {displayError.includes('buymeacoffee') ? (
117
+ <span>
118
+ Server is busy due to high demand. Please help keep the servers running β€” {' '}
119
+ <a
120
+ href="https://buymeacoffee.com/manojthapa"
121
+ target="_blank"
122
+ rel="noopener noreferrer"
123
+ style={{ color: 'var(--color-warning)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: '0.25rem' }}
124
+ >
125
+ <Coffee size={16} /> Buy me a coffee
126
+ </a>
127
+ </span>
128
+ ) : (
129
+ displayError
130
+ )}
131
+ </div>
132
+ <button
133
+ onClick={() => setDismissedError(true)}
134
+ style={{
135
+ background: 'transparent',
136
+ border: 'none',
137
+ color: 'inherit',
138
+ cursor: 'pointer',
139
+ padding: '0.25rem',
140
+ display: 'flex',
141
+ alignItems: 'center',
142
+ justifyContent: 'center',
143
+ opacity: 0.7,
144
+ transition: 'opacity 0.2s'
145
+ }}
146
+ onMouseEnter={(e) => e.target.style.opacity = 1}
147
+ onMouseLeave={(e) => e.target.style.opacity = 0.7}
148
+ >
149
+ <X size={18} />
150
+ </button>
151
+ </div>
152
+ )}
153
+
154
+ {/* Score & Header Section */}
155
+ <div style={{
156
+ display: 'grid',
157
+ gridTemplateColumns: isSmallScreen ? '1fr' : 'minmax(250px, 1fr) 2fr',
158
+ gap: '2rem',
159
+ marginBottom: '2rem',
160
+ alignItems: 'stretch'
161
+ }}>
162
+ {/* Score Card */}
163
+ <div className="card" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '2.5rem' }}>
164
+ <div className="score-circle-container" style={{ position: 'relative', width: '180px', height: '180px', marginBottom: '1.5rem' }}>
165
+ {/* Glowing Background */}
166
+ <div style={{
167
+ position: 'absolute',
168
+ inset: 0,
169
+ borderRadius: '50%',
170
+ background: `radial-gradient(circle at center, ${result.score >= 70 ? 'var(--color-success)' : (result.score >= 50 ? 'var(--color-warning)' : 'var(--color-error)')} 0%, transparent 70%)`,
171
+ opacity: 0.15,
172
+ filter: 'blur(20px)'
173
+ }}></div>
174
+
175
+ {/* SVG Progress Circle */}
176
+ <svg width="180" height="180" viewBox="0 0 180 180" style={{ transform: 'rotate(-90deg)' }}>
177
+ <circle
178
+ cx="90"
179
+ cy="90"
180
+ r="80"
181
+ fill="none"
182
+ stroke="var(--color-bg-secondary)"
183
+ strokeWidth="10"
184
+ />
185
+ <circle
186
+ cx="90"
187
+ cy="90"
188
+ r="80"
189
+ fill="none"
190
+ stroke={result.score >= 70 ? 'var(--color-success)' : (result.score >= 50 ? 'var(--color-warning)' : 'var(--color-error)')}
191
+ strokeWidth="10"
192
+ strokeDasharray={502}
193
+ strokeDashoffset={502 - (502 * result.score) / 100}
194
+ strokeLinecap="round"
195
+ style={{ transition: 'stroke-dashoffset 1s ease-out' }}
196
+ />
197
+ </svg>
198
+
199
+ <div style={{
200
+ position: 'absolute',
201
+ inset: 0,
202
+ display: 'flex',
203
+ alignItems: 'center',
204
+ justifyContent: 'center',
205
+ flexDirection: 'column'
206
+ }}>
207
+ <span style={{ fontSize: '3.5rem', fontWeight: 800, lineHeight: 1, letterSpacing: '-0.03em' }}>{result.score}%</span>
208
+ <span style={{ fontSize: '1rem', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: '0.25rem' }}>Match</span>
209
+ </div>
210
+ </div>
211
+ </div>
212
+
213
+ {/* Header Details Card */}
214
+ <div className="card" style={{ display: 'flex', flexDirection: 'column', padding: '2rem' }}>
215
+ <div style={{ marginBottom: 'auto' }}>
216
+ <div style={{ display: 'flex', gap: '0.75rem', marginBottom: '1rem' }}>
217
+ <div style={{
218
+ padding: '0.25rem 0.75rem',
219
+ borderRadius: '20px',
220
+ background: result.domain_match === 'complete_mismatch'
221
+ ? 'rgba(239, 68, 68, 0.1)'
222
+ : result.domain_match === 'weak_match'
223
+ ? 'rgba(245, 158, 11, 0.1)'
224
+ : 'rgba(16, 185, 129, 0.1)',
225
+ color: result.domain_match === 'complete_mismatch'
226
+ ? 'var(--color-error)'
227
+ : result.domain_match === 'weak_match'
228
+ ? 'var(--color-warning)'
229
+ : 'var(--color-success)',
230
+ fontSize: '0.85rem',
231
+ fontWeight: 600,
232
+ display: 'inline-flex',
233
+ alignItems: 'center',
234
+ gap: '0.4rem',
235
+ border: `1px solid ${result.domain_match === 'complete_mismatch'
236
+ ? 'rgba(239, 68, 68, 0.2)'
237
+ : result.domain_match === 'weak_match'
238
+ ? 'rgba(245, 158, 11, 0.2)'
239
+ : 'rgba(16, 185, 129, 0.2)'}`
240
+ }}>
241
+ {result.domain_match === 'complete_mismatch' ? <AlertCircle size={14} /> : result.domain_match === 'weak_match' ? <AlertCircle size={14} /> : <CheckCircle size={14} />}
242
+ {result.domain_match === 'complete_mismatch' ? 'Field Mismatch' : result.domain_match === 'weak_match' ? 'Partial Match' : 'Strong Match'}
243
+ </div>
244
+ </div>
245
+ <h2 style={{ fontSize: '2rem', marginBottom: '0.5rem', lineHeight: 1.2 }}>{job.title}</h2>
246
+ <p style={{ fontSize: '1.1rem', color: 'var(--color-text-muted)', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
247
+ at <span style={{ color: 'var(--color-text-primary)', fontWeight: 600 }}>{job.company}</span>
248
+ </p>
249
+ </div>
250
+ <p style={{ fontSize: '1rem', lineHeight: 1.6, color: 'var(--color-text-secondary)', marginTop: '1.5rem', padding: '1.5rem', background: 'rgba(255,255,255,0.02)', borderRadius: '12px', border: '1px solid var(--glass-border)' }}>
251
+ {result.domain_match === 'complete_mismatch' ? (
252
+ <>Your background is in a different field. Optimizing would be difficult without fabricating experience, but we can help you transition.</>
253
+ ) : result.domain_match === 'weak_match' ? (
254
+ <>You have transferable skills but need more specific experience. Focus on projects to bridge the gap.</>
255
+ ) : result.score >= 80 ? (
256
+ <>Excellent fit! Your profile closely matches the requirements. Minor tweaks can make you standout even more.</>
257
+ ) : (
258
+ <>Good foundation. Adding specific keywords and project experience will significantly boost your match score.</>
259
+ )}
260
+ </p>
261
+ </div>
262
+ </div>
263
+
264
+ <div className="skills-grid" style={{ display: 'grid', gridTemplateColumns: isSmallScreen ? '1fr' : '1fr 1fr', gap: '2rem', marginBottom: '2rem' }}>
265
+ {/* Good Matches */}
266
+ <div className="card" style={{ padding: '2rem' }}>
267
+ <h3 style={{ color: 'var(--color-success)', display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.5rem' }}>
268
+ <CheckCircle size={24} /> Good Matches
269
+ </h3>
270
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.75rem' }}>
271
+ {result.matching_skills?.length > 0 ? (
272
+ result.matching_skills.map((skill, i) => (
273
+ <span key={i} style={{
274
+ padding: '0.5rem 1rem',
275
+ background: 'rgba(16, 185, 129, 0.1)',
276
+ border: '1px solid rgba(16, 185, 129, 0.2)',
277
+ borderRadius: '30px',
278
+ color: 'var(--color-text-primary)',
279
+ fontSize: '0.95rem',
280
+ fontWeight: 500
281
+ }}>
282
+ {skill}
283
+ </span>
284
+ ))
285
+ ) : (
286
+ <span style={{ fontStyle: 'italic', color: 'var(--color-text-muted)' }}>No direct matches found.</span>
287
+ )}
288
+ </div>
289
+ </div>
290
+
291
+ {/* Missing / To Improve */}
292
+ <div className="card" style={{ padding: '2rem' }}>
293
+ <h3 style={{ color: 'var(--color-error)', display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.5rem' }}>
294
+ <AlertCircle size={24} /> Missing / To Improve
295
+ </h3>
296
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.75rem' }}>
297
+ {result.missing_skills?.length > 0 ? (
298
+ result.missing_skills.map((skill, i) => (
299
+ <span key={i} style={{
300
+ padding: '0.5rem 1rem',
301
+ background: 'rgba(239, 68, 68, 0.05)',
302
+ border: '1px solid rgba(239, 68, 68, 0.2)',
303
+ borderRadius: '30px',
304
+ color: 'var(--color-text-secondary)',
305
+ fontSize: '0.95rem'
306
+ }}>
307
+ {skill}
308
+ </span>
309
+ ))
310
+ ) : result.score < 80 ? (
311
+ <span style={{ fontStyle: 'italic', color: 'var(--color-warning)' }}>
312
+ No specific missing keywords, but experience gaps detected. Check <strong>Recommendations</strong> below.
313
+ </span>
314
+ ) : (
315
+ <span style={{ fontStyle: 'italic', color: 'var(--color-text-muted)' }}>None! Great job.</span>
316
+ )}
317
+ </div>
318
+ </div>
319
+ </div>
320
+
321
+ {/* Recommendations */}
322
+ {result.project_recommendations && result.project_recommendations.length > 0 && result.domain_match !== 'complete_mismatch' && (
323
+ <div className="card" style={{ padding: '2rem', background: 'linear-gradient(to right, rgba(245, 158, 11, 0.05), transparent)' }}>
324
+ <h3 style={{ color: 'var(--color-warning)', display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1rem' }}>
325
+ <Wrench size={24} />
326
+ {['Software Engineering', 'Data Science/AI'].includes(result.detected_industry) ? 'Recommended Projects' : 'Recommended Experience'}
327
+ </h3>
328
+ <p style={{ color: 'var(--color-text-muted)', marginBottom: '1.5rem', maxWidth: '800px' }}>
329
+ Strengthen your profile by gaining experience in these specific areas:
330
+ </p>
331
+ <div style={{ display: 'grid', gap: '1rem' }}>
332
+ {result.project_recommendations.map((project, i) => (
333
+ <div key={i} style={{
334
+ padding: '1rem 1.5rem',
335
+ background: 'rgba(255, 255, 255, 0.03)',
336
+ borderRadius: '12px',
337
+ border: '1px solid var(--glass-border)',
338
+ display: 'flex',
339
+ alignItems: 'baseline',
340
+ gap: '1rem'
341
+ }}>
342
+ <span style={{ color: 'var(--color-warning)', fontWeight: 800 }}>{i + 1}.</span>
343
+ <span style={{ color: 'var(--color-text-primary)' }}>{project}</span>
344
+ </div>
345
+ ))}
346
+ </div>
347
+ </div>
348
+ )}
349
+
350
+ {/* Transition Plan (Mismatch) */}
351
+ {result.domain_match === 'complete_mismatch' && (
352
+ <div className="card" style={{ marginTop: '2rem', padding: '2.5rem' }}>
353
+ <div style={{ textAlign: 'center', marginBottom: '2rem' }}>
354
+ <div style={{ width: '56px', height: '56px', background: 'rgba(45, 212, 191, 0.1)', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 1.5rem', color: 'var(--color-primary)' }}>
355
+ <Briefcase size={28} />
356
+ </div>
357
+ <h3 style={{ fontSize: '1.75rem', marginBottom: '0.5rem' }}>Transition Roadmap</h3>
358
+ <p style={{ color: 'var(--color-text-secondary)' }}>Steps to break into this field</p>
359
+ </div>
360
+ <div style={{ display: 'grid', gridTemplateColumns: isSmallScreen ? '1fr' : 'repeat(auto-fit, minmax(250px, 1fr))', gap: '1.5rem' }}>
361
+ {/* Roadmap Cards */}
362
+ {[
363
+ { title: 'Take Courses', desc: `Learn ${result.missing_skills?.slice(0, 2).join(', ')} online.` },
364
+ { title: 'Get Certified', desc: `Obtain certifications relevant to ${job.title}.` },
365
+ { title: 'Build Projects', desc: 'Create a portfolio to show hands-on skills.' },
366
+ { title: 'Start Junior', desc: 'Look for entry-level roles with training.' }
367
+ ].map((item, idx) => (
368
+ <div key={idx} className="card" style={{ padding: '1.5rem', background: 'rgba(255,255,255,0.02)' }}>
369
+ <div style={{ width: '28px', height: '28px', background: 'var(--color-primary)', borderRadius: '6px', color: '#050b14', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 'bold', marginBottom: '1rem' }}>{idx + 1}</div>
370
+ <h4 style={{ marginBottom: '0.5rem' }}>{item.title}</h4>
371
+ <p style={{ fontSize: '0.9rem', color: 'var(--color-text-muted)' }}>{item.desc}</p>
372
+ </div>
373
+ ))}
374
+ </div>
375
+ </div>
376
+ )}
377
+
378
+ <div className="actions" style={{ marginTop: '3rem', display: 'flex', justifyContent: 'center', gap: '1rem', borderTop: '1px solid var(--color-border)', paddingTop: '2rem' }}>
379
+ <button className="btn btn-secondary" style={{ background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px' }} onClick={() => { setFile(null); setResult(null); }}>
380
+ Upload Different CV
381
+ </button>
382
+ {result.domain_match !== 'complete_mismatch' ? (
383
+ <button
384
+ className="btn btn-secondary btn-lg no-hover-shadow"
385
+ onClick={onNext}
386
+ style={{ background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px', boxShadow: 'none' }}
387
+ >
388
+ Optimize CV
389
+ </button>
390
+ ) : (
391
+ <button className="btn btn-secondary" style={{ background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px' }} onClick={onBack}>
392
+ Find a Better Match
393
+ </button>
394
+ )}
395
+ </div>
396
+ </div>
397
+ );
398
+ }
399
+
400
+ // Floating "Analyzing" State
401
+ if (analyzing) {
402
+ return (
403
+ <div className="loading" style={{ textAlign: 'center', padding: '0', perspective: '1000px', marginTop: '3rem', minHeight: '50vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
404
+ <div style={{ position: 'relative' }}>
405
+ <motion.div
406
+ animate={{ rotateY: 360 }}
407
+ transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
408
+ style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}
409
+ >
410
+ <FileText size={80} color="var(--color-primary)" strokeWidth={1.5} />
411
+ </motion.div>
412
+ <motion.div
413
+ animate={{
414
+ y: [-5, 5, -5]
415
+ }}
416
+ transition={{ duration: 1.5, repeat: Infinity, ease: "easeInOut" }}
417
+ style={{
418
+ position: 'absolute',
419
+ bottom: -10,
420
+ right: -25
421
+ }}
422
+ >
423
+ <ScanLine size={28} color="var(--color-primary)" />
424
+ </motion.div>
425
+ </div>
426
+ <h2 className="hero-title" style={{ marginTop: '1.5rem', fontSize: '2.5rem' }}>
427
+ Analyzing Your CV...
428
+ </h2>
429
+ </div>
430
+ );
431
+ }
432
+
433
+ return (
434
+ <div className="cv-upload-container card fade-in" style={{ maxWidth: '600px', margin: '0 auto', textAlign: 'center', padding: '3rem', position: 'relative' }}>
435
+ <button
436
+ className="btn btn-ghost"
437
+ onClick={onBack}
438
+ style={{
439
+ position: 'absolute',
440
+ top: '1.5rem',
441
+ left: '1.5rem',
442
+ color: 'var(--color-text-muted)',
443
+ display: 'flex',
444
+ alignItems: 'center',
445
+ gap: '0.5rem',
446
+ padding: '0.5rem 1rem',
447
+ borderRadius: '20px',
448
+ fontSize: '0.9rem'
449
+ }}
450
+ >
451
+ <ArrowLeft size={18} /> Back
452
+ </button>
453
+
454
+ <div style={{ marginBottom: '2rem' }}>
455
+ <div style={{ height: '5rem' }}></div>
456
+ <h2>Analyze your fit for {job.title}</h2>
457
+ <p style={{ color: 'var(--color-text-muted)' }}>at {job.company}</p>
458
+ </div>
459
+
460
+ {/* Error Alert - shown at top */}
461
+ {displayError && (
462
+ <div className="alert alert-error" style={{ marginBottom: '1.5rem', textAlign: 'left', display: 'flex', alignItems: 'flex-start', gap: '0.75rem', position: 'relative' }}>
463
+ <AlertCircle size={20} style={{ flexShrink: 0, marginTop: '2px' }} />
464
+ <div style={{ fontSize: '0.95rem', lineHeight: 1.5, flex: 1 }}>
465
+ {displayError.includes('buymeacoffee') ? (
466
+ <span>
467
+ Server is busy due to high demand. Please help keep the servers running β€” {' '}
468
+ <a
469
+ href="https://buymeacoffee.com/manojthapa"
470
+ target="_blank"
471
+ rel="noopener noreferrer"
472
+ style={{ color: 'var(--color-warning)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: '0.25rem' }}
473
+ >
474
+ <Coffee size={16} /> Buy me a coffee
475
+ </a>
476
+ </span>
477
+ ) : (
478
+ displayError
479
+ )}
480
+ </div>
481
+ <button
482
+ onClick={() => { setError(null); setDismissedError(true); }}
483
+ style={{
484
+ background: 'transparent',
485
+ border: 'none',
486
+ color: 'inherit',
487
+ cursor: 'pointer',
488
+ padding: '0.25rem',
489
+ display: 'flex',
490
+ alignItems: 'center',
491
+ justifyContent: 'center',
492
+ opacity: 0.7,
493
+ transition: 'opacity 0.2s'
494
+ }}
495
+ onMouseEnter={(e) => e.target.style.opacity = 1}
496
+ onMouseLeave={(e) => e.target.style.opacity = 0.7}
497
+ >
498
+ <X size={18} />
499
+ </button>
500
+ </div>
501
+ )}
502
+
503
+ <div
504
+ className={`dropzone ${isDragging ? 'dragging' : ''}`}
505
+ onDragEnter={handleDrag}
506
+ onDragLeave={handleDrag}
507
+ onDragOver={handleDrag}
508
+ onDrop={handleDrop}
509
+ style={{
510
+ border: isDragging ? '2px dashed var(--color-primary)' : 'none',
511
+ borderRadius: '12px',
512
+ padding: '3rem',
513
+ cursor: 'pointer',
514
+ transition: 'all 0.2s',
515
+ background: isDragging ? 'rgba(45, 212, 191, 0.05)' : 'transparent',
516
+ }}
517
+ >
518
+ {!file ? (
519
+ <>
520
+ <Upload size={64} style={{ color: 'var(--color-text-muted)', marginBottom: '1rem' }} />
521
+ <h3>Drop your CV here</h3>
522
+ <p style={{ margin: '1rem 0', color: 'var(--color-text-muted)' }}>or</p>
523
+ <label className="btn btn-secondary">
524
+ Browse Files
525
+ <input type="file" onChange={handleFileSelect} accept=".pdf,.docx" hidden />
526
+ </label>
527
+ <p style={{ marginTop: '1rem', fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>Supported formats: PDF, DOCX</p>
528
+ </>
529
+ ) : (
530
+ <div className="file-preview">
531
+ <FileText size={48} style={{ color: 'var(--color-primary)' }} />
532
+ <h3 style={{ marginTop: '1rem' }}>{file.name}</h3>
533
+ <p style={{ color: 'var(--color-text-muted)' }}>{(file.size / 1024 / 1024).toFixed(2)} MB</p>
534
+ <button
535
+ onClick={(e) => { e.stopPropagation(); setFile(null); }}
536
+ style={{
537
+ marginTop: '1rem',
538
+ background: 'transparent',
539
+ border: 'none',
540
+ color: 'var(--color-text-muted)',
541
+ cursor: 'pointer',
542
+ display: 'flex',
543
+ alignItems: 'center',
544
+ gap: '0.5rem',
545
+ padding: '0.5rem',
546
+ borderRadius: '8px',
547
+ transition: 'all 0.2s',
548
+ margin: '1rem auto 0'
549
+ }}
550
+ onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--color-error)'; e.currentTarget.style.background = 'rgba(239, 68, 68, 0.1)'; }}
551
+ onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'transparent'; }}
552
+ >
553
+ <Trash2 size={18} /> Remove File
554
+ </button>
555
+ </div>
556
+ )}
557
+ </div>
558
+ </div >
559
+ );
560
+ }
561
+
562
+ export default CVAnalysis;
frontend/src/components/DocumentPreview.jsx ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+ import { Download, FileText, Check, ExternalLink, Sparkles, AlertTriangle, Eye } from 'lucide-react';
3
+
4
+ function DocumentPreview({ cv, textContent, isPdf, onDownloadCV, analysisResult, job, onBack }) {
5
+ const [isMobile, setIsMobile] = useState(window.innerWidth < 1235);
6
+
7
+ useEffect(() => {
8
+ const handleResize = () => setIsMobile(window.innerWidth < 1235);
9
+ window.addEventListener('resize', handleResize);
10
+ return () => window.removeEventListener('resize', handleResize);
11
+ }, []);
12
+
13
+ // Mobile Layout - stacked without embedded PDF
14
+ if (isMobile) {
15
+ return (
16
+ <div className="preview-container-mobile fade-in" style={{ maxWidth: '600px', margin: '0 auto', padding: '0 1rem' }}>
17
+ {/* Optimization Report Card */}
18
+ <div className="card" style={{ marginBottom: '1.5rem' }}>
19
+ <div className="card-header">
20
+ <h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
21
+ <Sparkles size={20} color="var(--color-primary)" /> Optimization Report
22
+ </h3>
23
+ </div>
24
+
25
+ <div style={{ padding: '1.5rem' }}>
26
+ {analysisResult && (
27
+ <>
28
+ <div className="stat-item" style={{ marginBottom: '1.5rem' }}>
29
+ <label>New Match Score</label>
30
+ <div style={{ fontSize: '2.5rem', fontWeight: 700, color: analysisResult.score >= 80 ? 'var(--color-success)' : 'var(--color-warning)' }}>
31
+ {analysisResult.score}%
32
+ </div>
33
+ <div style={{ width: '100%', background: 'var(--color-bg-secondary)', height: '6px', borderRadius: '3px', marginTop: '0.5rem' }}>
34
+ <div style={{ width: `${analysisResult.score}%`, background: analysisResult.score >= 80 ? 'var(--color-success)' : 'var(--color-warning)', height: '100%', borderRadius: '3px' }}></div>
35
+ </div>
36
+ </div>
37
+
38
+ {analysisResult.matching_skills?.length > 0 && (
39
+ <div className="stat-list" style={{ marginBottom: '1.5rem' }}>
40
+ <h4 style={{ marginBottom: '0.75rem', fontSize: '0.85rem', textTransform: 'uppercase', color: 'var(--color-text-muted)' }}>
41
+ Skills Added
42
+ </h4>
43
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
44
+ {analysisResult.matching_skills.slice(0, 6).map((skill, i) => (
45
+ <span key={i} style={{ padding: '0.25rem 0.75rem', background: 'rgba(45, 212, 191, 0.1)', border: '1px solid rgba(45, 212, 191, 0.3)', borderRadius: '20px', fontSize: '0.8rem', color: 'var(--color-primary)' }}>
46
+ <Check size={12} style={{ marginRight: '0.25rem' }} /> {skill}
47
+ </span>
48
+ ))}
49
+ {analysisResult.matching_skills.length > 6 && (
50
+ <span style={{ padding: '0.25rem 0.75rem', fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
51
+ +{analysisResult.matching_skills.length - 6} more
52
+ </span>
53
+ )}
54
+ </div>
55
+ </div>
56
+ )}
57
+ </>
58
+ )}
59
+
60
+ {/* Action Buttons */}
61
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
62
+ {isPdf && (
63
+ <a
64
+ href={cv}
65
+ target="_blank"
66
+ rel="noopener noreferrer"
67
+ className="btn btn-secondary btn-full"
68
+ style={{ justifyContent: 'center', background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px' }}
69
+ >
70
+ View CV
71
+ </a>
72
+ )}
73
+
74
+ <button className="btn btn-secondary btn-full" onClick={onDownloadCV} style={{ justifyContent: 'center', background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px' }}>
75
+ Download CV
76
+ </button>
77
+
78
+ {job && (
79
+ <a
80
+ href={job.redirect_url}
81
+ target="_blank"
82
+ rel="noopener noreferrer"
83
+ className="btn btn-secondary btn-full"
84
+ style={{ justifyContent: 'center', background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px' }}
85
+ >
86
+ Apply
87
+ </a>
88
+ )}
89
+
90
+ </div>
91
+ </div>
92
+ </div>
93
+ </div>
94
+ );
95
+ }
96
+
97
+ // Desktop Layout - side by side with embedded PDF
98
+ return (
99
+ <div className="preview-container" style={{ display: 'grid', gridTemplateColumns: 'minmax(300px, 1fr) 2fr', gap: '2rem', minHeight: '500px', maxHeight: 'calc(100vh - 250px)', paddingBottom: '2rem' }}>
100
+
101
+ {/* Sidebar / Stats */}
102
+ <div className="preview-sidebar fade-in">
103
+ <div className="card" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
104
+ <div className="card-header">
105
+ <h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
106
+ <Sparkles size={20} color="var(--color-primary)" /> Optimization Report
107
+ </h3>
108
+ </div>
109
+
110
+ <div style={{ padding: '1.5rem', flex: 1, overflowY: 'auto' }}>
111
+ {analysisResult && (
112
+ <>
113
+ <div className="stat-item" style={{ marginBottom: '1.5rem' }}>
114
+ <label>New Match Score</label>
115
+ <div style={{ fontSize: '2.5rem', fontWeight: 700, color: analysisResult.score === 100 ? 'var(--color-success)' : (analysisResult.score >= 80 ? 'var(--color-success)' : 'var(--color-warning)') }}>
116
+ {analysisResult.score}%
117
+ </div>
118
+ <div style={{ width: '100%', background: 'var(--color-bg-secondary)', height: '6px', borderRadius: '3px', marginTop: '0.5rem' }}>
119
+ <div style={{ width: `${analysisResult.score}%`, background: analysisResult.score === 100 ? 'var(--color-success)' : (analysisResult.score >= 80 ? 'var(--color-success)' : 'var(--color-warning)'), height: '100%', borderRadius: '3px' }}></div>
120
+ </div>
121
+
122
+ {/* Why not 100%? Explanation - Show whenever score is below 100 */}
123
+ {analysisResult.score < 100 ? (
124
+ <div style={{ marginTop: '1rem', padding: '0.75rem', background: 'rgba(245, 158, 11, 0.1)', border: '1px solid rgba(245, 158, 11, 0.3)', borderRadius: 'var(--radius-sm)', fontSize: '0.8rem' }}>
125
+ <div style={{ color: 'var(--color-warning)', fontWeight: 600, marginBottom: '0.25rem' }}>
126
+ Why not 100%?
127
+ </div>
128
+ <div style={{ color: 'var(--color-text-secondary)' }}>
129
+ {analysisResult.missing_skills && analysisResult.missing_skills.length > 0 ? (
130
+ ['Software Engineering', 'Data Science/AI'].includes(analysisResult.detected_industry) ? (
131
+ <>You need projects demonstrating: {analysisResult.missing_skills.slice(0, 3).join(', ')}{analysisResult.missing_skills.length > 3 ? ` + ${analysisResult.missing_skills.length - 3} more` : ''}</>
132
+ ) : (
133
+ <>You need experience demonstrating: {analysisResult.missing_skills.slice(0, 3).join(', ')}{analysisResult.missing_skills.length > 3 ? ` + ${analysisResult.missing_skills.length - 3} more` : ''}</>
134
+ )
135
+ ) : (
136
+ ['Software Engineering', 'Data Science/AI'].includes(analysisResult.detected_industry) ? (
137
+ <>Build more projects with relevant technologies to reach 100%. The job requires specific experience we couldn't add without fabricating.</>
138
+ ) : (
139
+ <>Gain more experience in relevant areas to reach 100%. The job requires specific experience we couldn't add without fabricating.</>
140
+ )
141
+ )}
142
+ </div>
143
+ </div>
144
+ ) : (
145
+ <div style={{ marginTop: '0.75rem', color: 'var(--color-success)', fontSize: '0.85rem', fontWeight: 500 }}>
146
+ ✨ Perfect match! All required skills covered.
147
+ </div>
148
+ )}
149
+ </div>
150
+
151
+ <div className="stat-list">
152
+ <h4 style={{ marginBottom: '1rem', fontSize: '0.9rem', textTransform: 'uppercase', color: 'var(--color-text-muted)' }}>
153
+ skills added
154
+ </h4>
155
+ <ul style={{ listStyle: 'none', padding: 0 }}>
156
+ {analysisResult.matching_skills?.slice(0, 6).map((skill, i) => (
157
+ <li key={i} style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--color-border)', fontSize: '0.9rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
158
+ <Check size={14} color="var(--color-success)" /> {skill}
159
+ </li>
160
+ ))}
161
+ {analysisResult.matching_skills?.length > 6 && (
162
+ <li style={{ padding: '0.5rem 0', color: 'var(--color-text-muted)', fontSize: '0.8rem' }}>
163
+ + {analysisResult.matching_skills.length - 6} more
164
+ </li>
165
+ )}
166
+ </ul>
167
+ </div>
168
+
169
+ {/* Remaining Gaps - What couldn't be added */}
170
+ {analysisResult.missing_skills && analysisResult.missing_skills.length > 0 && (
171
+ <div className="remaining-gaps" style={{ marginTop: '1.5rem' }}>
172
+ <h4 style={{ marginBottom: '0.75rem', fontSize: '0.9rem', textTransform: 'uppercase', color: 'var(--color-warning)' }}>
173
+ <AlertTriangle size={14} style={{ marginRight: '0.5rem' }} />
174
+ Gaps Remaining
175
+ </h4>
176
+
177
+ <ul style={{ listStyle: 'none', padding: 0 }}>
178
+ {analysisResult.missing_skills.slice(0, 4).map((skill, i) => (
179
+ <li key={i} style={{ padding: '0.4rem 0', fontSize: '0.85rem', color: 'var(--color-text-secondary)' }}>
180
+ β€’ {skill}
181
+ </li>
182
+ ))}
183
+ {analysisResult.missing_skills.length > 4 && (
184
+ <li style={{ padding: '0.4rem 0', color: 'var(--color-text-muted)', fontSize: '0.8rem' }}>
185
+ + {analysisResult.missing_skills.length - 4} more
186
+ </li>
187
+ )}
188
+ </ul>
189
+
190
+ {/* Industry-specific improvement suggestions */}
191
+ <div style={{ marginTop: '1rem', padding: '0.75rem', background: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.3)', borderRadius: 'var(--radius-sm)', fontSize: '0.8rem' }}>
192
+ <div style={{ color: 'var(--color-primary)', fontWeight: 600, marginBottom: '0.5rem' }}>
193
+ πŸ’‘ How to improve:
194
+ </div>
195
+ <div style={{ color: 'var(--color-text-secondary)' }}>
196
+ {['Software Engineering', 'Data Science/AI'].includes(analysisResult.detected_industry) ? (
197
+ <>Build personal projects or contribute to open-source to demonstrate: <strong>{analysisResult.missing_skills.slice(0, 2).join(', ')}</strong></>
198
+ ) : analysisResult.detected_industry === 'Healthcare' ? (
199
+ <>Gain hands-on experience through clinical rotations, CPD courses, or volunteering to demonstrate: <strong>{analysisResult.missing_skills.slice(0, 2).join(', ')}</strong></>
200
+ ) : analysisResult.detected_industry === 'Finance' ? (
201
+ <>Consider relevant certifications (CFA, ACCA) or internships to demonstrate: <strong>{analysisResult.missing_skills.slice(0, 2).join(', ')}</strong></>
202
+ ) : analysisResult.detected_industry === 'Marketing' ? (
203
+ <>Run personal campaigns, get Google/HubSpot certifications to demonstrate: <strong>{analysisResult.missing_skills.slice(0, 2).join(', ')}</strong></>
204
+ ) : (
205
+ <>Seek internships, certifications, or volunteering opportunities to demonstrate: <strong>{analysisResult.missing_skills.slice(0, 2).join(', ')}</strong></>
206
+ )}
207
+ </div>
208
+ </div>
209
+
210
+ <p style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)', marginTop: '0.75rem', fontStyle: 'italic' }}>
211
+ We don't fabricate details. Gain real experience to close these gaps.
212
+ </p>
213
+ </div>
214
+ )}
215
+ </>
216
+ )}
217
+
218
+ <div style={{ marginTop: 'auto', paddingTop: '1.5rem', display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
219
+ <button className="btn btn-secondary btn-full" style={{ background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px' }} onClick={onDownloadCV}>
220
+ Download CV
221
+ </button>
222
+
223
+ {job && (
224
+ <a
225
+ href={job.redirect_url}
226
+ target="_blank"
227
+ rel="noopener noreferrer"
228
+ className="btn btn-secondary btn-full"
229
+ style={{ background: 'rgba(10, 22, 37, 0.8)', border: '1px solid rgba(0, 229, 255, 0.2)', borderRadius: '12px' }}
230
+ >
231
+ Apply
232
+ </a>
233
+ )}
234
+ </div>
235
+ </div>
236
+ </div>
237
+ </div>
238
+
239
+ {/* Document Preview */}
240
+ <div className="document-viewer card fade-in" style={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
241
+ <div className="viewer-header" style={{ padding: '1rem', borderBottom: '1px solid var(--color-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--color-bg-secondary)' }}>
242
+ <span style={{ fontWeight: 500, display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
243
+ <FileText size={18} /> Generated Application
244
+ </span>
245
+ {isPdf && (
246
+ <a href={cv} target="_blank" rel="noopener noreferrer" className="btn btn-sm btn-text">
247
+ <ExternalLink size={14} /> Open in New Tab
248
+ </a>
249
+ )}
250
+ </div>
251
+
252
+ <div style={{ flex: 1, background: '#525659', position: 'relative' }}>
253
+ {isPdf ? (
254
+ <iframe
255
+ src={`${cv}#toolbar=0&navpanes=0`}
256
+ title="CV Preview"
257
+ style={{ width: '100%', height: '100%', border: 'none' }}
258
+ />
259
+ ) : (
260
+ <div style={{ padding: '2rem', height: '100%', overflowY: 'auto', background: 'white', color: 'black', fontFamily: 'monospace', whiteSpace: 'pre-wrap' }}>
261
+ {textContent}
262
+ </div>
263
+ )}
264
+ </div>
265
+ </div>
266
+ </div>
267
+ );
268
+ }
269
+
270
+ export default DocumentPreview;
frontend/src/components/GenerationProgress.jsx ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react';
2
+ import { motion } from 'framer-motion';
3
+
4
+ const GenerationProgress = ({ type = 'cv' }) => {
5
+ const [step, setStep] = useState(0);
6
+
7
+ const cvSteps = [
8
+ "Analyzing job requirements...",
9
+ "Identifying your best achievements...",
10
+ "Drafting professional summary...",
11
+ "Optimizing bullet points with STAR method...",
12
+ "Applying ATS-friendly formatting...",
13
+ "Compiling Professional CV..."
14
+ ];
15
+
16
+ const coverLetterSteps = [
17
+ "Analyzing job requirements...",
18
+ "Matching your experience...",
19
+ "Crafting compelling opening...",
20
+ "Highlighting key achievements...",
21
+ "Writing professional closing...",
22
+ "Generating PDF..."
23
+ ];
24
+
25
+ const steps = type === 'cover_letter' ? coverLetterSteps : cvSteps;
26
+
27
+ useEffect(() => {
28
+ const interval = setInterval(() => {
29
+ setStep(s => (s < steps.length - 1 ? s + 1 : s));
30
+ }, 2500);
31
+ return () => clearInterval(interval);
32
+ }, [steps.length]);
33
+
34
+ return (
35
+ <motion.p
36
+ key={step}
37
+ className="hero-title"
38
+ initial={{ opacity: 0, y: 10 }}
39
+ animate={{ opacity: 1, y: 0 }}
40
+ exit={{ opacity: 0, y: -10 }}
41
+ style={{ fontSize: '2rem', marginTop: '1.5rem', marginBottom: 0 }}
42
+ >
43
+ {steps[step]}
44
+ </motion.p>
45
+ );
46
+ };
47
+
48
+ export default GenerationProgress;
frontend/src/components/JobList.jsx ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react';
2
+ import { MapPin, Calendar, DollarSign, Clock, Building, Search, ChevronLeft, ChevronRight, Briefcase, ChevronDown, SearchX } from 'lucide-react';
3
+ import { motion } from 'framer-motion';
4
+
5
+ function JobList({ jobs, selectedJob, onSelectJob, cvSkills = [], postedFilter, setPostedFilter, hasSearched }) {
6
+
7
+ // Filter jobs based on posted date - HMR Trigger
8
+ const getFilteredJobs = () => {
9
+ if (!jobs) return [];
10
+
11
+ const now = new Date();
12
+ return jobs.filter(job => {
13
+ if (postedFilter === 'all') return true;
14
+
15
+ // Use 'created' field (ISO date from backend)
16
+ const postedDate = new Date(job.created);
17
+ if (isNaN(postedDate.getTime())) return true; // Skip if invalid date
18
+
19
+ const diffTime = now - postedDate;
20
+ const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
21
+
22
+ if (postedFilter === 'today') return diffDays <= 1;
23
+ if (postedFilter === '3days') return diffDays <= 3;
24
+ if (postedFilter === 'week') return diffDays <= 7;
25
+ if (postedFilter === 'month') return diffDays <= 30;
26
+
27
+ return true;
28
+ });
29
+ };
30
+
31
+ const filteredJobs = getFilteredJobs();
32
+
33
+ // Helper to format salary - use backend's salary_display or format manually
34
+ const formatSalary = (job) => {
35
+ if (job.salary_display && job.salary_display !== 'Salary not specified') {
36
+ return job.salary_display;
37
+ }
38
+ if (!job.salary_min && !job.salary_max) return 'Competitive';
39
+ const curr = 'Β£';
40
+ if (job.salary_min && job.salary_max) {
41
+ return `${curr}${job.salary_min.toLocaleString()} - ${curr}${job.salary_max.toLocaleString()}`;
42
+ }
43
+ if (job.salary_min) return `${curr}${job.salary_min.toLocaleString()}+`;
44
+ return `Up to ${curr}${job.salary_max.toLocaleString()}`;
45
+ };
46
+
47
+ // Helper to format date with relative display
48
+ const formatDate = (dateString) => {
49
+ if (!dateString) return '';
50
+ const date = new Date(dateString);
51
+ if (isNaN(date.getTime())) return '';
52
+
53
+ const now = new Date();
54
+ const diffTime = now - date;
55
+ const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
56
+
57
+ if (diffDays === 0) return 'Today';
58
+ if (diffDays === 1) return 'Yesterday';
59
+ if (diffDays <= 7) return `${diffDays} days ago`;
60
+
61
+ return date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
62
+ };
63
+
64
+ // Helper to strip HTML and decode entities
65
+ const stripHtml = (html) => {
66
+ if (!html) return '';
67
+ // First decode common entities
68
+ const decoded = html
69
+ .replace(/&lt;/g, '<')
70
+ .replace(/&gt;/g, '>')
71
+ .replace(/&quot;/g, '"')
72
+ .replace(/&amp;/g, '&')
73
+ .replace(/&nbsp;/g, ' ');
74
+
75
+ // Then strip tags
76
+ return decoded.replace(/<[^>]*>?/gm, '');
77
+ };
78
+
79
+ // Helper to clean snippet - removes redundant title/salary info from start
80
+ const cleanSnippet = (description, title) => {
81
+ if (!description) return '';
82
+ let text = stripHtml(description).trim();
83
+
84
+ // If the description starts with the job title (or part of it), skip past it
85
+ const titleWords = title?.toLowerCase().split(/\s+/).slice(0, 3).join(' ') || '';
86
+ const textLower = text.toLowerCase();
87
+
88
+ if (titleWords && textLower.startsWith(titleWords)) {
89
+ // Find where the actual description starts (after dashes, colons, or similar)
90
+ const afterTitle = text.substring(titleWords.length);
91
+ const match = afterTitle.match(/^[\s\-–—:,]+(.+)/s);
92
+ if (match) {
93
+ text = match[1].trim();
94
+ }
95
+ }
96
+
97
+ // Also skip common preamble patterns like "Role:", "Job Title:", etc.
98
+ text = text.replace(/^(Role|Position|Job Title|Job Description|About the Role|Overview|Summary|Description)[\s:–-]+/i, '');
99
+
100
+ return text;
101
+ };
102
+
103
+ // Pagination
104
+ const JOBS_PER_PAGE = 9;
105
+ const [currentPage, setCurrentPage] = useState(1);
106
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
107
+
108
+ // Reset page when filter changes or jobs change
109
+ const totalPages = Math.ceil(filteredJobs.length / JOBS_PER_PAGE);
110
+ const validPage = Math.min(currentPage, totalPages || 1);
111
+
112
+ const startIndex = (validPage - 1) * JOBS_PER_PAGE;
113
+ const paginatedJobs = filteredJobs.slice(startIndex, startIndex + JOBS_PER_PAGE);
114
+
115
+ const container = {
116
+ hidden: { opacity: 0 },
117
+ show: {
118
+ opacity: 1,
119
+ transition: {
120
+ staggerChildren: 0.05
121
+ }
122
+ }
123
+ };
124
+
125
+ const item = {
126
+ hidden: { opacity: 0, y: 20 },
127
+ show: { opacity: 1, y: 0 }
128
+ };
129
+
130
+
131
+
132
+ return (
133
+ <div className="job-list-container">
134
+ {/* Controls / Filter Bar */}
135
+ <div className="list-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
136
+ <h2 style={{ fontSize: '1.5rem', fontWeight: 700, margin: 0 }}>
137
+ <span className="text-gradient">{filteredJobs.length} Jobs Found</span>
138
+ </h2>
139
+
140
+ <div className="filter-select" style={{ position: 'relative', zIndex: 20 }}>
141
+ <button
142
+ onClick={() => setIsDropdownOpen(!isDropdownOpen)}
143
+ className="btn"
144
+ style={{
145
+ background: 'rgba(255, 255, 255, 0.05)',
146
+ border: '1px solid var(--color-border)',
147
+ color: 'var(--color-text-primary)',
148
+ padding: '0.6rem 1.25rem',
149
+ borderRadius: '12px',
150
+ display: 'flex',
151
+ alignItems: 'center',
152
+ gap: '0.75rem',
153
+ minWidth: '160px',
154
+ justifyContent: 'space-between',
155
+ cursor: 'pointer'
156
+ }}
157
+ >
158
+ <span style={{ fontSize: '0.9rem' }}>
159
+ {postedFilter === 'all' && 'Any time'}
160
+ {postedFilter === 'today' && 'Past 24 hours'}
161
+ {postedFilter === '3days' && 'Past 3 days'}
162
+ {postedFilter === 'week' && 'Past week'}
163
+ {postedFilter === 'month' && 'Past month'}
164
+ </span>
165
+ <ChevronDown size={16} style={{ transition: 'transform 0.3s', transform: isDropdownOpen ? 'rotate(180deg)' : 'rotate(0deg)' }} />
166
+ </button>
167
+
168
+ {isDropdownOpen && (
169
+ <div
170
+ style={{
171
+ position: 'absolute',
172
+ top: '120%',
173
+ right: 0,
174
+ width: '100%',
175
+ minWidth: '180px',
176
+ background: '#050b14',
177
+ backdropFilter: 'none',
178
+ border: '1px solid var(--color-border)',
179
+ borderRadius: '12px',
180
+ padding: '0.5rem',
181
+ boxShadow: '0 10px 40px -10px rgba(0,0,0,0.5)',
182
+ display: 'flex',
183
+ flexDirection: 'column',
184
+ gap: '0.25rem'
185
+ }}
186
+ >
187
+ {[
188
+ { value: 'all', label: 'Any time' },
189
+ { value: 'today', label: 'Past 24 hours' },
190
+ { value: '3days', label: 'Past 3 days' },
191
+ { value: 'week', label: 'Past week' },
192
+ { value: 'month', label: 'Past month' }
193
+ ].map(option => (
194
+ <button
195
+ key={option.value}
196
+ onClick={() => {
197
+ setPostedFilter(option.value);
198
+ setCurrentPage(1);
199
+ setIsDropdownOpen(false);
200
+ }}
201
+ style={{
202
+ background: postedFilter === option.value ? 'rgba(45, 212, 191, 0.15)' : 'transparent',
203
+ color: postedFilter === option.value ? 'var(--color-primary)' : 'var(--color-text-secondary)',
204
+ border: 'none',
205
+ padding: '0.6rem 1rem',
206
+ borderRadius: '8px',
207
+ textAlign: 'left',
208
+ cursor: 'pointer',
209
+ fontSize: '0.9rem',
210
+ transition: 'all 0.2s'
211
+ }}
212
+ className="dropdown-item"
213
+ >
214
+ {option.label}
215
+ </button>
216
+ ))}
217
+ </div>
218
+ )}
219
+ </div>
220
+ </div>
221
+
222
+ {/* List */}
223
+ <motion.div
224
+ className="job-grid"
225
+ variants={container}
226
+ initial="hidden"
227
+ animate="show"
228
+ style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: '1.5rem' }}
229
+ >
230
+ {filteredJobs.length === 0 ? (
231
+ <div className="card no-hover" style={{ padding: '4rem 2rem', gridColumn: '1 / -1', maxWidth: '800px', margin: '0 auto', width: '100%', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
232
+ <div style={{ color: 'var(--color-primary)', marginBottom: '1.5rem', background: 'rgba(45, 212, 191, 0.1)', display: 'inline-flex', padding: '1.5rem', borderRadius: '50%' }}>
233
+ <SearchX size={48} />
234
+ </div>
235
+ <h3 style={{ fontSize: '1.5rem', marginBottom: '0.5rem' }}>No jobs match your criteria</h3>
236
+ <p style={{ color: 'var(--color-text-secondary)', maxWidth: '400px', margin: '0 auto' }}>Try adjusting your search terms, location, or the "Date Posted" filter to see more results.</p>
237
+ </div>
238
+ ) : (
239
+ paginatedJobs.map(job => (
240
+ <motion.div
241
+ key={job.id}
242
+ variants={item}
243
+ className={`job-card card ${selectedJob?.id === job.id ? 'active' : ''}`}
244
+ onClick={() => onSelectJob(job)}
245
+ whileHover={{ y: -5, transition: { duration: 0.2 } }}
246
+ style={{ cursor: 'pointer', display: 'flex', flexDirection: 'column', height: '100%' }}
247
+ >
248
+ <div className="job-header" style={{ marginBottom: '1rem', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '1rem' }}>
249
+ <div style={{ flex: 1 }}>
250
+ <h3 className="job-title" style={{ fontSize: '1.15rem', lineHeight: '1.4' }}>{job.title}</h3>
251
+ {job.location && (
252
+ <span className="job-location" style={{ display: 'flex', alignItems: 'center', gap: '0.25rem', fontSize: '0.9rem', color: 'var(--color-text-secondary)', marginTop: '0.25rem' }}>
253
+ <MapPin size={14} /> {job.location}
254
+ </span>
255
+ )}
256
+ </div>
257
+ <span style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: '0.25rem', flexShrink: 0, marginTop: '0.2rem' }}>
258
+ <Calendar size={14} />
259
+ {formatDate(job.created)}
260
+ </span>
261
+ </div>
262
+
263
+ <div className="job-company" style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '1rem', fontWeight: 600 }}>
264
+ <div style={{ padding: '0.4rem', background: 'rgba(255,255,255,0.05)', borderRadius: '8px' }}>
265
+ <Building size={16} />
266
+ </div>
267
+ {job.company}
268
+ </div>
269
+
270
+ <div className="job-meta" style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginBottom: '1rem' }}>
271
+ <span className="meta-item">
272
+ <DollarSign size={14} /> {formatSalary(job)}
273
+ </span>
274
+ {job.contract_time && job.contract_time !== 'Unknown' && (
275
+ <span className="meta-item">
276
+ <Clock size={14} /> {job.contract_time}
277
+ </span>
278
+ )}
279
+ </div>
280
+
281
+
282
+ <div className="job-footer" style={{ marginTop: 'auto', display: 'flex', gap: '1rem' }}>
283
+ <button className="btn btn-outline btn-sm btn-full">
284
+ Analyze Fit
285
+ </button>
286
+ <a
287
+ href={job.redirect_url}
288
+ target="_blank"
289
+ rel="noopener noreferrer"
290
+ className="btn btn-secondary btn-sm"
291
+ onClick={(e) => e.stopPropagation()}
292
+ title="View Original"
293
+ >
294
+ View
295
+ </a>
296
+ </div>
297
+ </motion.div>
298
+ ))
299
+ )}
300
+ </motion.div>
301
+
302
+ {/* Pagination Controls */}
303
+ {totalPages > 1 && (
304
+ <div className="pagination" style={{
305
+ flexWrap: 'wrap',
306
+ marginTop: '2rem',
307
+ padding: '0',
308
+ width: '100%',
309
+ maxWidth: '100%',
310
+ margin: '3rem auto 0',
311
+ flexDirection: 'column'
312
+ }}>
313
+ <div style={{ marginBottom: '1rem', color: 'var(--color-text-muted)', fontSize: '0.8rem' }}>
314
+ Page {validPage} of {totalPages}
315
+ </div>
316
+ <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', justifyContent: 'center' }}>
317
+ <button
318
+ className="btn btn-ghost btn-sm"
319
+ onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
320
+ disabled={validPage <= 1}
321
+ style={{ display: 'flex', alignItems: 'center', gap: '0.25rem', opacity: validPage <= 1 ? 0.5 : 1 }}
322
+ >
323
+ <ChevronLeft size={20} />
324
+ </button>
325
+
326
+ <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
327
+ {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
328
+ let pageNum;
329
+ if (totalPages <= 5) {
330
+ pageNum = i + 1;
331
+ } else if (validPage <= 3) {
332
+ pageNum = i + 1;
333
+ } else if (validPage >= totalPages - 2) {
334
+ pageNum = totalPages - 4 + i;
335
+ } else {
336
+ pageNum = validPage - 2 + i;
337
+ }
338
+
339
+ // Planet Textures Mapping (Mercury -> Neptune)
340
+ const planets = [
341
+ { name: 'Mercury', bg: "url('/textures/mercury_map.jpg')", color: '#fff' },
342
+ { name: 'Venus', bg: "url('/textures/venus_map.jpg')", color: '#000' },
343
+ { name: 'Earth', bg: "linear-gradient(135deg, rgba(20,80,180,0.7), rgba(40,120,220,0.6)), url('/textures/earth_daymap.jpg')", color: '#fff' },
344
+ { name: 'Mars', bg: "url('/textures/mars_map.jpg')", color: '#fff' },
345
+ { name: 'Jupiter', bg: "url('/textures/jupiter_map.jpg')", color: '#fff' },
346
+ { name: 'Saturn', bg: "url('/textures/saturn_map.jpg')", color: '#fff' },
347
+ { name: 'Uranus', bg: "url('/textures/uranus_map.jpg')", color: '#000' },
348
+ { name: 'Neptune', bg: "url('/textures/neptune_map.jpg')", color: '#fff' }
349
+ ];
350
+
351
+ const planetIndex = (pageNum - 1) % 8;
352
+ const planet = planets[planetIndex];
353
+
354
+ return (
355
+ <button
356
+ key={i}
357
+ className={`btn`}
358
+ onClick={() => setCurrentPage(pageNum)}
359
+ style={{
360
+ width: '35px',
361
+ height: '35px',
362
+ padding: 0,
363
+ display: 'flex',
364
+ alignItems: 'center',
365
+ justifyContent: 'center',
366
+ borderRadius: '50%',
367
+ fontSize: '0.75rem',
368
+ fontWeight: 'bold',
369
+ backgroundImage: planet.bg,
370
+ backgroundSize: '200%',
371
+ backgroundPosition: '50% 30%',
372
+ backgroundColor: '#1a3a5c',
373
+ color: '#fff',
374
+ border: validPage === pageNum ? '1px solid rgba(255,255,255,0.5)' : '1px solid rgba(255,255,255,0.15)',
375
+ boxShadow: 'none',
376
+ transition: 'all 0.3s',
377
+ transform: validPage === pageNum ? 'scale(1.1)' : 'scale(1)'
378
+ }}
379
+ title={`${planet.name} (Page ${pageNum})`}
380
+ >
381
+ <span style={{
382
+ position: 'relative',
383
+ zIndex: 2,
384
+ textShadow: '0 1px 3px rgba(0,0,0,0.9), 0 0 6px rgba(0,0,0,0.8)'
385
+ }}>
386
+ {pageNum}
387
+ </span>
388
+ </button>
389
+ );
390
+ })}
391
+ </div>
392
+
393
+ <button
394
+ className="btn btn-ghost btn-sm"
395
+ onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
396
+ disabled={validPage >= totalPages}
397
+ style={{ display: 'flex', alignItems: 'center', gap: '0.25rem', opacity: validPage >= totalPages ? 0.5 : 1 }}
398
+ >
399
+ <ChevronRight size={20} />
400
+ </button>
401
+ </div>
402
+ </div>
403
+ )
404
+ }
405
+ </div >
406
+ );
407
+ }
408
+
409
+ export default JobList;
410
+
frontend/src/components/JobSearch.jsx ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+ import { Search, MapPin, Filter } from 'lucide-react';
3
+ import { motion, AnimatePresence } from 'framer-motion';
4
+
5
+ function JobSearch({ onSearch, loading }) {
6
+ const [query, setQuery] = useState('');
7
+ const [location, setLocation] = useState('');
8
+ const [country, setCountry] = useState('gb'); // Default to UK
9
+ const [filters, setFilters] = useState({
10
+ fullTime: false,
11
+ partTime: false,
12
+ permanent: false,
13
+ contract: false
14
+ });
15
+ const [showFilters, setShowFilters] = useState(false);
16
+
17
+ // Debounce search
18
+ useEffect(() => {
19
+ const timer = setTimeout(() => {
20
+ // Always pass the current location, even if query is empty
21
+ onSearch(query, location, country, filters);
22
+ }, 800);
23
+
24
+ return () => clearTimeout(timer);
25
+ }, [query, location, country, filters, onSearch]);
26
+
27
+ const handleFilterChange = (e) => {
28
+ const { name, checked } = e.target;
29
+ setFilters(prev => ({ ...prev, [name]: checked }));
30
+ };
31
+
32
+ return (
33
+ <div className="search-container" style={{ maxWidth: '900px', margin: '0 auto' }}>
34
+ <div className="search-card-container">
35
+ {/* Query Input */}
36
+ <div className="input-group" style={{ flex: 1.5, position: 'relative' }}>
37
+ <Search className="input-icon" size={20} />
38
+ <input
39
+ type="text"
40
+ placeholder="What are you looking for?"
41
+ value={query}
42
+ onChange={(e) => setQuery(e.target.value)}
43
+ className="form-input"
44
+ style={{ border: 'none', background: 'transparent', boxShadow: 'none', paddingLeft: '3rem', fontSize: '1.1rem' }}
45
+ />
46
+ </div>
47
+
48
+ <div className="search-divider"></div>
49
+
50
+ {/* Location Input */}
51
+ <div className="input-group" style={{ flex: 1, position: 'relative' }}>
52
+ <MapPin className="input-icon" size={20} />
53
+ <input
54
+ type="text"
55
+ placeholder="Location"
56
+ value={location}
57
+ onChange={(e) => setLocation(e.target.value)}
58
+ className="form-input"
59
+ style={{ border: 'none', background: 'transparent', boxShadow: 'none', paddingLeft: '3rem', fontSize: '1.1rem' }}
60
+ />
61
+ </div>
62
+ </div>
63
+
64
+ {/* Active Filter Chips */}
65
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginTop: '1rem', justifyContent: 'center' }}>
66
+ {Object.entries(filters).filter(([_, value]) => value).map(([key, _]) => {
67
+ const label = {
68
+ fullTime: 'Full Time',
69
+ partTime: 'Part Time',
70
+ permanent: 'Permanent',
71
+ contract: 'Contract'
72
+ }[key];
73
+
74
+ return (
75
+ <motion.button
76
+ key={key}
77
+ initial={{ scale: 0.8, opacity: 0 }}
78
+ animate={{ scale: 1, opacity: 1 }}
79
+ exit={{ scale: 0.8, opacity: 0 }}
80
+ onClick={() => setFilters(prev => ({ ...prev, [key]: false }))}
81
+ style={{
82
+ display: 'flex',
83
+ alignItems: 'center',
84
+ gap: '0.5rem',
85
+ padding: '0.4rem 0.8rem',
86
+ background: 'rgba(45, 212, 191, 0.2)',
87
+ border: '1px solid var(--color-primary)',
88
+ borderRadius: '16px',
89
+ color: 'var(--color-primary)',
90
+ fontSize: '0.85rem',
91
+ cursor: 'pointer',
92
+ transition: 'all 0.2s'
93
+ }}
94
+ whileHover={{ scale: 1.05 }}
95
+ whileTap={{ scale: 0.95 }}
96
+ >
97
+ {label}
98
+ <div style={{ padding: '2px', borderRadius: '50%', background: 'rgba(0,0,0,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
99
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
100
+ <line x1="18" y1="6" x2="6" y2="18"></line>
101
+ <line x1="6" y1="6" x2="18" y2="18"></line>
102
+ </svg>
103
+ </div>
104
+ </motion.button>
105
+ );
106
+ })}
107
+ </div>
108
+
109
+ {/* Advanced Filters Toggle */}
110
+ <div style={{ marginTop: '1.5rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
111
+ <button
112
+ className="btn btn-text"
113
+ onClick={() => setShowFilters(!showFilters)}
114
+ style={{ padding: '0.5rem 1rem', display: 'flex', items: 'center', gap: '0.5rem', borderRadius: '20px', background: showFilters ? 'rgba(45, 212, 191, 0.1)' : 'transparent' }}
115
+ >
116
+ <Filter size={16} />
117
+ {showFilters ? 'Hide Filters' : 'Advanced Filters'}
118
+ </button>
119
+
120
+ <AnimatePresence>
121
+ {showFilters && (
122
+ <motion.div
123
+ initial={{ opacity: 0, height: 0, marginTop: 0 }}
124
+ animate={{ opacity: 1, height: 'auto', marginTop: 16 }}
125
+ exit={{ opacity: 0, height: 0, marginTop: 0 }}
126
+ className="filters-grid"
127
+ style={{ overflow: 'hidden', display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: '1rem' }}
128
+ >
129
+ {[
130
+ { name: 'fullTime', label: 'Full Time' },
131
+ { name: 'partTime', label: 'Part Time' },
132
+ { name: 'permanent', label: 'Permanent' },
133
+ { name: 'contract', label: 'Contract' }
134
+ ].map(filter => (
135
+ <label
136
+ key={filter.name}
137
+ className="checkbox-pill"
138
+ style={{
139
+ display: 'flex',
140
+ alignItems: 'center',
141
+ gap: '0.5rem',
142
+ padding: '0.5rem 1rem',
143
+ background: filters[filter.name] ? 'rgba(45, 212, 191, 0.15)' : 'rgba(255,255,255,0.05)',
144
+ border: `1px solid ${filters[filter.name] ? 'var(--color-primary)' : 'var(--color-border)'}`,
145
+ borderRadius: '20px',
146
+ cursor: 'pointer',
147
+ fontSize: '0.9rem',
148
+ transition: 'all 0.2s ease',
149
+ color: filters[filter.name] ? 'var(--color-primary)' : 'var(--color-text-secondary)'
150
+ }}
151
+ >
152
+ <input
153
+ type="checkbox"
154
+ name={filter.name}
155
+ checked={filters[filter.name]}
156
+ onChange={handleFilterChange}
157
+ style={{ display: 'none' }}
158
+ />
159
+ {filter.label}
160
+ </label>
161
+ ))}
162
+ </motion.div>
163
+ )}
164
+ </AnimatePresence>
165
+ </div>
166
+ </div>
167
+ );
168
+ }
169
+
170
+ export default JobSearch;
frontend/src/index.css ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ===== CSS Variables (NeuroArc Premium Palette) ===== */
2
+ :root {
3
+ /* Core Palette */
4
+ /* Core Palette */
5
+ --color-bg-primary: rgba(5, 11, 20, 0.2);
6
+ /* Transparent deep void */
7
+ --color-bg-secondary: rgba(10, 22, 37, 0.25);
8
+ /* Transparent card surface */
9
+ --color-bg-tertiary: rgba(17, 34, 64, 0.3);
10
+ /* Transparent input/hover */
11
+ --color-border: rgba(0, 229, 255, 0.2);
12
+ /* Cyan border */
13
+
14
+ /* Text */
15
+ --color-text-primary: #e0f7fa;
16
+ /* Ice blue white */
17
+ --color-text-secondary: #81d4fa;
18
+ /* Sky blue */
19
+ --color-text-muted: #4fc3f7;
20
+ /* Muted cyan */
21
+
22
+ /* Brand Colors */
23
+ --color-primary: #00e5ff;
24
+ /* Cyan Neon */
25
+ --color-primary-light: #84ffff;
26
+ --color-primary-dark: #00b8d4;
27
+ --color-primary-glow: rgba(0, 229, 255, 0.4);
28
+
29
+ --color-accent-primary: #ffd180;
30
+ /* Solar Gold */
31
+ --color-accent-secondary: #b388ff;
32
+ /* Deep Violet */
33
+
34
+ --color-cta: #ff9100;
35
+ /* Solar Orange */
36
+
37
+ /* Functional Colors */
38
+ --color-success: #00e676;
39
+ --color-warning: #ffab40;
40
+ --color-error: #ff5252;
41
+
42
+ /* Elevation & Effects */
43
+ --glass-bg: rgba(5, 20, 40, 0.1);
44
+ /* Maximum transparency */
45
+ --glass-border: rgba(0, 229, 255, 0.15);
46
+ /* Visible simple border */
47
+ --glass-blur: blur(0px);
48
+ /* No blur for crystal clear view */
49
+ --shadow-sm: 0 4px 6px -1px rgba(0, 229, 255, 0.05);
50
+ --shadow-md: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
51
+ --shadow-lg: 0 20px 25px -5px rgba(0, 0, 0, 0.6);
52
+ --shadow-glow: 0 0 25px rgba(0, 229, 255, 0.2);
53
+
54
+ /* Radius */
55
+ --radius-sm: 8px;
56
+ --radius-md: 16px;
57
+ --radius-lg: 24px;
58
+ --radius-xl: 32px;
59
+ }
60
+
61
+ /* ===== Reset & Base ===== */
62
+ *,
63
+ *::before,
64
+ *::after {
65
+ box-sizing: border-box;
66
+ margin: 0;
67
+ padding: 0;
68
+ }
69
+
70
+ html {
71
+ font-size: 16px;
72
+ scroll-behavior: smooth;
73
+ }
74
+
75
+ body {
76
+ font-family: 'Outfit', 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
77
+ background-color: var(--color-bg-primary);
78
+ color: var(--color-text-primary);
79
+ line-height: 1.6;
80
+ min-height: 100vh;
81
+ overflow-x: hidden;
82
+ -webkit-font-smoothing: antialiased;
83
+ }
84
+
85
+ /* 3D Background Container */
86
+ .background-3d {
87
+ position: fixed;
88
+ top: 0;
89
+ left: 0;
90
+ width: 100vw;
91
+ height: 100vh;
92
+ z-index: -1;
93
+ pointer-events: none;
94
+ background: radial-gradient(circle at 50% 0%, #112240 0%, #050b14 70%);
95
+ }
96
+
97
+ /* ===== Layout ===== */
98
+ .app {
99
+ display: flex;
100
+ flex-direction: column;
101
+ min-height: 100vh;
102
+ min-height: 100dvh;
103
+ /* Mobile viewport fix */
104
+ position: relative;
105
+ z-index: 1;
106
+ }
107
+
108
+ /* Glass Header */
109
+ .header {
110
+ background: var(--glass-bg);
111
+ backdrop-filter: var(--glass-blur);
112
+ border-bottom: 1px solid var(--glass-border);
113
+ padding: 1.25rem 2rem;
114
+ position: sticky;
115
+ top: 0;
116
+ z-index: 100;
117
+ }
118
+
119
+ .header-content {
120
+ max-width: 1400px;
121
+ margin: 0 auto;
122
+ display: flex;
123
+ justify-content: space-between;
124
+ align-items: center;
125
+ }
126
+
127
+ .logo {
128
+ display: flex;
129
+ align-items: center;
130
+ gap: 1rem;
131
+ font-size: 1.5rem;
132
+ font-weight: 800;
133
+ color: var(--color-text-primary);
134
+ letter-spacing: -0.03em;
135
+ cursor: pointer;
136
+ }
137
+
138
+ .logo-icon {
139
+ width: 42px;
140
+ height: 42px;
141
+ background: linear-gradient(135deg, var(--color-primary), var(--color-primary-dark));
142
+ border-radius: var(--radius-sm);
143
+ display: flex;
144
+ align-items: center;
145
+ justify-content: center;
146
+ color: #050b14;
147
+ box-shadow: 0 0 15px var(--color-primary-glow);
148
+ }
149
+
150
+ .main {
151
+ flex: 1;
152
+ max-width: 1400px;
153
+ margin: 0 auto;
154
+ padding: 3rem 2rem;
155
+ width: 100%;
156
+ }
157
+
158
+ .footer {
159
+ background: var(--color-bg-secondary);
160
+ border-top: 1px solid var(--color-border);
161
+ padding: 4rem 2rem;
162
+ text-align: center;
163
+ color: var(--color-text-muted);
164
+ }
165
+
166
+ /* ===== Immersive Steps (Dynamic) ===== */
167
+ /* Styles handled inline in App.jsx or scoped classes */
168
+
169
+ /* ===== Glass Cards & Containers ===== */
170
+ .card {
171
+ background: var(--glass-bg);
172
+ backdrop-filter: var(--glass-blur);
173
+ border: 1px solid var(--glass-border);
174
+ border-radius: var(--radius-lg);
175
+ padding: 2rem;
176
+ transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
177
+ position: relative;
178
+ overflow: hidden;
179
+ }
180
+
181
+
182
+
183
+ /* Ambient Glow for cards */
184
+ .card::after {
185
+ content: '';
186
+ position: absolute;
187
+ top: 0;
188
+ left: 0;
189
+ width: 100%;
190
+ height: 100%;
191
+ background: radial-gradient(circle at top right, rgba(45, 212, 191, 0.1), transparent 40%);
192
+ opacity: 0;
193
+ transition: opacity 0.4s ease;
194
+ pointer-events: none;
195
+ }
196
+
197
+ .card:hover::after {
198
+ opacity: 0;
199
+ }
200
+
201
+ /* Utility to disable hover effects */
202
+ .card.no-hover:hover {
203
+ transform: none;
204
+ border-color: var(--glass-border);
205
+ box-shadow: none;
206
+ }
207
+
208
+ .card.no-hover::after {
209
+ display: none;
210
+ }
211
+
212
+ /* ===== Buttons ===== */
213
+ .btn {
214
+ display: inline-flex;
215
+ align-items: center;
216
+ justify-content: center;
217
+ gap: 0.75rem;
218
+ padding: 0.875rem 2rem;
219
+ border-radius: var(--radius-md);
220
+ font-weight: 700;
221
+ font-size: 1rem;
222
+ cursor: pointer;
223
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
224
+ border: none;
225
+ text-decoration: none;
226
+ position: relative;
227
+ overflow: hidden;
228
+ z-index: 10;
229
+ }
230
+
231
+ .btn-primary {
232
+ background: linear-gradient(135deg, var(--color-primary), var(--color-primary-dark));
233
+ color: #050b14;
234
+ }
235
+
236
+ .btn-primary:hover {
237
+ transform: translateY(-2px);
238
+ box-shadow: 0 8px 25px rgba(45, 212, 191, 0.5);
239
+ filter: brightness(1.1);
240
+ }
241
+
242
+ .btn-primary.no-hover-shadow:hover {
243
+ box-shadow: none !important;
244
+ transform: none !important;
245
+ }
246
+
247
+ .btn-secondary {
248
+ background: rgba(255, 255, 255, 0.05);
249
+ /* Slight white tint */
250
+ color: var(--color-text-primary);
251
+ border: 1px solid var(--color-border);
252
+ }
253
+
254
+ .btn-secondary:hover {
255
+ background: rgba(45, 212, 191, 0.1);
256
+ border-color: var(--color-primary);
257
+ color: var(--color-primary);
258
+ box-shadow: 0 0 15px rgba(45, 212, 191, 0.1);
259
+ }
260
+
261
+ .btn-outline {
262
+ background: transparent;
263
+ color: var(--color-primary);
264
+ border: 1px solid var(--color-primary);
265
+ }
266
+
267
+ .btn-outline:hover {
268
+ background: rgba(45, 212, 191, 0.1);
269
+ }
270
+
271
+ .btn-ghost {
272
+ background: transparent;
273
+ color: var(--color-text-secondary);
274
+ }
275
+
276
+ .btn-ghost:hover {
277
+ color: var(--color-primary);
278
+ background: rgba(255, 255, 255, 0.05);
279
+ }
280
+
281
+ /* ===== Alerts ===== */
282
+ .alert {
283
+ padding: 1.25rem 1.5rem;
284
+ border-radius: var(--radius-md);
285
+ backdrop-filter: blur(10px);
286
+ border: 1px solid;
287
+ }
288
+
289
+ .alert-error {
290
+ background: rgba(239, 68, 68, 0.15);
291
+ border-color: rgba(239, 68, 68, 0.4);
292
+ color: #fca5a5;
293
+ }
294
+
295
+ .alert-warning {
296
+ background: rgba(245, 158, 11, 0.15);
297
+ border-color: rgba(245, 158, 11, 0.4);
298
+ color: #fcd34d;
299
+ }
300
+
301
+ .alert-success {
302
+ background: rgba(45, 212, 191, 0.15);
303
+ border-color: rgba(45, 212, 191, 0.4);
304
+ color: var(--color-primary);
305
+ }
306
+
307
+ /* ===== Inputs ===== */
308
+ .form-input,
309
+ .form-select {
310
+ width: 100%;
311
+ padding: 1rem 1.25rem;
312
+ padding-left: 3rem;
313
+ background: rgba(0, 0, 0, 0.3);
314
+ border: 1px solid var(--color-border);
315
+ border-radius: var(--radius-md);
316
+ color: var(--color-text-primary);
317
+ font-size: 1rem;
318
+ transition: all 0.3s ease;
319
+ }
320
+
321
+ .form-input:focus,
322
+ .form-select:focus {
323
+ outline: none;
324
+ border-color: var(--color-primary);
325
+ background: rgba(0, 0, 0, 0.5);
326
+ box-shadow: 0 0 0 3px rgba(45, 212, 191, 0.15);
327
+ }
328
+
329
+ .input-icon {
330
+ position: absolute;
331
+ left: 1.25rem;
332
+ top: 50%;
333
+ transform: translateY(-50%);
334
+ color: var(--color-text-secondary);
335
+ transition: color 0.3s ease;
336
+ }
337
+
338
+ .input-group:focus-within .input-icon {
339
+ color: var(--color-primary);
340
+ }
341
+
342
+ /* ===== Hero Typography ===== */
343
+ .hero-title {
344
+ font-size: 3.5rem;
345
+ font-weight: 800;
346
+ line-height: 1.3;
347
+ background: linear-gradient(to right, #fff, var(--color-primary-light));
348
+ -webkit-background-clip: text;
349
+ background-clip: text;
350
+ -webkit-text-fill-color: transparent;
351
+ margin-bottom: 1.25rem;
352
+ letter-spacing: -0.04em;
353
+ padding-bottom: 0.2rem;
354
+ }
355
+
356
+ .hero-subtitle {
357
+ font-size: 1.25rem;
358
+ color: var(--color-text-secondary);
359
+ max-width: 600px;
360
+ margin: 0 auto;
361
+ }
362
+
363
+ /* ===== Job specific improvements ===== */
364
+ .job-card {
365
+ /* Inherit standard border */
366
+ }
367
+
368
+ .job-card.active {
369
+ border-left-color: var(--color-primary);
370
+ background: linear-gradient(90deg, rgba(45, 212, 191, 0.05) 0%, rgba(10, 22, 37, 0.2) 100%);
371
+ }
372
+
373
+ .job-title {
374
+ font-size: 1.25rem;
375
+ font-weight: 700;
376
+ color: var(--color-text-primary);
377
+ margin-bottom: 0.25rem;
378
+ }
379
+
380
+ .meta-item {
381
+ display: inline-flex;
382
+ align-items: center;
383
+ gap: 0.35rem;
384
+ padding: 0.25rem 0.6rem;
385
+ background: rgba(255, 255, 255, 0.03);
386
+ border-radius: 6px;
387
+ font-size: 0.85rem;
388
+ color: var(--color-text-secondary);
389
+ }
390
+
391
+ /* ===== Animation Utilities ===== */
392
+ @keyframes fadeIn {
393
+ from {
394
+ opacity: 0;
395
+ transform: translateY(20px);
396
+ }
397
+
398
+ to {
399
+ opacity: 1;
400
+ transform: translateY(0);
401
+ }
402
+ }
403
+
404
+ .fade-in {
405
+ animation: fadeIn 0.6s cubic-bezier(0.2, 0.8, 0.2, 1);
406
+ }
407
+
408
+ /* Scrollbar */
409
+ ::-webkit-scrollbar {
410
+ width: 8px;
411
+ }
412
+
413
+ ::-webkit-scrollbar-track {
414
+ background: var(--color-bg-primary);
415
+ }
416
+
417
+ ::-webkit-scrollbar-thumb {
418
+ background: var(--color-border);
419
+ border-radius: 4px;
420
+ }
421
+
422
+ ::-webkit-scrollbar-thumb:hover {
423
+ background: var(--color-primary-dark);
424
+ }
425
+
426
+ @media (max-width: 768px) {
427
+ .hide-mobile {
428
+ display: none !important;
429
+ }
430
+
431
+ .show-mobile {
432
+ display: block !important;
433
+ }
434
+
435
+ .header-reset-btn {
436
+ padding: 0.6rem !important;
437
+ font-size: 0 !important;
438
+ /* Hide any lingering text space */
439
+ }
440
+
441
+ .header-reset-btn svg {
442
+ margin: 0 !important;
443
+ }
444
+
445
+ .hero-title {
446
+ font-size: 2.5rem;
447
+ }
448
+
449
+ .steps {
450
+ gap: 1rem;
451
+ }
452
+
453
+ .steps::before {
454
+ width: 90%;
455
+ }
456
+ }
457
+
458
+ .show-mobile {
459
+ display: none;
460
+ }
461
+
462
+ /* ===== Loading Spinner ===== */
463
+ @keyframes spin {
464
+ from {
465
+ transform: rotate(0deg);
466
+ }
467
+
468
+ to {
469
+ transform: rotate(360deg);
470
+ }
471
+ }
472
+
473
+ /* ===== Tooltip ===== */
474
+ .tooltip-container {
475
+ position: relative;
476
+ display: inline-block;
477
+ }
478
+
479
+ .tooltip-text {
480
+ visibility: hidden;
481
+ width: 120px;
482
+ background-color: var(--color-bg-primary);
483
+ color: var(--color-text-primary);
484
+ text-align: center;
485
+ border-radius: 6px;
486
+ padding: 8px 0;
487
+ position: absolute;
488
+ z-index: 1;
489
+ top: 130%;
490
+ /* Position below */
491
+ left: 50%;
492
+ margin-left: -60px;
493
+ opacity: 0;
494
+ transition: opacity 0.3s;
495
+ box-shadow: var(--shadow-md);
496
+ border: 1px solid var(--color-border);
497
+ font-size: 0.8rem;
498
+ font-weight: 500;
499
+ }
500
+
501
+ .tooltip-container:hover .tooltip-text {
502
+ visibility: visible;
503
+ opacity: 1;
504
+ }
505
+
506
+ .tooltip-text::after {
507
+ content: "";
508
+ position: absolute;
509
+ bottom: 100%;
510
+ /* Arrow at top */
511
+ left: 50%;
512
+ margin-left: -5px;
513
+ border-width: 5px;
514
+ border-style: solid;
515
+ border-color: transparent transparent var(--color-border) transparent;
516
+ /* Point up */
517
+ }
518
+
519
+ .spinner {
520
+ animation: spin 1s linear infinite;
521
+ color: var(--color-primary);
522
+ }
523
+
524
+ /* Footer responsive - stack elements on smaller screens */
525
+ /* Legacy footer-bmc styles removed */
526
+
527
+ /* ===== Responsive Search Bar ===== */
528
+ .search-card-container {
529
+ padding: 0.75rem;
530
+ border-radius: 100px;
531
+ display: flex;
532
+ align-items: center;
533
+ gap: 0.5rem;
534
+ background: var(--glass-bg);
535
+ border: 1px solid var(--color-border);
536
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
537
+ transition: all 0.3s ease;
538
+ }
539
+
540
+ .search-divider {
541
+ width: 1px;
542
+ height: 32px;
543
+ background: var(--color-border);
544
+ flex-shrink: 0;
545
+ }
546
+
547
+ @media (max-width: 768px) {
548
+ .search-card-container {
549
+ flex-direction: column;
550
+ border-radius: 24px;
551
+ padding: 1rem;
552
+ gap: 1rem;
553
+ background: var(--glass-bg);
554
+ /* Ensure readability */
555
+ }
556
+
557
+ .search-divider {
558
+ display: none;
559
+ }
560
+
561
+ .search-card-container .input-group {
562
+ width: 100% !important;
563
+ flex: none !important;
564
+ }
565
+ }
566
+
567
+ /* Responsive Footer Styles */
568
+ /* Responsive Footer Styles - Unified Center Layout */
569
+ .footer-responsive {
570
+ margin-top: auto;
571
+ padding: 2rem 1rem;
572
+ border-top: 1px solid var(--color-border);
573
+ background: var(--color-bg-primary);
574
+ display: flex;
575
+ flex-direction: column;
576
+ justify-content: center;
577
+ align-items: center;
578
+ position: relative;
579
+ font-size: 0.85rem;
580
+ gap: 0.5rem;
581
+ }
582
+
583
+ /* Link Section (About Us) - Order 1 */
584
+ .footer-left {
585
+ order: 1;
586
+ display: flex;
587
+ align-items: center;
588
+ justify-content: center;
589
+ width: 100%;
590
+ }
591
+
592
+ /* BMC Section - Order 3 */
593
+ .footer-right {
594
+ order: 3;
595
+ display: flex;
596
+ align-items: center;
597
+ justify-content: center;
598
+ width: 100%;
599
+ }
600
+
601
+ /* Center Section (Copyright) - Order 2 */
602
+ .footer-center {
603
+ order: 2;
604
+ text-align: center;
605
+ display: flex;
606
+ flex-direction: column;
607
+ gap: 0.25rem;
608
+ position: static;
609
+ transform: none;
610
+ width: 100%;
611
+ max-width: 800px;
612
+ padding: 0 1rem;
613
+ word-wrap: break-word;
614
+ }
615
+
616
+ /* About Us Card - Responsive Padding */
617
+ .about-us-card {
618
+ padding: 3rem;
619
+ }
620
+
621
+ @media (max-width: 768px) {
622
+ .about-us-card {
623
+ padding: 1.5rem;
624
+ }
625
+ }
frontend/src/main.jsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react'
2
+ import ReactDOM from 'react-dom/client'
3
+ import App from './App.jsx'
4
+ import './index.css'
5
+
6
+ ReactDOM.createRoot(document.getElementById('root')).render(
7
+ <React.StrictMode>
8
+ <App />
9
+ </React.StrictMode>,
10
+ )
frontend/vite.config.js ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+
4
+ export default defineConfig({
5
+ plugins: [react()],
6
+ server: {
7
+ port: 5173,
8
+ proxy: {
9
+ '/api': {
10
+ target: 'http://localhost:8000',
11
+ changeOrigin: true
12
+ }
13
+ }
14
+ }
15
+ })
run.sh ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # NeuroArc - Start Script
4
+ # Starts both backend and frontend servers
5
+ # Auto-kills existing processes on ports 8000 and 5173
6
+
7
+ # Colors for output
8
+ RED='\033[0;31m'
9
+ GREEN='\033[0;32m'
10
+ BLUE='\033[0;34m'
11
+ YELLOW='\033[1;33m'
12
+ NC='\033[0m' # No Color
13
+
14
+ # Ports used by the application
15
+ BACKEND_PORT=8000
16
+ FRONTEND_PORT=5173
17
+
18
+ echo ""
19
+ echo -e "${BLUE}╔═══════════════════════════════════════════╗${NC}"
20
+ echo -e "${BLUE}β•‘ πŸš€ NeuroArc Launcher β•‘${NC}"
21
+ echo -e "${BLUE}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}"
22
+ echo ""
23
+
24
+ # Get the directory where the script is located
25
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
26
+
27
+ # Function to kill process on a specific port
28
+ kill_port() {
29
+ local port=$1
30
+ local pid=$(lsof -ti:$port 2>/dev/null)
31
+
32
+ if [ -n "$pid" ]; then
33
+ echo -e "${YELLOW}⚠️ Port $port is in use by PID $pid. Killing...${NC}"
34
+ kill -9 $pid 2>/dev/null
35
+ sleep 1
36
+ echo -e "${GREEN}βœ“ Port $port is now free${NC}"
37
+ else
38
+ echo -e "${GREEN}βœ“ Port $port is available${NC}"
39
+ fi
40
+ }
41
+
42
+ # Function to cleanup on exit
43
+ cleanup() {
44
+ echo ""
45
+ echo -e "${YELLOW}πŸ›‘ Shutting down NeuroArc...${NC}"
46
+
47
+ # Kill backend and frontend processes
48
+ if [ -n "$BACKEND_PID" ]; then
49
+ kill $BACKEND_PID 2>/dev/null
50
+ echo -e "${GREEN}βœ“ Backend stopped${NC}"
51
+ fi
52
+
53
+ if [ -n "$FRONTEND_PID" ]; then
54
+ kill $FRONTEND_PID 2>/dev/null
55
+ echo -e "${GREEN}βœ“ Frontend stopped${NC}"
56
+ fi
57
+
58
+ # Also kill any remaining processes on our ports
59
+ kill_port $BACKEND_PORT
60
+ kill_port $FRONTEND_PORT
61
+
62
+ echo -e "${GREEN}πŸ‘‹ Goodbye!${NC}"
63
+ exit 0
64
+ }
65
+
66
+ # Set up trap to cleanup on Ctrl+C or script exit
67
+ trap cleanup SIGINT SIGTERM EXIT
68
+
69
+ # Kill any existing processes on our ports
70
+ echo -e "${BLUE}πŸ“‹ Checking ports...${NC}"
71
+ kill_port $BACKEND_PORT
72
+ kill_port $FRONTEND_PORT
73
+ echo ""
74
+
75
+ # Backend setup
76
+ echo -e "${BLUE}πŸ“¦ Setting up Backend...${NC}"
77
+ cd "$SCRIPT_DIR/backend"
78
+
79
+ # Create virtual environment if it doesn't exist
80
+ if [ ! -d "venv" ]; then
81
+ echo " Creating Python virtual environment..."
82
+ python3 -m venv venv
83
+ fi
84
+
85
+ # Activate virtual environment
86
+ source venv/bin/activate
87
+
88
+ # Install/update dependencies
89
+ echo " Installing Python dependencies..."
90
+ pip install -r requirements.txt --quiet
91
+
92
+ # Copy .env.example to .env if .env doesn't exist
93
+ if [ ! -f ".env" ]; then
94
+ if [ -f ".env.example" ]; then
95
+ cp .env.example .env
96
+ echo -e "${YELLOW}⚠️ Created .env from .env.example${NC}"
97
+ echo -e "${YELLOW} Please add your API keys to backend/.env${NC}"
98
+ fi
99
+ fi
100
+
101
+ # Check if GITHUB_TOKEN is set
102
+ if grep -q "your_github_token_here" .env 2>/dev/null; then
103
+ echo -e "${YELLOW}⚠️ GITHUB_TOKEN not configured - AI features will be limited${NC}"
104
+ fi
105
+
106
+ # Start backend with auto-reload
107
+ echo -e "${GREEN}βœ… Starting FastAPI Backend (http://localhost:$BACKEND_PORT)${NC}"
108
+ uvicorn main:app --reload --host 0.0.0.0 --port $BACKEND_PORT &
109
+ BACKEND_PID=$!
110
+
111
+ # Wait a moment for backend to start
112
+
113
+
114
+ # Frontend setup
115
+ echo ""
116
+ echo -e "${BLUE}πŸ“¦ Setting up Frontend...${NC}"
117
+ cd "$SCRIPT_DIR/frontend"
118
+
119
+ # Install npm dependencies if node_modules doesn't exist or package.json changed
120
+ if [ ! -d "node_modules" ] || [ "package.json" -nt "node_modules" ]; then
121
+ echo " Installing Node.js dependencies..."
122
+ npm install --silent
123
+ fi
124
+
125
+ # Start frontend with hot reload
126
+ echo -e "${GREEN}βœ… Starting React Frontend (http://localhost:$FRONTEND_PORT)${NC}"
127
+ npm run dev -- --host &
128
+ FRONTEND_PID=$!
129
+
130
+ # Wait for frontend to start
131
+
132
+
133
+ # Print success message
134
+ echo ""
135
+ echo -e "${GREEN}╔═══════════════════════════════════════════╗${NC}"
136
+ echo -e "${GREEN}β•‘ πŸŽ‰ NeuroArc is running! β•‘${NC}"
137
+ echo -e "${GREEN}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}"
138
+ echo ""
139
+ echo -e " ${BLUE}Frontend:${NC} http://localhost:$FRONTEND_PORT"
140
+ echo -e " ${BLUE}Backend:${NC} http://localhost:$BACKEND_PORT"
141
+ echo -e " ${BLUE}API Docs:${NC} http://localhost:$BACKEND_PORT/docs"
142
+ echo ""
143
+ echo -e "${YELLOW}πŸ“ Both servers have hot-reload enabled.${NC}"
144
+ echo -e "${YELLOW} Edit files and changes will apply automatically!${NC}"
145
+ echo ""
146
+ echo -e "Press ${RED}Ctrl+C${NC} to stop all servers"
147
+ echo ""
148
+
149
+ # Keep script running and wait for processes
150
+ wait $BACKEND_PID $FRONTEND_PID