fix: memperbaiki api predik tomat, riwayat dan setting dan riwayat

This commit is contained in:
muhamad fais aizat 2025-05-02 02:21:47 +07:00
parent 6e918b9615
commit 49e302455b
8 changed files with 307 additions and 65 deletions

View File

@ -85,14 +85,25 @@ def predict_price(db: Session = Depends(get_db)):
coef0 = float(settings.nilai_coef) if settings.nilai_coef is not None else 0.0 coef0 = float(settings.nilai_coef) if settings.nilai_coef is not None else 0.0
# Inisialisasi Model SVR # Inisialisasi Model SVR
# if kernel == "linear":
# svr = SVR(kernel=kernel, C=C, epsilon=epsilon)
# else:
# svr = SVR(kernel=kernel, C=C, gamma=gamma, epsilon=epsilon)
# if kernel in ["poly", "sigmoid"]:
# svr.coef0 = coef0
# if kernel == "poly":
# svr.degree = degree
if kernel == "linear": if kernel == "linear":
svr = SVR(kernel=kernel, C=C, epsilon=epsilon) svr = SVR(kernel="linear", C=C, epsilon=epsilon)
else:
svr = SVR(kernel=kernel, C=C, gamma=gamma, epsilon=epsilon) elif kernel == "rbf":
if kernel in ["poly", "sigmoid"]: svr = SVR(kernel="rbf", C=C, gamma=gamma, epsilon=epsilon)
svr.coef0 = coef0
if kernel == "poly": elif kernel == "sigmoid":
svr.degree = degree svr = SVR(kernel="sigmoid", C=C, gamma=gamma, coef0=coef0, epsilon=epsilon)
elif kernel == "poly":
svr = SVR(kernel="poly", C=C, gamma=gamma, coef0=coef0, degree=degree, epsilon=epsilon)
# **Melakukan Prediksi Rolling Window** # **Melakukan Prediksi Rolling Window**
hasil_prediksi = [] hasil_prediksi = []
@ -215,16 +226,28 @@ def get_price_history(
# 8. Latih Model SVR dengan Kernel Linear # 8. Latih Model SVR dengan Kernel Linear
# Inisialisasi Model SVR # Inisialisasi Model SVR
if kernel == "linear": # if kernel == "linear":
svr = SVR(kernel=kernel, C=C, epsilon=epsilon) # svr = SVR(kernel=kernel, C=C, epsilon=epsilon)
else: # else:
svr = SVR(kernel=kernel, C=C, gamma=gamma, epsilon=epsilon) # svr = SVR(kernel=kernel, C=C, gamma=gamma, epsilon=epsilon)
if kernel in ["poly", "sigmoid"]: # if kernel in ["poly", "sigmoid"]:
svr.coef0 = coef0 # svr.coef0 = coef0
if kernel == "poly": # if kernel == "poly":
svr.degree = degree # svr.degree = degree
# svr = SVR(kernel='linear', C=1.0, epsilon=0.01) # svr = SVR(kernel='linear', C=1.0, epsilon=0.01)
# svr = SVR(kernel='rbf', C=1.0, epsilon=0.01, gamma='scale') # svr = SVR(kernel='rbf', C=1.0, epsilon=0.01, gamma='scale')
if kernel == "linear":
svr = SVR(kernel="linear", C=C, epsilon=epsilon)
elif kernel == "rbf":
svr = SVR(kernel="rbf", C=C, gamma=gamma, epsilon=epsilon)
elif kernel == "sigmoid":
svr = SVR(kernel="sigmoid", C=C, gamma=gamma, coef0=coef0, epsilon=epsilon)
elif kernel == "poly":
svr = SVR(kernel="poly", C=C, gamma=gamma, coef0=coef0, degree=degree, epsilon=epsilon)
svr.fit(X_train, y_train) svr.fit(X_train, y_train)
# 9. Lakukan Prediksi pada Data Uji # 9. Lakukan Prediksi pada Data Uji

View File

@ -20,7 +20,7 @@ async def get_all_riwayat(db: Session = Depends(get_db)):
try: try:
query = select(riwayatPengujian, settingPredict.c.nama_kernel).join( query = select(riwayatPengujian, settingPredict.c.nama_kernel).join(
settingPredict, riwayatPengujian.c.id_kernel == settingPredict.c.id settingPredict, riwayatPengujian.c.id_kernel == settingPredict.c.id
) ).order_by(riwayatPengujian.c.id.desc())
result = db.execute(query).fetchall() result = db.execute(query).fetchall()
return [dict(row._mapping) for row in result] return [dict(row._mapping) for row in result]
except SQLAlchemyError as e: except SQLAlchemyError as e:

View File

@ -59,7 +59,7 @@ ALLOWED_FIELDS = {
"rbf": ["nilai_c", "nilai_gamma", "nilai_epsilon", "status"] "rbf": ["nilai_c", "nilai_gamma", "nilai_epsilon", "status"]
} }
# ✅ Update Setting by ID tanpa request body (Menggunakan Parameter)
@settingPredict_router.put("/{setting_id}",dependencies=[Depends(verify_token)]) @settingPredict_router.put("/{setting_id}",dependencies=[Depends(verify_token)])
async def update_setting( async def update_setting(
setting_id: int, setting_id: int,
@ -68,7 +68,7 @@ async def update_setting(
nilai_epsilon: str = Query(None), nilai_epsilon: str = Query(None),
nilai_degree: str = Query(None), nilai_degree: str = Query(None),
nilai_coef: str = Query(None), nilai_coef: str = Query(None),
status: bool = Query(None)
): ):
# Cek apakah setting dengan ID tersebut ada # Cek apakah setting dengan ID tersebut ada
query = select(settingPredict.c.nama_kernel).where(settingPredict.c.id == setting_id) query = select(settingPredict.c.nama_kernel).where(settingPredict.c.id == setting_id)
@ -87,7 +87,7 @@ async def update_setting(
"nilai_epsilon": nilai_epsilon, "nilai_epsilon": nilai_epsilon,
"nilai_degree": nilai_degree, "nilai_degree": nilai_degree,
"nilai_coef": nilai_coef, "nilai_coef": nilai_coef,
"status": status
} }
# Filter hanya field yang diperbolehkan untuk kernel tersebut # Filter hanya field yang diperbolehkan untuk kernel tersebut
@ -105,3 +105,25 @@ async def update_setting(
conn.commit() conn.commit()
return {"message": "Setting updated successfully", "updated_fields": update_data} return {"message": "Setting updated successfully", "updated_fields": update_data}
@settingPredict_router.put("/update-status/{setting_id}", dependencies=[Depends(verify_token)])
async def update_status_setting(
setting_id: int,
status: bool = Query(...)
):
# Cek apakah setting dengan ID tersebut ada
query = select(settingPredict.c.id).where(settingPredict.c.id == setting_id)
result = conn.execute(query).fetchone()
if not result:
raise HTTPException(status_code=404, detail="Setting not found")
# Update hanya status
query = update(settingPredict).where(settingPredict.c.id == setting_id).values(status=status)
result = conn.execute(query)
if result.rowcount == 0:
raise HTTPException(status_code=400, detail="Failed to update status")
conn.commit()
return {"message": "Status updated successfully", "updated_status": status}

View File

@ -1,4 +1,4 @@
import React,{useState, useEffect} from 'react' import React, { useState, useEffect } from 'react'
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label"
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@ -8,11 +8,51 @@ import { API_URL } from "../../../helpers/networt";
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
const Setting = () => { const Setting = () => {
const { toast } = useToast(); const { toast } = useToast();
const getemail = localStorage.getItem("email"); const getemail = localStorage.getItem("email");
const idUser = localStorage.getItem("idUser"); const idUser = localStorage.getItem("idUser");
const [email, setEmail] = useState(getemail); const [email, setEmail] = useState(getemail);
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [selectedKernel, setSelectedKernel] = useState("");
const [selectedKernelfalse, setSelectedKernelfalse] = useState("");
const [nilaiC, setNilaiC] = useState("");
const [epsilon, setEpsilon] = useState("");
const [gamma, setGamma] = useState("");
const [degree, setDegree] = useState("");
const [coef0, setCoef0] = useState("");
const fetchDataKernel = async () => {
const token = localStorage.getItem("token");
try {
const response = await axios.get(`${API_URL}/setpredict/`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
console.log(response.data)
if (response.data.length > 0) {
setSelectedKernel(response.data[0].id)
setSelectedKernelfalse(response.data[0].id)
setNilaiC(response.data[0].nilai_c)
setEpsilon(response.data[0].nilai_epsilon)
setGamma(response.data[0].nilai_gamma)
setDegree(response.data[0].nilai_degree)
setCoef0(response.data[0].nilai_coef)
}
// setDataHarga(response.data)
} catch (error) {
console.error("Error fetching data", error);
}
}
useEffect(() => {
fetchDataKernel();
}, []);
const handleCheckboxChange = (kernel) => {
setSelectedKernel(kernel === selectedKernel ? "" : kernel);
};
const handleSaveData = async () => { const handleSaveData = async () => {
@ -21,28 +61,123 @@ const Setting = () => {
const response = await axios.put( const response = await axios.put(
`${API_URL}/auth/forgot-password`, `${API_URL}/auth/forgot-password`,
{ {
email: email, email: email,
new_password: password new_password: password
}, },
{ {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Accept: "application/json", Accept: "application/json",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
} }
); );
toast({ toast({
description: "Pengaturan akun berhasil disimpan", description: "Pengaturan akun berhasil disimpan",
}); });
} catch (error) { } catch (error) {
// console.log(error.response.data.detail) // console.log(error.response.data.detail)
toast({ toast({
description: `${error.response.data.detail}`, description: `${error.response.data.detail}`,
variant: "destructive", variant: "destructive",
}); });
}
}
const handleSaveDataKernel = async () => {
const token = localStorage.getItem("token");
console.log(selectedKernelfalse)
console.log(selectedKernel)
try {
const updateStatus = await axios.put(
`${API_URL}/setpredict/update-status/${selectedKernelfalse}?status=false`,
null,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
const updateStatusnew = await axios.put(
`${API_URL}/setpredict/update-status/${selectedKernel}?status=true`,
null,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
if (selectedKernel === 1) {
const linear = await axios.put(
`${API_URL}/setpredict/1?nilai_c=${nilaiC}&nilai_epsilon=${epsilon}`,
null,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
} else if (selectedKernel ===2 ){
const poly = await axios.put(
`${API_URL}/setpredict/2?nilai_c=${nilaiC}&nilai_gamma=${gamma}&nilai_epsilon=${epsilon}&nilai_degree=${degree}&nilai_coef=${coef0}`,
null,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
} else if (selectedKernel ===3 ){
const sigmoid = await axios.put(
`${API_URL}/setpredict/3?nilai_c=${nilaiC}&nilai_gamma=${gamma}&nilai_epsilon=${epsilon}&nilai_coef=${coef0}`,
null,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
} else if (selectedKernel ===4 ){
const rbf = await axios.put(
`${API_URL}/setpredict/4?nilai_c=${nilaiC}&nilai_gamma=${gamma}&nilai_epsilon=${epsilon}`,
null,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
}
toast({
description: "Pengaturan model berhasil disimpan",
});
fetchDataKernel();
} catch (error) {
toast({
description: `${error.response.data.detail}`,
variant: "destructive",
});
} }
} }
return ( return (
@ -53,15 +188,15 @@ const Setting = () => {
<div className="xl:w-1/5 md:w-full w-full px-5 py-2"> <div className="xl:w-1/5 md:w-full w-full px-5 py-2">
<div className="grid w-full max-w-full items-center gap-1.5"> <div className="grid w-full max-w-full items-center gap-1.5">
<Label htmlFor="email">Email</Label> <Label htmlFor="email">Email</Label>
<Input readOnly type="email" id="email" value={email} placeholder="Email" /> <Input readOnly type="email" id="email" value={email} placeholder="Email" />
</div> </div>
</div> </div>
<div className="xl:w-1/5 md:w-full w-full px-5 py-2"> <div className="xl:w-1/5 md:w-full w-full px-5 py-2">
<div className="grid w-full max-w-full items-center gap-1.5"> <div className="grid w-full max-w-full items-center gap-1.5">
<Label htmlFor="password">Password</Label> <Label htmlFor="password">Password</Label>
<Input type="password" id="password" placeholder="password" value={password} <Input type="password" id="password" placeholder="password" value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
required/> required />
</div> </div>
</div> </div>
</div> </div>
@ -78,7 +213,11 @@ const Setting = () => {
<Label >pilih kernel</Label> <Label >pilih kernel</Label>
<div className="flex flex-wrap gap-3 px-5"> <div className="flex flex-wrap gap-3 px-5">
<div className="flex items-center space-x-2 xl:w-1/4 md:w-full w-full "> <div className="flex items-center space-x-2 xl:w-1/4 md:w-full w-full ">
<Checkbox id="linear" /> <Checkbox
id="linear"
checked={selectedKernel === 1}
onCheckedChange={() => handleCheckboxChange(1)}
/>
<label <label
htmlFor="linear" htmlFor="linear"
className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer" className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
@ -87,7 +226,11 @@ const Setting = () => {
</label> </label>
</div> </div>
<div className="flex items-center space-x-2 xl:w-1/4 md:w-full w-full "> <div className="flex items-center space-x-2 xl:w-1/4 md:w-full w-full ">
<Checkbox id="Polynomial" /> <Checkbox
id="Polynomial"
checked={selectedKernel === 2}
onCheckedChange={() => handleCheckboxChange(2)}
/>
<label <label
htmlFor="Polynomial" htmlFor="Polynomial"
className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer" className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
@ -96,7 +239,11 @@ const Setting = () => {
</label> </label>
</div> </div>
<div className="flex items-center space-x-2 xl:w-1/4 md:w-full w-full "> <div className="flex items-center space-x-2 xl:w-1/4 md:w-full w-full ">
<Checkbox id="sigmoid" /> <Checkbox
id="sigmoid"
checked={selectedKernel === 3}
onCheckedChange={() => handleCheckboxChange(3)}
/>
<label <label
htmlFor="sigmoid" htmlFor="sigmoid"
className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer" className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
@ -105,7 +252,11 @@ const Setting = () => {
</label> </label>
</div> </div>
<div className="flex items-center space-x-2 xl:w-1/2 md:w-full w-full "> <div className="flex items-center space-x-2 xl:w-1/2 md:w-full w-full ">
<Checkbox id="RBF" /> <Checkbox
id="RBF"
checked={selectedKernel === 4}
onCheckedChange={() => handleCheckboxChange(4)}
/>
<label <label
htmlFor="RBF" htmlFor="RBF"
className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer" className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
@ -119,31 +270,77 @@ const Setting = () => {
</div> </div>
<div className="xl:w-[70%] md:w-full w-full px-5 py-2"> <div className="xl:w-[70%] md:w-full w-full px-5 py-2">
<div className="grid grid-cols-auto-fit md:grid-cols-2 xl:grid-cols-3 gap-4"> <div className="grid grid-cols-auto-fit md:grid-cols-2 xl:grid-cols-3 gap-4">
<div className="grid w-full items-center gap-1.5"> <div className="grid w-full items-center gap-1.5">
<Label>Masukan nilai C</Label> <Label>Masukan nilai C</Label>
<Input type="text" placeholder="nilai C" /> <Input
</div> type="text"
<div className="grid w-full items-center gap-1.5"> placeholder="nilai C"
<Label>Masukan nilai epsilon</Label> value={nilaiC ?? ""}
<Input type="text" placeholder="nilai epsilon" /> onChange={(e) => setNilaiC(e.target.value)}
</div> disabled={
<div className="grid w-full items-center gap-1.5"> selectedKernel !== 1 &&
<Label>Masukan nilai Gamma</Label> selectedKernel !== 2 &&
<Input type="text" placeholder="nilai Gamma" /> selectedKernel !== 3 &&
</div> selectedKernel !== 4
<div className="grid w-full items-center gap-1.5"> }
<Label>Masukan nilai degree</Label>
<Input type="text" placeholder="nilai degree" /> />
</div> </div>
<div className="grid w-full items-center gap-1.5"> <div className="grid w-full items-center gap-1.5">
<Label>Masukan nilai coef0</Label> <Label>Masukan nilai epsilon</Label>
<Input type="text" placeholder="nilai coef0" /> <Input
</div> type="text"
placeholder="nilai epsilon"
value={epsilon ?? ""}
onChange={(e) => setEpsilon(e.target.value)}
disabled={
selectedKernel !== 1 &&
selectedKernel !== 2 &&
selectedKernel !== 3 &&
selectedKernel !== 4
}
/>
</div>
<div className="grid w-full items-center gap-1.5">
<Label>Masukan nilai Gamma</Label>
<Input
type="text"
placeholder="nilai Gamma"
value={gamma ?? ""}
onChange={(e) => setGamma(e.target.value)}
disabled={
selectedKernel !== 2 &&
selectedKernel !== 3 &&
selectedKernel !== 4
}
/>
</div>
<div className="grid w-full items-center gap-1.5">
<Label>Masukan nilai degree</Label>
<Input
type="text"
placeholder="nilai degree"
value={degree ?? ""}
onChange={(e) => setDegree(e.target.value)}
disabled={selectedKernel !== 2} />
</div>
<div className="grid w-full items-center gap-1.5">
<Label>Masukan nilai coef0</Label>
<Input
type="text"
placeholder="nilai coef0"
value={coef0 ?? ""}
onChange={(e) => setCoef0(e.target.value)}
disabled={
selectedKernel !== 2 && selectedKernel !== 3
}
/>
</div>
</div> </div>
</div> </div>
</div> </div>
<div> <div>
<Button className="xl:w-[80px] md:w-full w-full px-5 py-2 bg-gradient-to-r from-[#402412a8] to-[#9a070790]">simpan</Button> <Button className="xl:w-[80px] md:w-full w-full px-5 py-2 bg-gradient-to-r from-[#402412a8] to-[#9a070790]" onClick={handleSaveDataKernel}>simpan</Button>
</div> </div>
</div> </div>