Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
284 lines (226 loc) · 10.5 KB
/
Copy pathserver.py
File metadata and controls
284 lines (226 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import config
from memory import memory
import os
import shutil
import json
from datetime import datetime
from typing import Optional, Dict, List, Any
from fastapi import FastAPI, HTTPException, Body, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import decision
app = FastAPI(title="Nature Scout API")
@app.get("/")
async def root():
return {"status": "online", "message": "Nature Scout AI API is running."}
# Enable CORS for the frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, restrict this to your frontend URL
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Ensure resume directory exists
os.makedirs(config.RESUME_DIR, exist_ok=True)
# Mount static files for resume access
app.mount("/documents", StaticFiles(directory=config.RESUME_DIR), name="documents")
def sync_monitored_companies_file():
"""Generates checked-in visibility file for monitored targets."""
try:
portals = memory.get_portals(config.DB_PATH)
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "monitored_companies.md")
with open(file_path, "w", encoding="utf-8") as f:
f.write("# Monitored Companies (Intelligence Sources)\n\n")
f.write("This file is automatically generated by the AI Job Scout system for project visibility.\n\n")
if not portals:
f.write("*[System Notice]: No external targets are currently being monitored.*\n")
else:
for p in portals:
f.write(f"- **{p['name']}**: {p['url']}\n")
except Exception as e:
print(f"Failed to sync monitored companies file: {e}")
import threading
import main as agent_main
# Initial sync on startup
@app.on_event("startup")
async def startup_event():
sync_monitored_companies_file()
# Start the Scraper Agent in a background thread
print("Starting background Scraper Agent...")
threading.Thread(target=agent_main.main, daemon=True).start()
# --- Jobs Endpoints ---
@app.get("/jobs")
async def get_jobs(status: Optional[str] = None, remote_policy: Optional[str] = None):
"""Retrieves jobs, optionally filtered by status and remote policy."""
jobs = memory.get_jobs(config.DB_PATH, status=status)
if remote_policy:
jobs = [j for j in jobs if j.get('remote_policy') == remote_policy]
return jobs
@app.patch("/jobs/{job_id}/status")
async def update_job_status(job_id: str, status: str = Body(..., embed=True)):
"""Updates the status of a job (e.g., marking as 'applied')."""
if status not in ['inbox', 'applied', 'dismissed', 'saved']:
raise HTTPException(status_code=400, detail="Invalid status")
memory.update_job_status(job_id, status, config.DB_PATH)
return {"status": "success", "job_id": job_id, "new_status": status}
@app.get("/settings/portals")
async def get_portals():
"""Retrieves the list of monitored company portals."""
return memory.get_portals(config.DB_PATH)
@app.post("/settings/portals")
async def add_portal(portal: dict = Body(...)):
"""Adds a new company portal to the monitoring list."""
name = portal.get('company')
url = portal.get('url')
if not name or not url:
raise HTTPException(status_code=400, detail="Company name and URL are required")
portal_id = memory.add_portal(name, url, config.DB_PATH)
if portal_id is None:
raise HTTPException(status_code=400, detail="Portal URL already exists or error occurred")
return {"status": "success", "portal_id": portal_id}
@app.delete("/settings/portals/{portal_id}")
async def remove_portal(portal_id: int):
"""Removes a portal from the monitoring list."""
memory.remove_portal(portal_id, config.DB_PATH)
return {"status": "success"}
@app.post("/jobs/{job_id}/resume")
async def upload_resume(job_id: str, file: UploadFile = File(...)):
"""Uploads and links a resume to a specific job record."""
if not file.filename.lower().endswith(('.pdf', '.docx')):
raise HTTPException(status_code=400, detail="Only PDF and DOCX files are allowed")
file_content = await file.read()
# Try Firebase upload first
resume_url = memory.upload_resume_file(f"{job_id}_{file.filename}", file_content)
if not resume_url:
# Fallback to local (only works if running locally)
file_path = os.path.join(config.RESUME_DIR, f"{job_id}_{file.filename}")
with open(file_path, "wb") as buffer:
buffer.write(file_content)
resume_url = f"/documents/{job_id}_{file.filename}"
memory.update_job_resume(job_id, resume_url, config.DB_PATH)
return {"status": "success", "resume_url": resume_url}
# --- Settings Endpoints ---
@app.get("/settings/keywords")
async def get_keywords():
"""Retrieves the current list of monitored keywords."""
keywords = memory.get_setting("keywords", config.DB_PATH, default=config.KEYWORDS)
return {"keywords": keywords}
@app.post("/settings/keywords")
async def add_keyword(keyword: str = Body(..., embed=True)):
"""Adds a new keyword to the monitoring list."""
keywords = memory.get_setting("keywords", config.DB_PATH, default=config.KEYWORDS)
if keyword not in keywords:
keywords.append(keyword)
memory.set_setting("keywords", keywords, config.DB_PATH)
return {"status": "success", "keywords": keywords}
@app.delete("/settings/keywords/{keyword}")
async def remove_keyword(keyword: str):
"""Removes a keyword from the monitoring list."""
keywords = memory.get_setting("keywords", config.DB_PATH, default=config.KEYWORDS)
if keyword in keywords:
keywords.remove(keyword)
memory.set_setting("keywords", keywords, config.DB_PATH)
return {"status": "success", "keywords": keywords}
@app.post("/settings/sync")
async def trigger_sync():
"""Signals the agent to perform an immediate search cycle."""
memory.set_setting("sync_requested", True, config.DB_PATH)
return {"status": "success", "message": "Sync requested"}
@app.get("/settings/status")
async def get_status():
"""Retrieves the agent's last and next scan times."""
last_scan = memory.get_setting("last_scan_time", config.DB_PATH, default="Never")
status = memory.get_setting("agent_status", config.DB_PATH, default="Idle")
return {"last_scan": last_scan, "status": status}
@app.get("/logs")
async def get_logs():
"""Returns the last 50 lines of the agent execution log."""
log_path = 'logs/agent.log'
if not os.path.exists(log_path):
return {"logs": ["No logs found yet."]}
try:
with open(log_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
return {"logs": lines[-50:]}
except Exception as e:
return {"logs": [f"Error reading logs: {e}"]}
# --- Resume Management ---
@app.get("/resumes")
async def list_resumes():
return memory.get_resumes(config.DB_PATH)
@app.post("/resumes")
async def add_resume(data: dict):
rid = memory.add_resume(data['name'], data['content'], config.DB_PATH)
return {"status": "success", "id": rid}
@app.delete("/resumes/{rid}")
async def delete_resume(rid: int):
memory.remove_resume(rid, config.DB_PATH)
return {"status": "success"}
memory.set_primary_resume(rid, config.DB_PATH)
return {"status": "success"}
@app.get("/portals")
async def get_portals():
portals = memory.get_portals(config.DB_PATH)
return portals
@app.post("/portals")
async def add_portal(portal: dict = Body(...)):
memory.add_portal(portal['name'], portal['url'], config.DB_PATH)
sync_monitored_companies_file()
return {"status": "success"}
@app.delete("/portals/{pid}")
async def delete_portal(pid: int):
memory.remove_portal(pid, config.DB_PATH)
sync_monitored_companies_file()
return {"status": "success"}
# --- Application Intelligence ---
@app.post("/jobs/{jid}/match/{rid}")
async def match_job(jid: str, rid: int):
"""Recalculates match score for a specific job and resume."""
# 1. Fetch Job and Resume
jobs = memory.get_jobs(config.DB_PATH)
job = next((j for j in jobs if j['id'] == jid), None)
resumes = memory.get_resumes(config.DB_PATH)
resume = next((r for r in resumes if r['id'] == rid), None)
if not job or not resume:
return {"status": "error", "message": "Job or resume not found"}
analysis = decision.calculate_match_score(job['content'], resume['content'])
score = analysis.get('score', 0)
reason = analysis.get('reason', '')
gap = json.dumps(analysis.get('skills_gap', []))
# Update DB
conn = memory._get_connection(config.DB_PATH)
conn.execute("UPDATE jobs SET match_score = ?, match_reasoning = ?, skills_gap = ?, selected_resume_id = ? WHERE id = ?", (score, reason, gap, rid, jid))
conn.commit()
return {"status": "success", "score": score, "reason": reason, "skills_gap": analysis.get('skills_gap', [])}
@app.get("/jobs/{jid}/kit")
async def get_job_kit(jid: str):
"""Generates a tailored application kit for the selected resume."""
jobs = memory.get_jobs(config.DB_PATH)
job = next((j for j in jobs if j['id'] == jid), None)
if not job:
return {"status": "error", "message": "Job not found"}
# Find the selected resume or the primary one
rid = job.get('selected_resume_id')
resumes = memory.get_resumes(config.DB_PATH)
resume = next((r for r in resumes if r['id'] == rid), None) if rid else memory.get_primary_resume(config.DB_PATH)
if not resume:
return {"status": "error", "message": "No resume found for kit generation"}
kit = decision.generate_application_kit(job['content'], resume['content'])
return {"status": "success", "kit": kit, "resume_name": resume['name']}
class CoverLetterRequest(BaseModel):
company_info: str
resume_id: int
@app.post("/generate-cover-letter")
async def manual_cover_letter(req: CoverLetterRequest):
"""Generates a cover letter without a pre-ingested job."""
resumes = memory.get_resumes(config.DB_PATH)
resume = next((r for r in resumes if r['id'] == req.resume_id), None)
if not resume:
return {"status": "error", "message": "Resume profile not found"}
letter = decision.generate_custom_cover_letter(req.company_info, resume['content'])
return {"status": "success", "letter": letter}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)