tututz commited on
Commit
c431ca4
·
verified ·
1 Parent(s): 9b24124

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +40 -30
main.py CHANGED
@@ -1,5 +1,5 @@
1
  # ======================================================================
2
- # --- main.py (Modular, dengan builder eksternal) ---
3
  # ======================================================================
4
 
5
  import os
@@ -11,9 +11,8 @@ from fastapi import FastAPI, HTTPException
11
  from pydantic import BaseModel
12
  from typing import List, Dict, Any
13
 
14
-
15
  from .explanation_builder import build_explanation_from_rules
16
- # ---------------------
17
 
18
 
19
  # ======================================================================
@@ -22,14 +21,13 @@ from .explanation_builder import build_explanation_from_rules
22
  app = FastAPI(
23
  title="GCOMPRO",
24
  description="API Prediksi Risiko Akademik dan Rekomendasi Mata Kuliah.",
25
- version="1.4.0" # Versi dinaikkan untuk modularisasi
26
  )
27
 
28
  # ======================================================================
29
  # 2. Struktur Data Input/Output (Pydantic)
30
  # ======================================================================
31
 
32
-
33
  # --- Model untuk API Prediksi Risiko (App 1) ---
34
  class StudentFeatures(BaseModel):
35
  IPK_Terakhir: float
@@ -45,6 +43,19 @@ class StudentFeatures(BaseModel):
45
  IPK_Ternormalisasi_SKS: float
46
  Profil_Tren: str
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  # --- Model untuk API Rekomendasi MK (App 2) ---
49
  class RecommendationRequest(BaseModel):
50
  current_semester: int
@@ -84,7 +95,7 @@ course_details_map = {}
84
  prereq_map = {}
85
  out_degree_map = {}
86
 
87
-
88
 
89
  def load_ml_model():
90
  """Memuat model ML dari file .skops"""
@@ -148,7 +159,6 @@ def on_startup():
148
  # 4. Helper Function (Untuk API Rekomendasi)
149
  # ======================================================================
150
 
151
-
152
  def get_recommendations_logic(current_semester: int, courses_passed_list: List[str]) -> List[Dict[str, Any]]:
153
  """Inti dari logika rekomendasi, HANYA dengan validasi prereq."""
154
  passed_set = set(courses_passed_list)
@@ -186,17 +196,15 @@ def get_recommendations_logic(current_semester: int, courses_passed_list: List[s
186
  # 5. Endpoints API
187
  # ======================================================================
188
 
189
-
190
-
191
  @app.get("/")
192
  def read_root():
193
  return {
194
- "message": "Selamat Datang di API Layanan Akademik Mahasiswa (GCOMPRO)",
195
  "status": "ready",
196
  "endpoints": ["/predict/", "/recommend/"]
197
  }
198
 
199
- @app.post("/predict/")
200
  def predict_risk(student_data: StudentFeatures):
201
  if ml_model is None:
202
  raise HTTPException(status_code=503, detail="Model ML belum siap. Silakan coba lagi nanti.")
@@ -213,7 +221,7 @@ def predict_risk(student_data: StudentFeatures):
213
  classes = ml_model.classes_
214
  probabilities = dict(zip(classes, prediction_proba[0]))
215
 
216
- explanation_str = ""
217
 
218
  if hasattr(ml_model, 'tree_'):
219
  try:
@@ -223,22 +231,16 @@ def predict_risk(student_data: StudentFeatures):
223
  path = ml_model.decision_path(input_encoded)
224
  node_indices = path.indices[path.indptr[0]:path.indptr[1]]
225
 
226
- structured_rules = []
227
 
228
  for node_id in node_indices[:-1]:
229
  feature_index = tree.feature[node_id]
230
  feature_name = feature_names[feature_index]
231
  threshold = tree.threshold[node_id]
232
-
233
  sample_value = input_encoded.iloc[0, feature_index]
234
 
235
- condition_str = ""
236
- if sample_value <= threshold:
237
- condition_str = "rendah" # (<=)
238
- else:
239
- condition_str = "tinggi" # (>)
240
 
241
- # Simpan aturan dalam format terstruktur
242
  structured_rules.append({
243
  "feature": feature_name,
244
  "condition": condition_str,
@@ -246,20 +248,27 @@ def predict_risk(student_data: StudentFeatures):
246
  "value": sample_value
247
  })
248
 
249
- # Panggil fungsi builder yang sudah di-impor
250
- explanation_str = build_explanation_from_rules(structured_rules, prediction_val)
251
- # ---------------------
252
 
253
  except Exception as e:
254
- explanation_str = f"Gagal membuat penjelasan: {str(e)}"
 
 
 
255
  else:
256
- explanation_str = "Penjelasan (decision path) tidak tersedia untuk tipe model ini."
 
 
 
 
 
 
 
 
 
 
257
 
258
- return {
259
- "prediction": prediction_val,
260
- "probabilities": probabilities,
261
- "explanation": explanation_str
262
- }
263
  except Exception as e:
264
  raise HTTPException(status_code=500, detail=f"Terjadi kesalahan saat prediksi: {e}")
265
 
@@ -311,3 +320,4 @@ async def recommend_courses(request: RecommendationRequest):
311
  )
312
 
313
  return response_output
 
 
1
  # ======================================================================
2
+ # --- main.py (Modular, dengan builder eksternal & format respons baru) ---
3
  # ======================================================================
4
 
5
  import os
 
11
  from pydantic import BaseModel
12
  from typing import List, Dict, Any
13
 
14
+ # Impor fungsi builder dari file baru
15
  from .explanation_builder import build_explanation_from_rules
 
16
 
17
 
18
  # ======================================================================
 
21
  app = FastAPI(
22
  title="GCOMPRO",
23
  description="API Prediksi Risiko Akademik dan Rekomendasi Mata Kuliah.",
24
+ version="1.5.0"
25
  )
26
 
27
  # ======================================================================
28
  # 2. Struktur Data Input/Output (Pydantic)
29
  # ======================================================================
30
 
 
31
  # --- Model untuk API Prediksi Risiko (App 1) ---
32
  class StudentFeatures(BaseModel):
33
  IPK_Terakhir: float
 
43
  IPK_Ternormalisasi_SKS: float
44
  Profil_Tren: str
45
 
46
+ class PredictionExplanation(BaseModel):
47
+ """ Model Pydantic untuk struktur penjelasan baru """
48
+ opening_line: str
49
+ factors: List[str]
50
+
51
+ class PredictionResponse(BaseModel):
52
+ """ Model Pydantic untuk seluruh respons /predict/ """
53
+ prediction: str
54
+ probabilities: Dict[str, float]
55
+ explanation: PredictionExplanation
56
+ # --------------------------------------------------------
57
+
58
+
59
  # --- Model untuk API Rekomendasi MK (App 2) ---
60
  class RecommendationRequest(BaseModel):
61
  current_semester: int
 
95
  prereq_map = {}
96
  out_degree_map = {}
97
 
98
+ # --- Fungsi Pemuatan (dipanggil saat startup) ---
99
 
100
  def load_ml_model():
101
  """Memuat model ML dari file .skops"""
 
159
  # 4. Helper Function (Untuk API Rekomendasi)
160
  # ======================================================================
161
 
 
162
  def get_recommendations_logic(current_semester: int, courses_passed_list: List[str]) -> List[Dict[str, Any]]:
163
  """Inti dari logika rekomendasi, HANYA dengan validasi prereq."""
164
  passed_set = set(courses_passed_list)
 
196
  # 5. Endpoints API
197
  # ======================================================================
198
 
 
 
199
  @app.get("/")
200
  def read_root():
201
  return {
202
+ "message": "Selamat Datang di API Layanan Akademik Mahasiswa",
203
  "status": "ready",
204
  "endpoints": ["/predict/", "/recommend/"]
205
  }
206
 
207
+ @app.post("/predict/", response_model=PredictionResponse)
208
  def predict_risk(student_data: StudentFeatures):
209
  if ml_model is None:
210
  raise HTTPException(status_code=503, detail="Model ML belum siap. Silakan coba lagi nanti.")
 
221
  classes = ml_model.classes_
222
  probabilities = dict(zip(classes, prediction_proba[0]))
223
 
224
+ explanation_obj = {} # Ganti nama dari explanation_str
225
 
226
  if hasattr(ml_model, 'tree_'):
227
  try:
 
231
  path = ml_model.decision_path(input_encoded)
232
  node_indices = path.indices[path.indptr[0]:path.indptr[1]]
233
 
234
+ structured_rules = []
235
 
236
  for node_id in node_indices[:-1]:
237
  feature_index = tree.feature[node_id]
238
  feature_name = feature_names[feature_index]
239
  threshold = tree.threshold[node_id]
 
240
  sample_value = input_encoded.iloc[0, feature_index]
241
 
242
+ condition_str = "rendah" if sample_value <= threshold else "tinggi"
 
 
 
 
243
 
 
244
  structured_rules.append({
245
  "feature": feature_name,
246
  "condition": condition_str,
 
248
  "value": sample_value
249
  })
250
 
251
+ # Panggil builder, yang sekarang mengembalikan DICT
252
+ explanation_obj = build_explanation_from_rules(structured_rules, prediction_val)
 
253
 
254
  except Exception as e:
255
+ explanation_obj = {
256
+ "opening_line": f"Gagal membuat penjelasan: {str(e)}",
257
+ "factors": []
258
+ }
259
  else:
260
+ explanation_obj = {
261
+ "opening_line": "Penjelasan (decision path) tidak tersedia untuk tipe model ini.",
262
+ "factors": []
263
+ }
264
+
265
+ # Kembalikan objek Pydantic yang sudah divalidasi
266
+ return PredictionResponse(
267
+ prediction=prediction_val,
268
+ probabilities=probabilities,
269
+ explanation=explanation_obj
270
+ )
271
 
 
 
 
 
 
272
  except Exception as e:
273
  raise HTTPException(status_code=500, detail=f"Terjadi kesalahan saat prediksi: {e}")
274
 
 
320
  )
321
 
322
  return response_output
323
+