justKevv commited on
Commit
5e0b388
·
1 Parent(s): 1948db1

Add application file

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/*.pkl filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__
2
+ .venv
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Create cache directories with proper permissions
8
+ RUN mkdir -p /tmp/transformers_cache /tmp/hf_home && \
9
+ chmod 777 /tmp/transformers_cache /tmp/hf_home
10
+
11
+ # Set environment variables for transformers cache
12
+ ENV TRANSFORMERS_CACHE=/tmp/transformers_cache
13
+ ENV HF_HOME=/tmp/hf_home
14
+
15
+ # Copy the requirements file and install dependencies first to leverage caching
16
+ COPY requirements.txt .
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # Copy all of your project files from the repository into the container
20
+ COPY . .
21
+
22
+ # Tell Docker that the container listens on port 7860
23
+ # Hugging Face Spaces expects applications to run on this port
24
+ EXPOSE 7860
25
+
26
+ # --- CORRECTED COMMAND ---
27
+ # This correctly points to the 'app' variable inside the 'app/main.py' file
28
+ CMD ["uvicorn", "app.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.
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
- title: Resume Api
3
- emoji: 📉
4
- colorFrom: pink
5
- colorTo: gray
6
  sdk: docker
7
  pinned: false
8
  ---
 
1
  ---
2
+ title: Recommendation Api
3
+ emoji: 🐢
4
+ colorFrom: yellow
5
+ colorTo: blue
6
  sdk: docker
7
  pinned: false
8
  ---
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,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import joblib
2
+ from sentence_transformers import SentenceTransformer
3
+ import os
4
+
5
+ MODEL_DIR = "models"
6
+
7
+ # Initialize variables
8
+ tfidf_vectorizer = None
9
+ le = None
10
+ rf_model = None
11
+ sentence_model = None
12
+
13
+ try:
14
+ tfidf_vectorizer = joblib.load(os.path.join(MODEL_DIR, "tfidf_vectorizer.pkl"))
15
+ le = joblib.load(os.path.join(MODEL_DIR, "label_encoder.pkl"))
16
+ rf_model = joblib.load(os.path.join(MODEL_DIR, "random_forest_model.pkl"))
17
+ print("Classification models loaded.")
18
+
19
+ # Set cache directory to a writable location for Hugging Face Spaces
20
+ os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers_cache'
21
+ os.environ['HF_HOME'] = '/tmp/hf_home'
22
+
23
+ sentence_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
24
+ print("SentenceTransformer model loaded.")
25
+
26
+ except FileNotFoundError as e:
27
+ print(f"MODEL LOADING ERROR: {e}")
28
+ print("Make sure the .pkl files are in the 'models' directory.")
29
+ raise e # Re-raise to prevent the application from starting with None models
30
+
31
+ except Exception as e:
32
+ print(f"An unexpected error occurred during model loading: {e}")
33
+ raise e # Re-raise to prevent the application from starting with None models
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,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
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
+ if not all([tfidf_vectorizer, le, rf_model]):
59
+ raise RuntimeError("Classification models are not properly loaded")
60
+
61
+ print("debug")
62
+ print(profile_text)
63
+
64
+ cleaned_text = clean_resume(profile_text)
65
+ print("cleaned text:")
66
+ print(cleaned_text)
67
+
68
+ cleaned_text = profile_text.lower()
69
+ vectorized_text = tfidf_vectorizer.transform([cleaned_text])
70
+ prediction_encoded = rf_model.predict(vectorized_text)[0]
71
+ category = le.inverse_transform([prediction_encoded])[0]
72
+ return category
73
+
74
+ def get_ranked_internships(request: RecommendationRequest) -> list[int]:
75
+ """Performs two-stage ranking with dynamic geocoding."""
76
+ if not sentence_model:
77
+ raise RuntimeError("SentenceTransformer model is not properly loaded")
78
+
79
+ profile_text_to_encode = request.profile_text
80
+
81
+ if request.predicted_category:
82
+ profile_text_to_encode = f"The user's predicted job category is {request.predicted_category}. Based on that, consider their profile: {request.profile_text}"
83
+
84
+ profile_embedding = sentence_model.encode(profile_text_to_encode)
85
+ internship_texts = [internship.internship_text for internship in request.internships]
86
+
87
+ if not internship_texts:
88
+ return []
89
+
90
+ internship_embeddings = sentence_model.encode(internship_texts)
91
+ cosine_score = sentence_model.similarity(profile_embedding, internship_embeddings)[0].tolist()
92
+
93
+ print("--- FastAPI Debugging ---")
94
+ print(f"Received {len(internship_texts)} internships to rank.")
95
+ print(f"Calculated Cosine Scores: {cosine_score}")
96
+ print("--------------------------")
97
+
98
+ ranked_by_similarity = []
99
+ for i, internship in enumerate(request.internships):
100
+ ranked_by_similarity.append({
101
+ "id": internship.id,
102
+ "similarity_score": cosine_score[i],
103
+ "location": internship.location,
104
+ })
105
+
106
+ final_ranked_list = []
107
+ user_coords = geo_coords(request.preferred_location)
108
+
109
+ print(user_coords, request.preferred_location)
110
+
111
+
112
+ for internship in ranked_by_similarity:
113
+ final_score = internship['similarity_score']
114
+
115
+ if user_coords:
116
+ internship_coords = geo_coords(internship['location'])
117
+ if internship_coords:
118
+ distance_km = geodesic(user_coords, internship_coords).kilometers
119
+ if distance_km < 1:
120
+ final_score += 2.0
121
+ elif distance_km < 150:
122
+ final_score += 0.75
123
+
124
+ internship['final_score'] = final_score
125
+ final_ranked_list.append(internship)
126
+
127
+ final_ranked_list.sort(key=lambda x: x['final_score'], reverse=True)
128
+
129
+ final_ids = [item['id'] for item in final_ranked_list]
130
+
131
+ print(final_ranked_list)
132
+
133
+ 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
models/label_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c377bc01a653194d445516d47c2fc95ac8410597f3683896b90c051baebb1438
3
+ size 1349
models/random_forest_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ab4744a3f61d4be4361306201fc305dd7e447506038fc77adb8188e54e26c1c
3
+ size 561063985
models/tfidf_vectorizer.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d3c38128124178e73664852254c0ddfeb12e2803c559d8d93b87b045a21f515
3
+ size 2485163
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core FastAPI Framework
2
+ fastapi
3
+ uvicorn
4
+
5
+ # Machine Learning & Data - Pin scikit-learn version to match your models
6
+ scikit-learn==1.5.1
7
+ joblib
8
+ sentence-transformers
9
+ torch
10
+ geopy
11
+
12
+ # Pydantic is a dependency of FastAPI, but we list it for clarity
13
+ pydantic
14
+
15
+ # Good practice for managing environment variables
16
+ 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
+ }