Spaces:
Runtime error
Runtime error
chore: update
Browse files- .gitignore +4 -0
- Dockerfile +33 -0
- main.py +131 -0
- poetry.lock +0 -0
- pyproject.toml +21 -0
- static/samples.csv +0 -0
- templates/index.html +267 -0
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
.venv
|
| 3 |
+
__pycache__
|
| 4 |
+
models
|
Dockerfile
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use official Python 3.12 base image
|
| 2 |
+
FROM python:3.12
|
| 3 |
+
|
| 4 |
+
# Create a non-root user and switch to it
|
| 5 |
+
RUN useradd -m -u 1000 user
|
| 6 |
+
USER user
|
| 7 |
+
|
| 8 |
+
# Set working directory
|
| 9 |
+
WORKDIR /app
|
| 10 |
+
|
| 11 |
+
# Add Poetry to PATH
|
| 12 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 13 |
+
|
| 14 |
+
# Install Poetry for the current user
|
| 15 |
+
RUN pip install --user poetry
|
| 16 |
+
|
| 17 |
+
# Copy pyproject and poetry.lock to install dependencies
|
| 18 |
+
COPY --chown=user pyproject.toml poetry.lock ./
|
| 19 |
+
|
| 20 |
+
# Disable Poetry's virtual environment creation
|
| 21 |
+
RUN poetry config virtualenvs.create false --local
|
| 22 |
+
|
| 23 |
+
# Install dependencies (but not the current project itself)
|
| 24 |
+
RUN poetry install --no-root --no-interaction --no-cache
|
| 25 |
+
|
| 26 |
+
# Copy the rest of the application code
|
| 27 |
+
COPY --chown=user . .
|
| 28 |
+
|
| 29 |
+
# Expose port
|
| 30 |
+
EXPOSE 7860
|
| 31 |
+
|
| 32 |
+
# Run your app with uvicorn (update if entry point is different)
|
| 33 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
main.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
from fastapi.templating import Jinja2Templates
|
| 5 |
+
from fastapi.middleware.gzip import GZipMiddleware
|
| 6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
import pickle
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import csv
|
| 12 |
+
|
| 13 |
+
app = FastAPI()
|
| 14 |
+
|
| 15 |
+
app.add_middleware(
|
| 16 |
+
CORSMiddleware,
|
| 17 |
+
allow_origins=["*"],
|
| 18 |
+
allow_credentials=True,
|
| 19 |
+
allow_methods=["*"],
|
| 20 |
+
allow_headers=["*"],
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
app.mount("/static",StaticFiles(directory="static"),name="static")
|
| 24 |
+
app.add_middleware(GZipMiddleware)
|
| 25 |
+
templates = Jinja2Templates(directory="templates")
|
| 26 |
+
|
| 27 |
+
original_torch_load = torch.load
|
| 28 |
+
def torch_load_cpu(*args, **kwargs):
|
| 29 |
+
if 'map_location' not in kwargs:
|
| 30 |
+
kwargs['map_location'] = torch.device('cpu')
|
| 31 |
+
return original_torch_load(*args, **kwargs)
|
| 32 |
+
torch.load = torch_load_cpu
|
| 33 |
+
|
| 34 |
+
model = pickle.load(open("models/model.pkl","rb"))
|
| 35 |
+
tokenizer = pickle.load(open("models/tokenizer.pkl", "rb"))
|
| 36 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 37 |
+
model.to(device)
|
| 38 |
+
model.eval()
|
| 39 |
+
|
| 40 |
+
# Pydantic models for request/response
|
| 41 |
+
class PredictionInput(BaseModel):
|
| 42 |
+
text: str # Text input for the model
|
| 43 |
+
|
| 44 |
+
class PredictionResponse(BaseModel):
|
| 45 |
+
prediction: int # Predicted class (-1: unknown, 0: not gambling, 1: gambling)
|
| 46 |
+
prediction_text: str # Human readable prediction
|
| 47 |
+
probabilities: dict # Probabilities for each class
|
| 48 |
+
confidence: float # Probability for the predicted class
|
| 49 |
+
status: str # "judi", "bukan judi", or "ragu-ragu"
|
| 50 |
+
|
| 51 |
+
@app.get("/")
|
| 52 |
+
def read_root(request: Request):
|
| 53 |
+
return templates.TemplateResponse(
|
| 54 |
+
request=request, name="index.html", context={"id": id}
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
@app.post("/predict", response_model=PredictionResponse)
|
| 58 |
+
async def predict(input_data: PredictionInput):
|
| 59 |
+
try:
|
| 60 |
+
# Threshold values
|
| 61 |
+
threshold_low = 0.4
|
| 62 |
+
threshold_high = 0.7
|
| 63 |
+
|
| 64 |
+
text = str(input_data.text) if input_data.text is not None else ""
|
| 65 |
+
|
| 66 |
+
# Tokenize input text
|
| 67 |
+
inputs = tokenizer(
|
| 68 |
+
text,
|
| 69 |
+
return_tensors="pt",
|
| 70 |
+
padding=True,
|
| 71 |
+
truncation=True,
|
| 72 |
+
max_length=128
|
| 73 |
+
)
|
| 74 |
+
inputs = {key: val.to(device) for key, val in inputs.items()}
|
| 75 |
+
|
| 76 |
+
# Make prediction
|
| 77 |
+
with torch.no_grad():
|
| 78 |
+
outputs = model(**inputs)
|
| 79 |
+
probs = F.softmax(outputs.logits, dim=-1)
|
| 80 |
+
prob_0 = probs[0][0].item() # not gambling
|
| 81 |
+
prob_1 = probs[0][1].item() # gambling
|
| 82 |
+
|
| 83 |
+
# Determine prediction based on probability thresholds
|
| 84 |
+
if prob_1 >= threshold_high:
|
| 85 |
+
prediction = 1 # gambling
|
| 86 |
+
prediction_text = f'judi ({prob_1:.2f})'
|
| 87 |
+
status = "judi"
|
| 88 |
+
confidence = prob_1
|
| 89 |
+
elif prob_1 <= threshold_low:
|
| 90 |
+
prediction = 0 # not gambling
|
| 91 |
+
prediction_text = f'bukan judi ({prob_0:.2f})'
|
| 92 |
+
status = "bukan judi"
|
| 93 |
+
confidence = prob_0
|
| 94 |
+
else:
|
| 95 |
+
prediction = -1 # unknown / uncertain
|
| 96 |
+
prediction_text = f'ragu-ragu ({prob_1:.2f})'
|
| 97 |
+
status = "ragu-ragu"
|
| 98 |
+
confidence = max(prob_0, prob_1)
|
| 99 |
+
|
| 100 |
+
return PredictionResponse(
|
| 101 |
+
prediction=prediction,
|
| 102 |
+
prediction_text=prediction_text,
|
| 103 |
+
probabilities={"prob_bukan_judi": prob_0, "prob_judi": prob_1},
|
| 104 |
+
confidence=confidence,
|
| 105 |
+
status=status
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}")
|
| 110 |
+
|
| 111 |
+
@app.get("/predict")
|
| 112 |
+
async def predict_get(request: Request):
|
| 113 |
+
"""GET endpoint to render prediction form"""
|
| 114 |
+
return templates.TemplateResponse(
|
| 115 |
+
request=request, name="predict.html", context={}
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
@app.get("/samples")
|
| 119 |
+
async def get_samples():
|
| 120 |
+
file_path = "static/samples.csv"
|
| 121 |
+
|
| 122 |
+
if not os.path.exists(file_path):
|
| 123 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 124 |
+
|
| 125 |
+
try:
|
| 126 |
+
with open(file_path, newline='', encoding='utf-8') as csvfile:
|
| 127 |
+
reader = csv.DictReader(csvfile)
|
| 128 |
+
samples = [row["text"] for row in reader if row.get("text")]
|
| 129 |
+
return samples
|
| 130 |
+
except Exception as e:
|
| 131 |
+
raise HTTPException(status_code=500, detail=f"Error reading file: {str(e)}")
|
poetry.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pyproject.toml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[tool.poetry]
|
| 2 |
+
name = "isgdmodeldemo"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = ""
|
| 5 |
+
authors = ["Samuel <samuel@stmikku.ac.id>"]
|
| 6 |
+
readme = "README.md"
|
| 7 |
+
package-mode = false
|
| 8 |
+
|
| 9 |
+
[tool.poetry.dependencies]
|
| 10 |
+
python = ">=3.12"
|
| 11 |
+
fastapi = {extras = ["standard"], version = ">=0.115.12,<0.116.0"}
|
| 12 |
+
jinja2 = ">=3.1.6,<4.0.0"
|
| 13 |
+
uvicorn = ">=0.34.2,<0.35.0"
|
| 14 |
+
python-multipart = ">=0.0.20,<0.0.21"
|
| 15 |
+
transformers = ">=4.52.3,<5.0.0"
|
| 16 |
+
torch = ">=2.7.0,<3.0.0"
|
| 17 |
+
pandas = ">=2.2.3,<3.0.0"
|
| 18 |
+
|
| 19 |
+
[build-system]
|
| 20 |
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
| 21 |
+
build-backend = "poetry.core.masonry.api"
|
static/samples.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
templates/index.html
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="id">
|
| 3 |
+
|
| 4 |
+
<head>
|
| 5 |
+
<meta charset="UTF-8">
|
| 6 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 7 |
+
<title>Klasifikasi Teks</title>
|
| 8 |
+
<script src="https://cdn.tailwindcss.com"></script>
|
| 9 |
+
<script>
|
| 10 |
+
tailwind.config = {
|
| 11 |
+
theme: {
|
| 12 |
+
extend: {
|
| 13 |
+
animation: {
|
| 14 |
+
'slide-up': 'slideUp 0.6s ease-out',
|
| 15 |
+
'fade-in': 'fadeIn 0.5s ease-out',
|
| 16 |
+
'spin-slow': 'spin 1s linear infinite',
|
| 17 |
+
},
|
| 18 |
+
keyframes: {
|
| 19 |
+
slideUp: {
|
| 20 |
+
'0%': { opacity: '0', transform: 'translateY(30px)' },
|
| 21 |
+
'100%': { opacity: '1', transform: 'translateY(0)' }
|
| 22 |
+
},
|
| 23 |
+
fadeIn: {
|
| 24 |
+
'0%': { opacity: '0' },
|
| 25 |
+
'100%': { opacity: '1' }
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
</script>
|
| 32 |
+
<style>
|
| 33 |
+
.gradient-bg {
|
| 34 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
.gradient-btn {
|
| 38 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
.gradient-positive {
|
| 42 |
+
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
.gradient-negative {
|
| 46 |
+
background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
.gradient-unknown {
|
| 50 |
+
background: linear-gradient(135deg, #ffa726 0%, #ffcc02 100%);
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
.gradient-error {
|
| 54 |
+
background: linear-gradient(135deg, #ff6b6b 0%, #ffa500 100%);
|
| 55 |
+
}
|
| 56 |
+
</style>
|
| 57 |
+
</head>
|
| 58 |
+
|
| 59 |
+
<body class="gradient-bg min-h-screen flex items-center justify-center p-4 sm:p-6 lg:p-8">
|
| 60 |
+
<div
|
| 61 |
+
class="bg-white bg-opacity-95 backdrop-blur-lg rounded-2xl lg:rounded-3xl p-6 sm:p-8 lg:p-10 shadow-2xl max-w-xs sm:max-w-md lg:max-w-2xl w-full animate-slide-up">
|
| 62 |
+
<h1 class="text-center text-gray-800 mb-6 sm:mb-8 text-2xl sm:text-3xl lg:text-4xl font-light">
|
| 63 |
+
🤖 Klasifikasi Teks
|
| 64 |
+
</h1>
|
| 65 |
+
|
| 66 |
+
<form id="predictionForm" class="space-y-6">
|
| 67 |
+
<div class="space-y-2">
|
| 68 |
+
<label for="textInput" class="block text-gray-600 font-medium text-sm sm:text-base">
|
| 69 |
+
Masukkan teks untuk diklasifikasi:
|
| 70 |
+
</label>
|
| 71 |
+
<textarea id="textInput" name="text"
|
| 72 |
+
placeholder="Ketik teks Anda di sini... (contoh: 'Aku sih serius udah menang banyak di situs777' atau 'Produk ini sangat bagus dan berkualitas')"
|
| 73 |
+
required
|
| 74 |
+
class="w-full p-3 sm:p-4 border-2 border-gray-200 rounded-lg sm:rounded-xl text-sm sm:text-base resize-vertical min-h-[120px] sm:min-h-[140px] transition-all duration-300 focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-100"></textarea>
|
| 75 |
+
</div>
|
| 76 |
+
|
| 77 |
+
<div class="flex flex-col sm:flex-row gap-4">
|
| 78 |
+
<button type="submit" id="submitBtn"
|
| 79 |
+
class="gradient-btn text-white px-6 sm:px-8 py-3 sm:py-4 rounded-full text-sm sm:text-base font-medium cursor-pointer transition-all duration-300 w-full shadow-lg hover:shadow-xl hover:-translate-y-1 disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none">
|
| 80 |
+
Analisis Teks
|
| 81 |
+
</button>
|
| 82 |
+
|
| 83 |
+
<button type="button" id="loadExampleBtn"
|
| 84 |
+
class="bg-white text-indigo-600 border border-indigo-300 px-6 sm:px-8 py-3 sm:py-4 rounded-full text-sm sm:text-base font-medium cursor-pointer transition-all duration-300 w-full shadow-lg hover:shadow-xl hover:-translate-y-1 hover:bg-indigo-50">
|
| 85 |
+
Load Contoh
|
| 86 |
+
</button>
|
| 87 |
+
</div>
|
| 88 |
+
</form>
|
| 89 |
+
|
| 90 |
+
<div class="hidden text-center mt-6 animate-fade-in" id="loading">
|
| 91 |
+
<div
|
| 92 |
+
class="w-6 h-6 sm:w-8 sm:h-8 border-3 border-indigo-200 border-t-indigo-500 rounded-full animate-spin mx-auto mb-2 sm:mb-3">
|
| 93 |
+
</div>
|
| 94 |
+
<p class="text-gray-600 text-sm sm:text-base">Menganalisis teks Anda...</p>
|
| 95 |
+
</div>
|
| 96 |
+
|
| 97 |
+
<div id="result" class="hidden mt-6 sm:mt-8 p-4 sm:p-6 rounded-lg sm:rounded-xl text-white animate-fade-in">
|
| 98 |
+
<h3 id="resultTitle" class="mb-3 sm:mb-4 text-lg sm:text-xl lg:text-2xl font-semibold"></h3>
|
| 99 |
+
<div id="resultContent" class="space-y-3 sm:space-y-4 text-sm sm:text-base"></div>
|
| 100 |
+
</div>
|
| 101 |
+
</div>
|
| 102 |
+
|
| 103 |
+
<script>
|
| 104 |
+
document.getElementById('loadExampleBtn').addEventListener('click', async () => {
|
| 105 |
+
const textInput = document.getElementById('textInput');
|
| 106 |
+
try {
|
| 107 |
+
const res = await fetch('/samples');
|
| 108 |
+
const data = await res.json();
|
| 109 |
+
|
| 110 |
+
if (Array.isArray(data) && data.length > 0) {
|
| 111 |
+
// Ambil secara acak satu contoh
|
| 112 |
+
const randomIndex = Math.floor(Math.random() * data.length);
|
| 113 |
+
textInput.value = data[randomIndex];
|
| 114 |
+
textInput.focus();
|
| 115 |
+
} else {
|
| 116 |
+
alert('Tidak ada contoh tersedia.');
|
| 117 |
+
}
|
| 118 |
+
} catch (err) {
|
| 119 |
+
alert('Gagal memuat contoh: ' + err.message);
|
| 120 |
+
}
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
document.getElementById('predictionForm').addEventListener('submit', async function (e) {
|
| 124 |
+
e.preventDefault();
|
| 125 |
+
|
| 126 |
+
const textInput = document.getElementById('textInput');
|
| 127 |
+
const submitBtn = document.getElementById('submitBtn');
|
| 128 |
+
const loading = document.getElementById('loading');
|
| 129 |
+
const result = document.getElementById('result');
|
| 130 |
+
|
| 131 |
+
// Reset and show loading
|
| 132 |
+
result.classList.add('hidden');
|
| 133 |
+
loading.classList.remove('hidden');
|
| 134 |
+
submitBtn.disabled = true;
|
| 135 |
+
submitBtn.textContent = 'Menganalisis...';
|
| 136 |
+
|
| 137 |
+
try {
|
| 138 |
+
const response = await fetch('/predict', {
|
| 139 |
+
method: 'POST',
|
| 140 |
+
headers: {
|
| 141 |
+
'Content-Type': 'application/json',
|
| 142 |
+
},
|
| 143 |
+
body: JSON.stringify({
|
| 144 |
+
text: textInput.value
|
| 145 |
+
})
|
| 146 |
+
});
|
| 147 |
+
|
| 148 |
+
const data = await response.json();
|
| 149 |
+
|
| 150 |
+
if (response.ok) {
|
| 151 |
+
displayResult(data);
|
| 152 |
+
} else {
|
| 153 |
+
displayError(data.detail || 'Terjadi kesalahan');
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
} catch (error) {
|
| 157 |
+
displayError('Kesalahan jaringan: ' + error.message);
|
| 158 |
+
} finally {
|
| 159 |
+
loading.classList.add('hidden');
|
| 160 |
+
submitBtn.disabled = false;
|
| 161 |
+
submitBtn.textContent = 'Analisis Teks';
|
| 162 |
+
}
|
| 163 |
+
});
|
| 164 |
+
|
| 165 |
+
function displayResult(data) {
|
| 166 |
+
const result = document.getElementById('result');
|
| 167 |
+
const resultTitle = document.getElementById('resultTitle');
|
| 168 |
+
const resultContent = document.getElementById('resultContent');
|
| 169 |
+
|
| 170 |
+
// Remove all gradient classes first
|
| 171 |
+
result.className = result.className.replace(/gradient-\w+/g, '');
|
| 172 |
+
|
| 173 |
+
// Determine class based on prediction
|
| 174 |
+
let gradientClass, predictionText, iconEmoji;
|
| 175 |
+
|
| 176 |
+
if (data.prediction === 1) {
|
| 177 |
+
gradientClass = 'gradient-negative';
|
| 178 |
+
predictionText = 'Judi';
|
| 179 |
+
iconEmoji = '⚠️';
|
| 180 |
+
} else if (data.prediction === 0) {
|
| 181 |
+
gradientClass = 'gradient-positive';
|
| 182 |
+
predictionText = 'Bukan Judi';
|
| 183 |
+
iconEmoji = '✅';
|
| 184 |
+
} else {
|
| 185 |
+
gradientClass = 'gradient-unknown';
|
| 186 |
+
predictionText = 'Ragu-ragu';
|
| 187 |
+
iconEmoji = '❓';
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
result.classList.add(gradientClass);
|
| 191 |
+
resultTitle.textContent = `${iconEmoji} Prediksi: ${predictionText}`;
|
| 192 |
+
|
| 193 |
+
const confidence = (data.confidence * 100).toFixed(1);
|
| 194 |
+
const probBukanJudi = (data.probabilities.prob_bukan_judi * 100).toFixed(1);
|
| 195 |
+
const probJudi = (data.probabilities.prob_judi * 100).toFixed(1);
|
| 196 |
+
|
| 197 |
+
let statusExplanation = '';
|
| 198 |
+
if (data.prediction === 1) {
|
| 199 |
+
statusExplanation = 'Teks kemungkinan mengandung konten judi online';
|
| 200 |
+
} else if (data.prediction === 0) {
|
| 201 |
+
statusExplanation = 'Teks kemungkinan tidak mengandung konten judi';
|
| 202 |
+
} else {
|
| 203 |
+
statusExplanation = 'Model tidak yakin dengan klasifikasi teks ini';
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
resultContent.innerHTML = `
|
| 207 |
+
<div class="space-y-2 sm:space-y-3">
|
| 208 |
+
<p><strong>Status:</strong> ${data.status}</p>
|
| 209 |
+
<p class="italic opacity-90">${statusExplanation}</p>
|
| 210 |
+
<p><strong>Tingkat Keyakinan:</strong> ${confidence}%</p>
|
| 211 |
+
</div>
|
| 212 |
+
|
| 213 |
+
<div class="mt-4 sm:mt-6">
|
| 214 |
+
<p class="font-semibold mb-3 sm:mb-4">Detail Probabilitas:</p>
|
| 215 |
+
|
| 216 |
+
<div class="space-y-3 sm:space-y-4">
|
| 217 |
+
<div>
|
| 218 |
+
<div class="flex justify-between mb-1 sm:mb-2 text-sm sm:text-base">
|
| 219 |
+
<span>Bukan Judi</span>
|
| 220 |
+
<span>${probBukanJudi}%</span>
|
| 221 |
+
</div>
|
| 222 |
+
<div class="bg-white bg-opacity-30 rounded-full h-6 sm:h-8 overflow-hidden">
|
| 223 |
+
<div class="h-full bg-white bg-opacity-80 rounded-full flex items-center justify-center font-semibold text-gray-800 text-xs sm:text-sm transition-all duration-1000 ease-out" style="width: ${probBukanJudi}%">
|
| 224 |
+
${probBukanJudi}%
|
| 225 |
+
</div>
|
| 226 |
+
</div>
|
| 227 |
+
</div>
|
| 228 |
+
|
| 229 |
+
<div>
|
| 230 |
+
<div class="flex justify-between mb-1 sm:mb-2 text-sm sm:text-base">
|
| 231 |
+
<span>Judi</span>
|
| 232 |
+
<span>${probJudi}%</span>
|
| 233 |
+
</div>
|
| 234 |
+
<div class="bg-white bg-opacity-30 rounded-full h-6 sm:h-8 overflow-hidden">
|
| 235 |
+
<div class="h-full bg-white bg-opacity-80 rounded-full flex items-center justify-center font-semibold text-gray-800 text-xs sm:text-sm transition-all duration-1000 ease-out" style="width: ${probJudi}%">
|
| 236 |
+
${probJudi}%
|
| 237 |
+
</div>
|
| 238 |
+
</div>
|
| 239 |
+
</div>
|
| 240 |
+
</div>
|
| 241 |
+
</div>
|
| 242 |
+
|
| 243 |
+
<div class="mt-4 sm:mt-6 p-3 sm:p-4 bg-white bg-opacity-20 rounded-lg text-xs sm:text-sm">
|
| 244 |
+
<strong>Catatan:</strong> Sistem menggunakan threshold 40%-70% untuk menentukan tingkat kepastian prediksi.
|
| 245 |
+
</div>
|
| 246 |
+
`;
|
| 247 |
+
|
| 248 |
+
result.classList.remove('hidden');
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
function displayError(message) {
|
| 252 |
+
const result = document.getElementById('result');
|
| 253 |
+
const resultTitle = document.getElementById('resultTitle');
|
| 254 |
+
const resultContent = document.getElementById('resultContent');
|
| 255 |
+
|
| 256 |
+
// Remove all gradient classes and add error class
|
| 257 |
+
result.className = result.className.replace(/gradient-\w+/g, '');
|
| 258 |
+
result.classList.add('gradient-error');
|
| 259 |
+
|
| 260 |
+
resultTitle.textContent = '❌ Kesalahan';
|
| 261 |
+
resultContent.innerHTML = `<p class="text-sm sm:text-base">${message}</p>`;
|
| 262 |
+
result.classList.remove('hidden');
|
| 263 |
+
}
|
| 264 |
+
</script>
|
| 265 |
+
</body>
|
| 266 |
+
|
| 267 |
+
</html>
|