Andra Pratama commited on
Commit
ff8f346
·
1 Parent(s): decca90

UPDATE: classfication inference and fastapi web

Browse files
2-model-development/notebooks/classification.ipynb CHANGED
@@ -1,11 +1,9 @@
1
  {
2
  "cells": [
3
  {
4
- "cell_type": "code",
5
- "execution_count": null,
6
- "id": "747b3a43",
7
  "metadata": {},
8
- "outputs": [],
9
  "source": [
10
  "# Classification Model\n",
11
  "Program ini akan membuat model klasifikasi yang dapat memprediksi gaya belajar siswa (fast learner, consistent learner, dan reflective learner). Model klasifikasi akan berfokus pada Decision Tree Algorithm."
@@ -2528,10 +2526,18 @@
2528
  },
2529
  {
2530
  "cell_type": "code",
2531
- "execution_count": 4,
2532
  "id": "e921578b",
2533
  "metadata": {},
2534
- "outputs": [],
 
 
 
 
 
 
 
 
2535
  "source": [
2536
  "import joblib\n",
2537
  "import pandas as pd\n",
 
1
  {
2
  "cells": [
3
  {
4
+ "cell_type": "markdown",
5
+ "id": "cc48b0c6",
 
6
  "metadata": {},
 
7
  "source": [
8
  "# Classification Model\n",
9
  "Program ini akan membuat model klasifikasi yang dapat memprediksi gaya belajar siswa (fast learner, consistent learner, dan reflective learner). Model klasifikasi akan berfokus pada Decision Tree Algorithm."
 
2526
  },
2527
  {
2528
  "cell_type": "code",
2529
+ "execution_count": 1,
2530
  "id": "e921578b",
2531
  "metadata": {},
2532
+ "outputs": [
2533
+ {
2534
+ "name": "stdout",
2535
+ "output_type": "stream",
2536
+ "text": [
2537
+ "['Tryhard']\n"
2538
+ ]
2539
+ }
2540
+ ],
2541
  "source": [
2542
  "import joblib\n",
2543
  "import pandas as pd\n",
3-model-delivery/__pycache__/main.cpython-312.pyc ADDED
Binary file (2.98 kB). View file
 
3-model-delivery/app.py DELETED
@@ -1,123 +0,0 @@
1
- from flask import Flask, request, jsonify
2
- from flask_cors import CORS
3
- import google.generativeai as genai
4
- import joblib
5
- import pandas as pd
6
- import os
7
-
8
- # Konfigurasi Gemini API
9
- API_KEY = "PASTE_GEMINI_API_KEY_HERE" # Ganti dengan API Key kita
10
-
11
- genai.configure(api_key=API_KEY)
12
-
13
- # Pilih model yang digunakan
14
- # model yang digunakan bisa diganti sesuai kebutuhan
15
- model_gemini = genai.GenerativeModel('gemini-2.5-flash')
16
-
17
- # Load model klasifikasi ML
18
- MODEL_PATH = 'model_klasifikasi_gaya_belajar.joblib'
19
- print(f"[INFO] Sedang memuat model dari: {MODEL_PATH} ...")
20
-
21
- loaded_model = None
22
-
23
- # Cek apakah file model ada sebelum di-load
24
- if os.path.exists(MODEL_PATH):
25
- try:
26
- loaded_model = joblib.load(MODEL_PATH)
27
- print("✅ Model berhasil dimuat!")
28
- except Exception as e:
29
- print(f"❌ Error saat load model: {e}")
30
- else:
31
- print("⚠️ PERINGATAN: File model tidak ditemukan. Pastikan nama file benar.")
32
-
33
- # Setup Flask App
34
- app = Flask(__name__)
35
- CORS(app) # Mengizinkan akses dari Frontend (React)
36
-
37
- # Fungsi 1: Prediksi Label Gaya Belajar (klasifikasi ML)
38
- def predict_label(features):
39
- if loaded_model is None:
40
- return "Model Error"
41
-
42
- # DataFrame sesuai format input model saat training
43
- df = pd.DataFrame([{
44
- 'weekly_completed_modules': features['weekly_completed_modules'],
45
- 'weekly_active_days': features['weekly_active_days'],
46
- 'weekly_submission_count': features['weekly_submission_count'],
47
- 'weekly_avg_exam_score': features['weekly_avg_exam_score']
48
- }])
49
-
50
- try:
51
- prediction = loaded_model.predict(df)
52
- return prediction[0] # Mengambil hasil label pertama
53
- except Exception as e:
54
- print(f"Error pada prediksi ML: {e}")
55
- return "Error Prediksi"
56
-
57
- # Fungsi 2: Generate Insight Pembelajaran (Gemini API)
58
- def generate_learning_insight(user_features, predicted_label):
59
-
60
- # Prompt yang akan dikirim ke Gemini
61
- prompt = f"""
62
- Bertindaklah sebagai "Learning Coach" untuk platform belajar coding.
63
-
64
- Data Siswa:
65
- - Gaya Belajar: {predicted_label}
66
- - Modul Selesai: {user_features.get('weekly_completed_modules')}
67
- - Hari Aktif: {user_features.get('weekly_active_days')}
68
- - Rata-rata Skor: {user_features.get('weekly_avg_exam_score')}
69
-
70
- Instruksi Utama:
71
- Buatlah SATU paragraf pendek (maksimal 3-4 kalimat) yang berisi apresiasi, alasan mendapatkan label {predicted_label}, dan saran belajar singkat.
72
-
73
- Aturan Format (PENTING):
74
- 1. Output harus PLAIN TEXT murni.
75
- 2. DILARANG KERAS menggunakan format markdown seperti bold (**teks**), italic, atau bullet points.
76
- 3. Jangan gunakan tanda bintang (*) sama sekali.
77
- 4. Gunakan emoji secukupnya agar terkesan ramah (seperti Duolingo).
78
- 5. Gaya bahasa: Santai, suportif, dan mengalir.
79
- 6. Jangan sebut saya sebagai AI atau model bahasa.
80
-
81
- Contoh Output yang BENAR:
82
- "Wih, performamu minggu ini luar biasa banget! 🚀 Kamu layak disebut Speedrunner karena berhasil melahap 10 modul dalam seminggu dengan skor rata-rata 95 yang nyaris sempurna. Coba deh tantang dirimu bikin mini project dari materi tadi biar ilmunya makin nempel, semangat terus ya! 🔥"
83
- """
84
-
85
- try:
86
- response = model_gemini.generate_content(prompt)
87
- return response.text.strip()
88
- except Exception as e:
89
- print(f"Error pada Gemini API: {e}")
90
- # Fallback response jika API bermasalah
91
- return f"Halo {predicted_label}! Pertahankan performa belajarmu ya. 🚀"
92
-
93
- # Endpoint API
94
- @app.route('/api/analyze-student', methods=['POST'])
95
- def analyze():
96
- # 1. Terima data JSON dari request
97
- data = request.json
98
-
99
- # Gunakan .get() untuk menghindari error jika data kosong (default 0)
100
- features = {
101
- 'weekly_completed_modules': data.get('weekly_completed_modules', 0),
102
- 'weekly_active_days': data.get('weekly_active_days', 0),
103
- 'weekly_submission_count': data.get('weekly_submission_count', 0),
104
- 'weekly_avg_exam_score': data.get('weekly_avg_exam_score', 0)
105
- }
106
-
107
- # 2. Proses Prediksi ML
108
- pred_label = predict_label(features)
109
-
110
- # 3. Generate Insight AI
111
- insight = generate_learning_insight(features, pred_label)
112
-
113
- # 4. Return response JSON
114
- return jsonify({
115
- "status": "success",
116
- "prediction": pred_label,
117
- "ai_insight": insight,
118
- "features_received": features
119
- })
120
-
121
- if __name__ == '__main__':
122
- print("🚀 Server Flask berjalan di port 5000...")
123
- app.run(debug=True, port=5000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3-model-delivery/main.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import google.generativeai as genai
5
+ import joblib
6
+ import pandas as pd
7
+ import os
8
+
9
+ API_KEY = "AIzaSyD1USyNFVhLM8tpyAZr47C757B_UWZNuOk"
10
+ genai.configure(api_key=API_KEY)
11
+ model_gemini = genai.GenerativeModel("gemini-2.5-flash")
12
+
13
+ MODEL_PATH = 'model_klasifikasi_gaya_belajar.joblib'
14
+ loaded_model = joblib.load(MODEL_PATH) if os.path.exists(MODEL_PATH) else None
15
+
16
+ app = FastAPI()
17
+
18
+ app.add_middleware(
19
+ CORSMiddleware,
20
+ allow_origins=["*"],
21
+ allow_credentials=True,
22
+ allow_methods=["*"],
23
+ allow_headers=["*"],
24
+ )
25
+
26
+ class StudentFeatures(BaseModel):
27
+ weekly_completed_modules: int
28
+ weekly_active_days: int
29
+ weekly_submission_count: int
30
+ weekly_avg_exam_score: float
31
+
32
+ def predict_label(features):
33
+ df = pd.DataFrame([features.dict()])
34
+ return loaded_model.predict(df)[0] if loaded_model else "Model Error"
35
+
36
+ def generate_learning_insight(features, predicted_label):
37
+ prompt = f"""
38
+ Bertindaklah sebagai Learning Coach.
39
+
40
+ Gaya Belajar: {predicted_label}
41
+ Modul Selesai: {features.weekly_completed_modules}
42
+ Hari Aktif: {features.weekly_active_days}
43
+ Rata-rata Skor: {features.weekly_avg_exam_score}
44
+
45
+ Buat paragraf singkat tanpa markdown, tanpa simbol bintang, bahasa santai dan emotikon.
46
+ """
47
+ res = model_gemini.generate_content(prompt)
48
+ return res.text.strip()
49
+
50
+ @app.post("/api/analyze-student")
51
+ def analyze(features: StudentFeatures):
52
+ label = predict_label(features)
53
+ insight = generate_learning_insight(features, label)
54
+ return {
55
+ "status": "success",
56
+ "prediction": label,
57
+ "ai_insight": insight,
58
+ "features_received": features.dict()
59
+ }
3-model-delivery/model_klasifikasi_gaya_belajar.joblib CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:855bde45aa224f5791f6d346a5a94998474d6295f3d7e76f8df677c99bebb9af
3
- size 5865
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aab8d3f1688f29abc56136cbce952f7909c7dacba749f68fedc1814191454af7
3
+ size 5737