justKevv commited on
Commit
cc94a9d
·
1 Parent(s): 96bd1b3
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__
2
+ venv
Dockerfile ADDED
@@ -0,0 +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"]
GEO_CACHE.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ {"jakarta": [-6.1754049, 106.827168], "jayapura": [-2.5387539, 140.7037389], "gorontalo": [0.7186174, 122.4555927], "pekanbaru": [0.5262455, 101.4515727], "pangkal pinang": [-2.1206733, 106.1134604], "tomohon": [1.3255914, 124.838605], "administrasi jakarta pusat": [-6.18234, 106.8428715], "parepare": [-4.0202504, 119.6611703], "gunungsitoli": [1.2900569, 97.6150768], "dumai": [1.6631967, 101.4470369], "batu": [-7.8711667, 112.5269482], "solok": [-0.93103, 100.804328], "malang": [-7.9771308, 112.6340265], "samarinda": [-0.5017804, 117.1393089], "kendari": [-3.9918068, 122.5180066], "semarang": [-6.9903988, 110.4229104], "bogor": [-6.5962986, 106.7972421], "padangpanjang": [-0.4654636, 100.3932441], "palu": [-0.9051548, 119.8722373], "tebing tinggi": [3.3273686, 99.1623025], "langsa": [4.4730892, 97.9681841], "bitung": [1.44344, 125.1940836], "lubuklinggau": [-3.2919136, 102.8715732], "kupang": [-10.1632209, 123.6017755], "pariaman": [-0.6263889, 100.1177778], "binjai": [3.6063964, 98.4899865], "manado": [1.4900578, 124.8408708], "surabaya": [-7.2462836, 112.7377674], "mataram": [-8.5837726, 116.10685], "bukittinggi": [-0.3051954, 100.3694921], "blitar": [-8.1311983, 112.3115572], "metro": [-5.1078839, 105.3078642], "subulussalam": [2.6403146, 98.0052459], "prabumulih": [-3.4382688, 104.2310181], "bekasi": [-6.2349858, 106.9945444], "tangerang": [-6.1761924, 106.6382161], "kotamobagu": [0.7352231, 124.3154057], "tanjung pinang": [0.9236915, 104.446094], "tanjungbalai": [2.9703419, 99.8020903], "pekalongan": [-6.8905065, 109.6761489], "palopo": [-2.9996306, 120.1920679], "bau-bau": [-3.5671, 120.3863], "medan": [3.5894617, 98.6741623], "serang": [-6.1169662, 106.1518079], "singkawang": [0.9069861, 108.9889657], "sabang": [5.8927453, 95.3225751], "administrasi jakarta timur": [-6.2628908, 106.8822289], "tasikmalaya": [-7.3262484, 108.2201154], "administrasi jakarta barat": [-6.168982, 106.7895028], "yogyakarta": [-7.8012646, 110.3646857], "tangerang selatan": [-6.3227016, 106.7085737], "banjarmasin": [-3.3187496, 114.5925828], "kediri": [-7.8111057, 112.0046051], "bima": [-8.5647631, 118.762474], "madiun": [-7.6290837, 111.5168819], "palangka raya": [-2.2072919, 113.9164372], "jambi": [-1.6394711, 102.9454264], "palembang": [-2.9888243, 104.7568507], "tarakan": [3.3000169, 117.6330159], "padang": [-0.9247587, 100.3632561], "sukabumi": [-6.9199289, 106.9265095], "cirebon": [-6.7137044, 108.5608483], "payakumbuh": [-0.2242687, 100.6319419], "ambon": [-3.6959434, 128.178785], "mojokerto": [-7.5413378, 112.5094975], "sorong": [-0.8634105, 131.2544805], "tual": [-5.6389933, 132.7429249], "makassar": [-5.1342962, 119.4124282], "sawahlunto": [-0.6818141, 100.778552], "batam": [1.1030815, 104.0383696], "lhokseumawe": [5.1789659, 97.1480544], "sungai penuh": [-2.0706799, 101.3961054], "bandar lampung": [-5.4460713, 105.2643742], "denpasar": [-8.6524973, 115.2191175], "bandung": [-6.9218457, 107.6070833], "ternate": [0.7852043, 127.3832342], "bontang": [0.1236548, 117.471708], "administrasi jakarta utara": [-6.136197, 106.9006902], "probolinggo": [-7.7441461, 113.2158401], "banjarbaru": [-3.4430389, 114.8308816], "bengkulu": [-3.5186763, 102.5359834], "magelang": [-7.4770747, 110.2182164], "tegal": [-6.8674488, 109.1378271]}
LICENSE ADDED
@@ -0,0 +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.
api/index.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from app.main import app
app/__init__.py ADDED
File without changes
app/api/__init__.py ADDED
File without changes
app/api/routes/__init__.py ADDED
File without changes
app/api/routes/recommendations.py ADDED
@@ -0,0 +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}
app/core/__init__.py ADDED
File without changes
app/core/models.py ADDED
@@ -0,0 +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}")
app/main.py ADDED
@@ -0,0 +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"}
app/schemas/__init__.py ADDED
File without changes
app/schemas/recommendation.py ADDED
@@ -0,0 +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]
app/services/__init__.py ADDED
File without changes
app/services/ranking.py ADDED
@@ -0,0 +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
app/utils/__init__.py ADDED
File without changes
app/utils/text.py ADDED
@@ -0,0 +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
requirements.txt ADDED
@@ -0,0 +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
vercel.json ADDED
@@ -0,0 +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
+ }