File size: 7,179 Bytes
8588baa
 
0c6bfe8
52f9bc6
 
 
 
 
8588baa
 
 
52f9bc6
 
0c6bfe8
e1963a4
e8dfeec
52f9bc6
8588baa
 
 
52f9bc6
 
0c6bfe8
52f9bc6
 
 
 
 
 
 
 
 
 
 
 
 
0c6bfe8
8588baa
52f9bc6
 
 
 
 
0c6bfe8
52f9bc6
 
 
 
 
 
 
 
 
0c6bfe8
52f9bc6
 
 
 
0c6bfe8
52f9bc6
0c6bfe8
 
 
 
 
 
 
 
bf84b00
0c6bfe8
52f9bc6
 
 
 
 
 
 
 
 
 
 
 
0c6bfe8
 
 
52f9bc6
 
 
0c6bfe8
 
 
 
 
 
 
 
52f9bc6
 
bf84b00
52f9bc6
bf84b00
52f9bc6
 
 
 
bf84b00
52f9bc6
 
 
 
 
 
bf84b00
 
52f9bc6
 
 
 
 
 
0c6bfe8
52f9bc6
 
 
 
0c6bfe8
 
 
52f9bc6
 
8df4e5c
52f9bc6
0c6bfe8
52f9bc6
 
fece0eb
5d815dc
 
 
0c6bfe8
52f9bc6
 
bf84b00
52f9bc6
 
 
 
bf84b00
0c6bfe8
52f9bc6
 
 
0c6bfe8
 
e8dfeec
bf84b00
0c6bfe8
bf84b00
52f9bc6
0c6bfe8
8588baa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import logging
import traceback
from flask import Flask, render_template, request, jsonify
import pandas as pd
import json
from joblib import load
import mysql.connector
from mysql.connector import Error

# =[Modules dan Packages]========================
from c45 import c45  # Ensure this is correctly imported and available

# =[Variabel Global]=============================
app = Flask(__name__, static_url_path='/static')
model = None
model = load('/code/model_scratch_2.model')

# Setup logging
logging.basicConfig(level=logging.DEBUG)

# =[Routing]=====================================

# [Routing untuk Halaman Utama atau Home]
@app.route("/")
def beranda():
    return render_template('index.html')

# [Routing untuk API]
@app.route("/deteksi", methods=['GET', 'POST'])
def apiDeteksi():
    if request.method == 'POST':
        try:
            # Extract form data
            nama = request.form['Nama']
            posisi_harapan = request.form['Posisi_Harapan']
            usia = int(request.form['Usia'])

            # Extract kategori umur as an object
            kategori_umur_obj = request.form.get('KategoriUmur')
            if kategori_umur_obj is not None:
                kategori_umur_values = json.loads(kategori_umur_obj)
            else:
                kategori_umur_values = {}

            kategori_umur_values = {f"KategoriUmur[{i}]": int(request.form.get(f"KategoriUmur[{i}]")) for i in range(1, 11)}
            kategori_umur_dict = {f"Kategori_Umur_{i}": kategori_umur_values.get(f"KategoriUmur[{i}]", 0) for i in range(1, 11)}

            pendidikan = int(request.form['Pendidikan'])
            lama_pengalaman = int(request.form['Lama_Pengalaman'])
            kesesuaian_posisi_dg_skills = int(request.form['Kesesuaian_Posisi_Skill'])
            kesesuaian_posisi_dg_pengalaman = int(request.form['Kesesuaian_Posisi_Pengalaman'])

            # Perform prediction
            data = {**kategori_umur_dict,
                    "Pendidikan": pendidikan,
                    "Lama_Pengalaman": lama_pengalaman,
                    "Kesesuaian_Posisi_Skill": kesesuaian_posisi_dg_skills,
                    "Kesesuaian_Posisi_Pengalaman": kesesuaian_posisi_dg_pengalaman}

            df_test = pd.DataFrame(data, index=[0])

            # Check if model is loaded
            if model is None:
                raise Exception("Model not loaded")

            # Perform prediction
            hasil_prediksi = model.predict(df_test)[0]

            # Log prediction result
            logging.debug(f"Prediction result: {hasil_prediksi}")

            # Map prediction to a string
            if hasil_prediksi == 1:
                hasil_prediksi_str = 'Recommended Candidate'
            elif hasil_prediksi == 0:
                hasil_prediksi_str = 'Not Recommended Candidate'
            else:
                hasil_prediksi_str = 'Data Tidak Sesuai Dengan Format'

            # Save data to the database
            try:
                connection = mysql.connector.connect(host='sql12.freesqldatabase.com',
                                                     database='sql12711336',
                                                     user='sql12711336',
                                                     password='ufDVxditnx')
                if connection.is_connected():
                    cursor = connection.cursor(prepared=True)
                    insert_query = ("INSERT INTO klasifikasi "
                                    "(nama, kategori_umur_1, kategori_umur_2, "
                                    "kategori_umur_3, kategori_umur_4, kategori_umur_5, kategori_umur_6, "
                                    "kategori_umur_7, kategori_umur_8, kategori_umur_9, kategori_umur_10, pendidikan, lama_pengalaman, "
                                    "kesesuaian_posisi_dg_skills, kesesuaian_posisi_dg_pengalaman, "
                                    "posisi_harapan, usia, hasil_prediksi) "
                                    "VALUES "
                                    "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")

                    cursor.execute(insert_query, (nama,) + tuple(data.values()) + (posisi_harapan, usia, hasil_prediksi_str))
                    connection.commit()
                    logging.debug("Data berhasil disimpan ke database.")
            except Error as e:
                logging.error(f"Error while connecting to MySQL: {e}")
            finally:
                if connection.is_connected():
                    cursor.close()
                    connection.close()
                    logging.debug("MySQL connection is closed")

            # Return prediction result as JSON
            return jsonify({
                "prediksi": hasil_prediksi_str
            })
        except Exception as e:
            logging.error(f"Error during prediction: {e}")
            logging.error(traceback.format_exc())
            return jsonify({
                "error": "Error during prediction"
            })

    # If the request is not POST, render the prediksi.html page
    return render_template('prediksi.html')

@app.route("/view_tabel", methods=['GET'])
def view_tabel():
    try:
        connection = mysql.connector.connect(host='sql12.freesqldatabase.com',
                                             database='sql12711336',
                                             user='sql12711336',
                                             password='ufDVxditnx')
        if connection.is_connected():
            cursor = connection.cursor(dictionary=True)
            cursor.execute("SELECT * FROM klasifikasi ORDER BY no ASC")
            data_tabel = cursor.fetchall()

            # Konversi nilai pendidikan, lama_pengalaman, kesesuaian_posisi_dg_skills, dan kesesuaian_posisi_dg_pengalaman
            for row in data_tabel:
                row['pendidikan'] = ">= S1" if row['pendidikan'] == "1" else "<S1"
                row['lama_pengalaman'] = ">=1 Tahun" if row['lama_pengalaman'] == "1" else "<1 Tahun"
                row['kesesuaian_posisi_dg_skills'] = "Skills Sesuai Posisi Harapan" if row['kesesuaian_posisi_dg_skills'] == "1" else "Skills Tidak Sesuai Posisi Harapan"
                row['kesesuaian_posisi_dg_pengalaman'] = "Pengalaman Sesuai Posisi Harapan" if row['kesesuaian_posisi_dg_pengalaman'] == "1" else "Pengalaman Tidak Sesuai Posisi Harapan"

            return render_template('view_tabel.html', data_tabel=data_tabel)
    except Error as e:
        logging.error(f"Error while connecting to MySQL: {e}")
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            logging.debug("MySQL connection is closed")

# =[Main]========================================

if __name__ == '__main__':
    # Load model yang telah ditraining
    try:
        model = load('/code/model_scratch_2.model')
        logging.debug("Model loaded successfully")
    except Exception as e:
        logging.error(f"Error loading model: {e}")

    # Run Flask di localhost
    app.run(host="0.0.0.0", port=5000, debug=True)  # Make sure to allow connections from outside if needed