Spaces:
Sleeping
Sleeping
Add application file
Browse files- .gitignore +2 -2
- Dockerfile +20 -20
- LICENSE +21 -21
- api/index.py +1 -1
- app/api/routes/recommendations.py +15 -15
- app/core/models.py +85 -85
- app/main.py +14 -14
- app/schemas/recommendation.py +16 -16
- app/services/ranking.py +121 -121
- app/utils/text.py +17 -17
- requirements.txt +17 -17
- vercel.json +14 -14
.gitignore
CHANGED
|
@@ -1,2 +1,2 @@
|
|
| 1 |
-
__pycache__
|
| 2 |
-
venv
|
|
|
|
| 1 |
+
__pycache__
|
| 2 |
+
venv
|
Dockerfile
CHANGED
|
@@ -1,20 +1,20 @@
|
|
| 1 |
-
# Use an official Python runtime as a parent image
|
| 2 |
-
FROM python:3.9-slim
|
| 3 |
-
|
| 4 |
-
# Set the working directory in the container
|
| 5 |
-
WORKDIR /app
|
| 6 |
-
|
| 7 |
-
# Copy the requirements file and install dependencies first to leverage caching
|
| 8 |
-
COPY requirements.txt .
|
| 9 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 10 |
-
|
| 11 |
-
# Copy all of your project files from the repository into the container
|
| 12 |
-
COPY . .
|
| 13 |
-
|
| 14 |
-
# Tell Docker that the container listens on port 7860
|
| 15 |
-
# Hugging Face Spaces expects applications to run on this port
|
| 16 |
-
EXPOSE 7860
|
| 17 |
-
|
| 18 |
-
# Define the command to run your app
|
| 19 |
-
# This assumes your main file is `main.py` and the FastAPI variable is `app`
|
| 20 |
-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 1 |
+
# Use an official Python runtime as a parent image
|
| 2 |
+
FROM python:3.9-slim
|
| 3 |
+
|
| 4 |
+
# Set the working directory in the container
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
|
| 7 |
+
# Copy the requirements file and install dependencies first to leverage caching
|
| 8 |
+
COPY requirements.txt .
|
| 9 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 10 |
+
|
| 11 |
+
# Copy all of your project files from the repository into the container
|
| 12 |
+
COPY . .
|
| 13 |
+
|
| 14 |
+
# Tell Docker that the container listens on port 7860
|
| 15 |
+
# Hugging Face Spaces expects applications to run on this port
|
| 16 |
+
EXPOSE 7860
|
| 17 |
+
|
| 18 |
+
# Define the command to run your app
|
| 19 |
+
# This assumes your main file is `main.py` and the FastAPI variable is `app`
|
| 20 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
| 1 |
-
MIT License
|
| 2 |
-
|
| 3 |
-
Copyright (c) 2025 Kevin Bramasta Arvyto Wardhana
|
| 4 |
-
|
| 5 |
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
-
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
-
in the Software without restriction, including without limitation the rights
|
| 8 |
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
-
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
-
furnished to do so, subject to the following conditions:
|
| 11 |
-
|
| 12 |
-
The above copyright notice and this permission notice shall be included in all
|
| 13 |
-
copies or substantial portions of the Software.
|
| 14 |
-
|
| 15 |
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
-
SOFTWARE.
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Kevin Bramasta Arvyto Wardhana
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
api/index.py
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
from app.main import app
|
|
|
|
| 1 |
+
from app.main import app
|
app/api/routes/recommendations.py
CHANGED
|
@@ -1,15 +1,15 @@
|
|
| 1 |
-
from fastapi import APIRouter
|
| 2 |
-
from ...schemas.recommendation import ProfileRequest, RecommendationRequest
|
| 3 |
-
from ...services import ranking
|
| 4 |
-
|
| 5 |
-
router = APIRouter()
|
| 6 |
-
|
| 7 |
-
@router.post("/predict-category", tags=["Predictions"])
|
| 8 |
-
def predict_category(request: ProfileRequest):
|
| 9 |
-
category = ranking.get_category_prediction(request.profile_text)
|
| 10 |
-
return {"predicted_category": category}
|
| 11 |
-
|
| 12 |
-
@router.post("/recommend-internships", tags=["Predictions"])
|
| 13 |
-
def recommend_internships(request: RecommendationRequest):
|
| 14 |
-
ranked_ids = ranking.get_ranked_internships(request)
|
| 15 |
-
return {"recommendations": ranked_ids}
|
|
|
|
| 1 |
+
from fastapi import APIRouter
|
| 2 |
+
from ...schemas.recommendation import ProfileRequest, RecommendationRequest
|
| 3 |
+
from ...services import ranking
|
| 4 |
+
|
| 5 |
+
router = APIRouter()
|
| 6 |
+
|
| 7 |
+
@router.post("/predict-category", tags=["Predictions"])
|
| 8 |
+
def predict_category(request: ProfileRequest):
|
| 9 |
+
category = ranking.get_category_prediction(request.profile_text)
|
| 10 |
+
return {"predicted_category": category}
|
| 11 |
+
|
| 12 |
+
@router.post("/recommend-internships", tags=["Predictions"])
|
| 13 |
+
def recommend_internships(request: RecommendationRequest):
|
| 14 |
+
ranked_ids = ranking.get_ranked_internships(request)
|
| 15 |
+
return {"recommendations": ranked_ids}
|
app/core/models.py
CHANGED
|
@@ -1,85 +1,85 @@
|
|
| 1 |
-
import joblib
|
| 2 |
-
from sentence_transformers import SentenceTransformer
|
| 3 |
-
import os
|
| 4 |
-
import requests
|
| 5 |
-
from huggingface_hub import snapshot_download # <-- Add this import
|
| 6 |
-
|
| 7 |
-
TEMP_DIR = "/tmp"
|
| 8 |
-
|
| 9 |
-
# This function for your .pkl files is still correct and needed
|
| 10 |
-
def download_and_load_model(model_url, model_filename):
|
| 11 |
-
# ... (no changes needed in this function)
|
| 12 |
-
local_path = os.path.join(TEMP_DIR, model_filename)
|
| 13 |
-
if not os.path.exists(local_path):
|
| 14 |
-
print(f"Downloading model from {model_url} to {local_path}...")
|
| 15 |
-
try:
|
| 16 |
-
response = requests.get(model_url, stream=True)
|
| 17 |
-
response.raise_for_status()
|
| 18 |
-
with open(local_path, "wb") as f:
|
| 19 |
-
for chunk in response.iter_content(chunk_size=8192):
|
| 20 |
-
f.write(chunk)
|
| 21 |
-
print("Download complete.")
|
| 22 |
-
except requests.exceptions.RequestException as e:
|
| 23 |
-
print(f"Failed to download model {model_filename}. Error: {e}")
|
| 24 |
-
return None
|
| 25 |
-
try:
|
| 26 |
-
return joblib.load(local_path)
|
| 27 |
-
except Exception as e:
|
| 28 |
-
print(f"Failed to load model {local_path}. Error: {e}")
|
| 29 |
-
return None
|
| 30 |
-
|
| 31 |
-
# --- NEW FUNCTION FOR THE SENTENCE TRANSFORMER ---
|
| 32 |
-
def get_sentence_transformer(model_name='all-MiniLM-L6-v2'):
|
| 33 |
-
"""
|
| 34 |
-
Downloads the SentenceTransformer model to /tmp if it doesn't exist,
|
| 35 |
-
then loads it from there.
|
| 36 |
-
"""
|
| 37 |
-
local_model_path = os.path.join(TEMP_DIR, model_name)
|
| 38 |
-
|
| 39 |
-
if not os.path.exists(local_model_path):
|
| 40 |
-
print(f"Downloading SentenceTransformer model '{model_name}' to {local_model_path}...")
|
| 41 |
-
# Use snapshot_download to get all files for the model from Hugging Face
|
| 42 |
-
try:
|
| 43 |
-
snapshot_download(repo_id=f"sentence-transformers/{model_name}",
|
| 44 |
-
local_dir=local_model_path,
|
| 45 |
-
local_dir_use_symlinks=False) # This is important for Vercel
|
| 46 |
-
print("Download complete.")
|
| 47 |
-
except Exception as e:
|
| 48 |
-
print(f"Failed to download SentenceTransformer model. Error: {e}")
|
| 49 |
-
return None
|
| 50 |
-
|
| 51 |
-
# Load the model from the local path in /tmp
|
| 52 |
-
try:
|
| 53 |
-
print(f"Loading SentenceTransformer model from {local_model_path}...")
|
| 54 |
-
return SentenceTransformer(local_model_path)
|
| 55 |
-
except Exception as e:
|
| 56 |
-
print(f"Failed to load SentenceTransformer model from {local_model_path}. Error: {e}")
|
| 57 |
-
return None
|
| 58 |
-
|
| 59 |
-
# --- Main Model Loading Logic ---
|
| 60 |
-
try:
|
| 61 |
-
# Your .pkl model loading remains the same
|
| 62 |
-
TFIDF_URL = "https://pub-4a389a9b2dc842a2a55678d2db0ec0c6.r2.dev/tfidf_vectorizer.pkl"
|
| 63 |
-
LE_URL = "https://pub-4a389a9b2dc842a2a55678d2db0ec0c6.r2.dev/label_encoder.pkl"
|
| 64 |
-
RF_MODEL_URL = "https://pub-4a389a9b2dc842a2a55678d2db0ec0c6.r2.dev/random_forest_model.pkl"
|
| 65 |
-
|
| 66 |
-
tfidf_vectorizer = download_and_load_model(TFIDF_URL, "tfidf_vectorizer.pkl")
|
| 67 |
-
le = download_and_load_model(LE_URL, "label_encoder.pkl")
|
| 68 |
-
rf_model = download_and_load_model(RF_MODEL_URL, "random_forest_model.pkl")
|
| 69 |
-
|
| 70 |
-
if all([tfidf_vectorizer, le, rf_model]):
|
| 71 |
-
print("Classification models loaded successfully.")
|
| 72 |
-
else:
|
| 73 |
-
print("One or more classification models failed to load.")
|
| 74 |
-
|
| 75 |
-
# --- THIS IS THE LINE TO CHANGE ---
|
| 76 |
-
# Old line: sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 77 |
-
# New line:
|
| 78 |
-
sentence_model = get_sentence_transformer()
|
| 79 |
-
if sentence_model:
|
| 80 |
-
print("SentenceTransformer model loaded successfully.")
|
| 81 |
-
else:
|
| 82 |
-
print("SentenceTransformer model failed to load.")
|
| 83 |
-
|
| 84 |
-
except Exception as e:
|
| 85 |
-
print(f"An unexpected error occurred during model loading: {e}")
|
|
|
|
| 1 |
+
import joblib
|
| 2 |
+
from sentence_transformers import SentenceTransformer
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
from huggingface_hub import snapshot_download # <-- Add this import
|
| 6 |
+
|
| 7 |
+
TEMP_DIR = "/tmp"
|
| 8 |
+
|
| 9 |
+
# This function for your .pkl files is still correct and needed
|
| 10 |
+
def download_and_load_model(model_url, model_filename):
|
| 11 |
+
# ... (no changes needed in this function)
|
| 12 |
+
local_path = os.path.join(TEMP_DIR, model_filename)
|
| 13 |
+
if not os.path.exists(local_path):
|
| 14 |
+
print(f"Downloading model from {model_url} to {local_path}...")
|
| 15 |
+
try:
|
| 16 |
+
response = requests.get(model_url, stream=True)
|
| 17 |
+
response.raise_for_status()
|
| 18 |
+
with open(local_path, "wb") as f:
|
| 19 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 20 |
+
f.write(chunk)
|
| 21 |
+
print("Download complete.")
|
| 22 |
+
except requests.exceptions.RequestException as e:
|
| 23 |
+
print(f"Failed to download model {model_filename}. Error: {e}")
|
| 24 |
+
return None
|
| 25 |
+
try:
|
| 26 |
+
return joblib.load(local_path)
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"Failed to load model {local_path}. Error: {e}")
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
# --- NEW FUNCTION FOR THE SENTENCE TRANSFORMER ---
|
| 32 |
+
def get_sentence_transformer(model_name='all-MiniLM-L6-v2'):
|
| 33 |
+
"""
|
| 34 |
+
Downloads the SentenceTransformer model to /tmp if it doesn't exist,
|
| 35 |
+
then loads it from there.
|
| 36 |
+
"""
|
| 37 |
+
local_model_path = os.path.join(TEMP_DIR, model_name)
|
| 38 |
+
|
| 39 |
+
if not os.path.exists(local_model_path):
|
| 40 |
+
print(f"Downloading SentenceTransformer model '{model_name}' to {local_model_path}...")
|
| 41 |
+
# Use snapshot_download to get all files for the model from Hugging Face
|
| 42 |
+
try:
|
| 43 |
+
snapshot_download(repo_id=f"sentence-transformers/{model_name}",
|
| 44 |
+
local_dir=local_model_path,
|
| 45 |
+
local_dir_use_symlinks=False) # This is important for Vercel
|
| 46 |
+
print("Download complete.")
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"Failed to download SentenceTransformer model. Error: {e}")
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
# Load the model from the local path in /tmp
|
| 52 |
+
try:
|
| 53 |
+
print(f"Loading SentenceTransformer model from {local_model_path}...")
|
| 54 |
+
return SentenceTransformer(local_model_path)
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Failed to load SentenceTransformer model from {local_model_path}. Error: {e}")
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
# --- Main Model Loading Logic ---
|
| 60 |
+
try:
|
| 61 |
+
# Your .pkl model loading remains the same
|
| 62 |
+
TFIDF_URL = "https://pub-4a389a9b2dc842a2a55678d2db0ec0c6.r2.dev/tfidf_vectorizer.pkl"
|
| 63 |
+
LE_URL = "https://pub-4a389a9b2dc842a2a55678d2db0ec0c6.r2.dev/label_encoder.pkl"
|
| 64 |
+
RF_MODEL_URL = "https://pub-4a389a9b2dc842a2a55678d2db0ec0c6.r2.dev/random_forest_model.pkl"
|
| 65 |
+
|
| 66 |
+
tfidf_vectorizer = download_and_load_model(TFIDF_URL, "tfidf_vectorizer.pkl")
|
| 67 |
+
le = download_and_load_model(LE_URL, "label_encoder.pkl")
|
| 68 |
+
rf_model = download_and_load_model(RF_MODEL_URL, "random_forest_model.pkl")
|
| 69 |
+
|
| 70 |
+
if all([tfidf_vectorizer, le, rf_model]):
|
| 71 |
+
print("Classification models loaded successfully.")
|
| 72 |
+
else:
|
| 73 |
+
print("One or more classification models failed to load.")
|
| 74 |
+
|
| 75 |
+
# --- THIS IS THE LINE TO CHANGE ---
|
| 76 |
+
# Old line: sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 77 |
+
# New line:
|
| 78 |
+
sentence_model = get_sentence_transformer()
|
| 79 |
+
if sentence_model:
|
| 80 |
+
print("SentenceTransformer model loaded successfully.")
|
| 81 |
+
else:
|
| 82 |
+
print("SentenceTransformer model failed to load.")
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
print(f"An unexpected error occurred during model loading: {e}")
|
app/main.py
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
-
from .api.routes import recommendations
|
| 3 |
-
|
| 4 |
-
app = FastAPI(
|
| 5 |
-
title="Student Recommendation API",
|
| 6 |
-
description="An API that uses machine learning to predict job categories and recommend internships.",
|
| 7 |
-
version="1.0.0"
|
| 8 |
-
)
|
| 9 |
-
|
| 10 |
-
app.include_router(recommendations.router, prefix="/api/v1")
|
| 11 |
-
|
| 12 |
-
@app.get("/", tags=["Root"])
|
| 13 |
-
def read_root():
|
| 14 |
-
return {"message": "Welcome to the Student Recommendation API"}
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from .api.routes import recommendations
|
| 3 |
+
|
| 4 |
+
app = FastAPI(
|
| 5 |
+
title="Student Recommendation API",
|
| 6 |
+
description="An API that uses machine learning to predict job categories and recommend internships.",
|
| 7 |
+
version="1.0.0"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
app.include_router(recommendations.router, prefix="/api/v1")
|
| 11 |
+
|
| 12 |
+
@app.get("/", tags=["Root"])
|
| 13 |
+
def read_root():
|
| 14 |
+
return {"message": "Welcome to the Student Recommendation API"}
|
app/schemas/recommendation.py
CHANGED
|
@@ -1,16 +1,16 @@
|
|
| 1 |
-
from pydantic import BaseModel
|
| 2 |
-
from typing import List, Optional
|
| 3 |
-
|
| 4 |
-
class ProfileRequest(BaseModel):
|
| 5 |
-
profile_text: str
|
| 6 |
-
|
| 7 |
-
class InternshipItem(BaseModel):
|
| 8 |
-
id: int
|
| 9 |
-
internship_text: str
|
| 10 |
-
location: str
|
| 11 |
-
|
| 12 |
-
class RecommendationRequest(BaseModel):
|
| 13 |
-
profile_text: str
|
| 14 |
-
predicted_category: Optional[str] = None
|
| 15 |
-
preferred_location: str
|
| 16 |
-
internships: List[InternshipItem]
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
|
| 4 |
+
class ProfileRequest(BaseModel):
|
| 5 |
+
profile_text: str
|
| 6 |
+
|
| 7 |
+
class InternshipItem(BaseModel):
|
| 8 |
+
id: int
|
| 9 |
+
internship_text: str
|
| 10 |
+
location: str
|
| 11 |
+
|
| 12 |
+
class RecommendationRequest(BaseModel):
|
| 13 |
+
profile_text: str
|
| 14 |
+
predicted_category: Optional[str] = None
|
| 15 |
+
preferred_location: str
|
| 16 |
+
internships: List[InternshipItem]
|
app/services/ranking.py
CHANGED
|
@@ -1,121 +1,121 @@
|
|
| 1 |
-
from geopy.distance import geodesic
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
from geopy.geocoders import Nominatim
|
| 5 |
-
|
| 6 |
-
from ..core.models import tfidf_vectorizer, le, rf_model, sentence_model
|
| 7 |
-
from ..schemas.recommendation import RecommendationRequest
|
| 8 |
-
from ..utils.text import clean_resume
|
| 9 |
-
|
| 10 |
-
geolocator = Nominatim(user_agent="student_recommendation_api_v1")
|
| 11 |
-
|
| 12 |
-
GEO_CACHE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "GEO_CACHE.txt")
|
| 13 |
-
GEO_CACHE = {}
|
| 14 |
-
|
| 15 |
-
def load_geo_cache():
|
| 16 |
-
global GEO_CACHE
|
| 17 |
-
if os.path.exists(GEO_CACHE_FILE):
|
| 18 |
-
with open(GEO_CACHE_FILE, "r") as f:
|
| 19 |
-
try:
|
| 20 |
-
GEO_CACHE = json.load(f)
|
| 21 |
-
except json.JSONDecodeError:
|
| 22 |
-
GEO_CACHE = {}
|
| 23 |
-
|
| 24 |
-
def save_geo_cache():
|
| 25 |
-
with open(GEO_CACHE_FILE, "w") as f:
|
| 26 |
-
json.dump(GEO_CACHE, f)
|
| 27 |
-
|
| 28 |
-
load_geo_cache()
|
| 29 |
-
|
| 30 |
-
def geo_coords(city_name: str) -> tuple | None:
|
| 31 |
-
"""
|
| 32 |
-
Geocodes a city name to (latitude, longitude).
|
| 33 |
-
Uses an in-memory cache to avoid repeated API calls.
|
| 34 |
-
"""
|
| 35 |
-
city_name = city_name.lower().strip()
|
| 36 |
-
if city_name in GEO_CACHE:
|
| 37 |
-
return GEO_CACHE[city_name]
|
| 38 |
-
try:
|
| 39 |
-
print(f"--- Geocoding and caching new city: {city_name} ---")
|
| 40 |
-
location = geolocator.geocode(f"{city_name}, Indonesia")
|
| 41 |
-
|
| 42 |
-
if location:
|
| 43 |
-
coords = (location.latitude, location.longitude)
|
| 44 |
-
GEO_CACHE[city_name] = coords
|
| 45 |
-
save_geo_cache()
|
| 46 |
-
return coords
|
| 47 |
-
else:
|
| 48 |
-
print(f"Location not found for {city_name}")
|
| 49 |
-
GEO_CACHE[city_name] = None
|
| 50 |
-
save_geo_cache()
|
| 51 |
-
return None
|
| 52 |
-
except Exception as e:
|
| 53 |
-
print(f"Error geocoding {city_name}: {e}")
|
| 54 |
-
return None
|
| 55 |
-
|
| 56 |
-
def get_category_prediction(profile_text: str) -> str:
|
| 57 |
-
"""Processes text and predicts the job category."""
|
| 58 |
-
cleaned_text = profile_text.lower()
|
| 59 |
-
vectorized_text = tfidf_vectorizer.transform([cleaned_text])
|
| 60 |
-
prediction_encoded = rf_model.predict(vectorized_text)[0]
|
| 61 |
-
category = le.inverse_transform([prediction_encoded])[0]
|
| 62 |
-
return category
|
| 63 |
-
|
| 64 |
-
def get_ranked_internships(request: RecommendationRequest) -> list[int]:
|
| 65 |
-
"""Performs two-stage ranking with dynamic geocoding."""
|
| 66 |
-
|
| 67 |
-
profile_text_to_encode = request.profile_text
|
| 68 |
-
|
| 69 |
-
if request.predicted_category:
|
| 70 |
-
profile_text_to_encode = f"The user's predicted job category is {request.predicted_category}. Based on that, consider their profile: {request.profile_text}"
|
| 71 |
-
|
| 72 |
-
profile_embedding = sentence_model.encode(profile_text_to_encode)
|
| 73 |
-
internship_texts = [internship.internship_text for internship in request.internships]
|
| 74 |
-
|
| 75 |
-
if not internship_texts:
|
| 76 |
-
return []
|
| 77 |
-
|
| 78 |
-
internship_embeddings = sentence_model.encode(internship_texts)
|
| 79 |
-
cosine_score = sentence_model.similarity(profile_embedding, internship_embeddings)[0].tolist()
|
| 80 |
-
|
| 81 |
-
print("--- FastAPI Debugging ---")
|
| 82 |
-
print(f"Received {len(internship_texts)} internships to rank.")
|
| 83 |
-
print(f"Calculated Cosine Scores: {cosine_score}")
|
| 84 |
-
print("--------------------------")
|
| 85 |
-
|
| 86 |
-
ranked_by_similarity = []
|
| 87 |
-
for i, internship in enumerate(request.internships):
|
| 88 |
-
ranked_by_similarity.append({
|
| 89 |
-
"id": internship.id,
|
| 90 |
-
"similarity_score": cosine_score[i],
|
| 91 |
-
"location": internship.location,
|
| 92 |
-
})
|
| 93 |
-
|
| 94 |
-
final_ranked_list = []
|
| 95 |
-
user_coords = geo_coords(request.preferred_location)
|
| 96 |
-
|
| 97 |
-
print(user_coords, request.preferred_location)
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
for internship in ranked_by_similarity:
|
| 101 |
-
final_score = internship['similarity_score']
|
| 102 |
-
|
| 103 |
-
if user_coords:
|
| 104 |
-
internship_coords = geo_coords(internship['location'])
|
| 105 |
-
if internship_coords:
|
| 106 |
-
distance_km = geodesic(user_coords, internship_coords).kilometers
|
| 107 |
-
if distance_km < 1:
|
| 108 |
-
final_score += 2.0
|
| 109 |
-
elif distance_km < 150:
|
| 110 |
-
final_score += 0.75
|
| 111 |
-
|
| 112 |
-
internship['final_score'] = final_score
|
| 113 |
-
final_ranked_list.append(internship)
|
| 114 |
-
|
| 115 |
-
final_ranked_list.sort(key=lambda x: x['final_score'], reverse=True)
|
| 116 |
-
|
| 117 |
-
final_ids = [item['id'] for item in final_ranked_list]
|
| 118 |
-
|
| 119 |
-
print(final_ranked_list)
|
| 120 |
-
|
| 121 |
-
return final_ids
|
|
|
|
| 1 |
+
from geopy.distance import geodesic
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from geopy.geocoders import Nominatim
|
| 5 |
+
|
| 6 |
+
from ..core.models import tfidf_vectorizer, le, rf_model, sentence_model
|
| 7 |
+
from ..schemas.recommendation import RecommendationRequest
|
| 8 |
+
from ..utils.text import clean_resume
|
| 9 |
+
|
| 10 |
+
geolocator = Nominatim(user_agent="student_recommendation_api_v1")
|
| 11 |
+
|
| 12 |
+
GEO_CACHE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "GEO_CACHE.txt")
|
| 13 |
+
GEO_CACHE = {}
|
| 14 |
+
|
| 15 |
+
def load_geo_cache():
|
| 16 |
+
global GEO_CACHE
|
| 17 |
+
if os.path.exists(GEO_CACHE_FILE):
|
| 18 |
+
with open(GEO_CACHE_FILE, "r") as f:
|
| 19 |
+
try:
|
| 20 |
+
GEO_CACHE = json.load(f)
|
| 21 |
+
except json.JSONDecodeError:
|
| 22 |
+
GEO_CACHE = {}
|
| 23 |
+
|
| 24 |
+
def save_geo_cache():
|
| 25 |
+
with open(GEO_CACHE_FILE, "w") as f:
|
| 26 |
+
json.dump(GEO_CACHE, f)
|
| 27 |
+
|
| 28 |
+
load_geo_cache()
|
| 29 |
+
|
| 30 |
+
def geo_coords(city_name: str) -> tuple | None:
|
| 31 |
+
"""
|
| 32 |
+
Geocodes a city name to (latitude, longitude).
|
| 33 |
+
Uses an in-memory cache to avoid repeated API calls.
|
| 34 |
+
"""
|
| 35 |
+
city_name = city_name.lower().strip()
|
| 36 |
+
if city_name in GEO_CACHE:
|
| 37 |
+
return GEO_CACHE[city_name]
|
| 38 |
+
try:
|
| 39 |
+
print(f"--- Geocoding and caching new city: {city_name} ---")
|
| 40 |
+
location = geolocator.geocode(f"{city_name}, Indonesia")
|
| 41 |
+
|
| 42 |
+
if location:
|
| 43 |
+
coords = (location.latitude, location.longitude)
|
| 44 |
+
GEO_CACHE[city_name] = coords
|
| 45 |
+
save_geo_cache()
|
| 46 |
+
return coords
|
| 47 |
+
else:
|
| 48 |
+
print(f"Location not found for {city_name}")
|
| 49 |
+
GEO_CACHE[city_name] = None
|
| 50 |
+
save_geo_cache()
|
| 51 |
+
return None
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"Error geocoding {city_name}: {e}")
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
def get_category_prediction(profile_text: str) -> str:
|
| 57 |
+
"""Processes text and predicts the job category."""
|
| 58 |
+
cleaned_text = profile_text.lower()
|
| 59 |
+
vectorized_text = tfidf_vectorizer.transform([cleaned_text])
|
| 60 |
+
prediction_encoded = rf_model.predict(vectorized_text)[0]
|
| 61 |
+
category = le.inverse_transform([prediction_encoded])[0]
|
| 62 |
+
return category
|
| 63 |
+
|
| 64 |
+
def get_ranked_internships(request: RecommendationRequest) -> list[int]:
|
| 65 |
+
"""Performs two-stage ranking with dynamic geocoding."""
|
| 66 |
+
|
| 67 |
+
profile_text_to_encode = request.profile_text
|
| 68 |
+
|
| 69 |
+
if request.predicted_category:
|
| 70 |
+
profile_text_to_encode = f"The user's predicted job category is {request.predicted_category}. Based on that, consider their profile: {request.profile_text}"
|
| 71 |
+
|
| 72 |
+
profile_embedding = sentence_model.encode(profile_text_to_encode)
|
| 73 |
+
internship_texts = [internship.internship_text for internship in request.internships]
|
| 74 |
+
|
| 75 |
+
if not internship_texts:
|
| 76 |
+
return []
|
| 77 |
+
|
| 78 |
+
internship_embeddings = sentence_model.encode(internship_texts)
|
| 79 |
+
cosine_score = sentence_model.similarity(profile_embedding, internship_embeddings)[0].tolist()
|
| 80 |
+
|
| 81 |
+
print("--- FastAPI Debugging ---")
|
| 82 |
+
print(f"Received {len(internship_texts)} internships to rank.")
|
| 83 |
+
print(f"Calculated Cosine Scores: {cosine_score}")
|
| 84 |
+
print("--------------------------")
|
| 85 |
+
|
| 86 |
+
ranked_by_similarity = []
|
| 87 |
+
for i, internship in enumerate(request.internships):
|
| 88 |
+
ranked_by_similarity.append({
|
| 89 |
+
"id": internship.id,
|
| 90 |
+
"similarity_score": cosine_score[i],
|
| 91 |
+
"location": internship.location,
|
| 92 |
+
})
|
| 93 |
+
|
| 94 |
+
final_ranked_list = []
|
| 95 |
+
user_coords = geo_coords(request.preferred_location)
|
| 96 |
+
|
| 97 |
+
print(user_coords, request.preferred_location)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
for internship in ranked_by_similarity:
|
| 101 |
+
final_score = internship['similarity_score']
|
| 102 |
+
|
| 103 |
+
if user_coords:
|
| 104 |
+
internship_coords = geo_coords(internship['location'])
|
| 105 |
+
if internship_coords:
|
| 106 |
+
distance_km = geodesic(user_coords, internship_coords).kilometers
|
| 107 |
+
if distance_km < 1:
|
| 108 |
+
final_score += 2.0
|
| 109 |
+
elif distance_km < 150:
|
| 110 |
+
final_score += 0.75
|
| 111 |
+
|
| 112 |
+
internship['final_score'] = final_score
|
| 113 |
+
final_ranked_list.append(internship)
|
| 114 |
+
|
| 115 |
+
final_ranked_list.sort(key=lambda x: x['final_score'], reverse=True)
|
| 116 |
+
|
| 117 |
+
final_ids = [item['id'] for item in final_ranked_list]
|
| 118 |
+
|
| 119 |
+
print(final_ranked_list)
|
| 120 |
+
|
| 121 |
+
return final_ids
|
app/utils/text.py
CHANGED
|
@@ -1,17 +1,17 @@
|
|
| 1 |
-
import re
|
| 2 |
-
|
| 3 |
-
def clean_resume(text: str) -> str:
|
| 4 |
-
"""
|
| 5 |
-
Cleans the input resume text by removing URLs, special characters,
|
| 6 |
-
and extra whitespace, and converting to lowercase.
|
| 7 |
-
"""
|
| 8 |
-
# Remove URLs
|
| 9 |
-
text = re.sub(r'http\S+|www\S+', '', text)
|
| 10 |
-
# Remove non-alphanumeric characters (keeps only letters and spaces)
|
| 11 |
-
text = re.sub(r'[^A-Za-z\s]', '', text)
|
| 12 |
-
# Convert to lowercase
|
| 13 |
-
text = text.lower()
|
| 14 |
-
# Remove extra whitespace
|
| 15 |
-
text = re.sub(r'\s+', ' ', text).strip()
|
| 16 |
-
|
| 17 |
-
return text
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
def clean_resume(text: str) -> str:
|
| 4 |
+
"""
|
| 5 |
+
Cleans the input resume text by removing URLs, special characters,
|
| 6 |
+
and extra whitespace, and converting to lowercase.
|
| 7 |
+
"""
|
| 8 |
+
# Remove URLs
|
| 9 |
+
text = re.sub(r'http\S+|www\S+', '', text)
|
| 10 |
+
# Remove non-alphanumeric characters (keeps only letters and spaces)
|
| 11 |
+
text = re.sub(r'[^A-Za-z\s]', '', text)
|
| 12 |
+
# Convert to lowercase
|
| 13 |
+
text = text.lower()
|
| 14 |
+
# Remove extra whitespace
|
| 15 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 16 |
+
|
| 17 |
+
return text
|
requirements.txt
CHANGED
|
@@ -1,17 +1,17 @@
|
|
| 1 |
-
# Core FastAPI Framework
|
| 2 |
-
fastapi
|
| 3 |
-
uvicorn
|
| 4 |
-
requests
|
| 5 |
-
|
| 6 |
-
# Machine Learning & Data
|
| 7 |
-
scikit-learn
|
| 8 |
-
joblib
|
| 9 |
-
sentence-transformers
|
| 10 |
-
torch
|
| 11 |
-
geopy
|
| 12 |
-
huggingface-hub
|
| 13 |
-
# Pydantic is a dependency of FastAPI, but we list it for clarity
|
| 14 |
-
pydantic
|
| 15 |
-
|
| 16 |
-
# Good practice for managing environment variables
|
| 17 |
-
python-dotenv
|
|
|
|
| 1 |
+
# Core FastAPI Framework
|
| 2 |
+
fastapi
|
| 3 |
+
uvicorn
|
| 4 |
+
requests
|
| 5 |
+
|
| 6 |
+
# Machine Learning & Data
|
| 7 |
+
scikit-learn
|
| 8 |
+
joblib
|
| 9 |
+
sentence-transformers
|
| 10 |
+
torch
|
| 11 |
+
geopy
|
| 12 |
+
huggingface-hub
|
| 13 |
+
# Pydantic is a dependency of FastAPI, but we list it for clarity
|
| 14 |
+
pydantic
|
| 15 |
+
|
| 16 |
+
# Good practice for managing environment variables
|
| 17 |
+
python-dotenv
|
vercel.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
-
{
|
| 2 |
-
"functions": {
|
| 3 |
-
"api/index.py": {
|
| 4 |
-
"maxDuration": 60,
|
| 5 |
-
"memory": 3008
|
| 6 |
-
}
|
| 7 |
-
},
|
| 8 |
-
"routes": [
|
| 9 |
-
{
|
| 10 |
-
"src": "/(.*)",
|
| 11 |
-
"dest": "api/index.py"
|
| 12 |
-
}
|
| 13 |
-
]
|
| 14 |
-
}
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"functions": {
|
| 3 |
+
"api/index.py": {
|
| 4 |
+
"maxDuration": 60,
|
| 5 |
+
"memory": 3008
|
| 6 |
+
}
|
| 7 |
+
},
|
| 8 |
+
"routes": [
|
| 9 |
+
{
|
| 10 |
+
"src": "/(.*)",
|
| 11 |
+
"dest": "api/index.py"
|
| 12 |
+
}
|
| 13 |
+
]
|
| 14 |
+
}
|