Davidbio commited on
Commit
68e495a
·
verified ·
1 Parent(s): cf88e8b

Upload Manual ML Indobert

Browse files
Files changed (6) hide show
  1. .dockerignore +91 -0
  2. .gitignore +61 -0
  3. Dockerfile +33 -0
  4. README.md +90 -11
  5. app.py +218 -0
  6. requirements.txt +17 -0
.dockerignore ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .dockerignore - Exclude file yang tidak diperlukan dari Docker build
2
+ # Ini memastikan hanya file yang terpakai yang masuk ke Docker image
3
+
4
+ # Model checkpoints dan versions yang tidak terpakai
5
+ models/indobert_versions/
6
+ models/indobert/checkpoint-*/
7
+ **/checkpoint-*/
8
+ **/checkpoints/
9
+ **/*.ckpt
10
+
11
+ # Training artifacts yang tidak perlu
12
+ *.pth.tar
13
+ *.pt
14
+ trainer_state.json
15
+ training_args.bin
16
+
17
+ # Data dan dataset (tidak perlu di Space)
18
+ data/
19
+ datasets/
20
+ *.csv
21
+ *.json
22
+ *.jsonl
23
+ !config.json
24
+ !tokenizer.json
25
+ !tokenizer_config.json
26
+ !special_tokens_map.json
27
+
28
+ # Python cache
29
+ __pycache__/
30
+ *.py[cod]
31
+ *$py.class
32
+ *.so
33
+ .Python
34
+ *.egg-info/
35
+ .pytest_cache/
36
+ .mypy_cache/
37
+
38
+ # Virtual environments
39
+ venv/
40
+ env/
41
+ ENV/
42
+
43
+ # IDE
44
+ .vscode/
45
+ .idea/
46
+ *.swp
47
+ *.swo
48
+ *~
49
+ .DS_Store
50
+ Thumbs.db
51
+
52
+ # Git
53
+ .git/
54
+ .gitignore
55
+ .gitattributes
56
+
57
+ # Documentation yang tidak perlu di runtime
58
+ DEPLOYMENT.md
59
+ QUICKSTART.md
60
+ *.md
61
+ !README.md
62
+
63
+ # Test files
64
+ test_*.py
65
+ tests/
66
+ *_test.py
67
+
68
+ # Scripts yang tidak perlu di runtime
69
+ upload_model_to_hub.py
70
+ quick_deploy.sh
71
+ quick_deploy.ps1
72
+
73
+ # Logs
74
+ *.log
75
+ logs/
76
+
77
+ # Temporary files
78
+ *.tmp
79
+ tmp/
80
+ temp/
81
+ .cache/
82
+
83
+ # Large files yang tidak perlu
84
+ *.zip
85
+ *.tar
86
+ *.gz
87
+ *.rar
88
+
89
+ # Notebook checkpoints
90
+ .ipynb_checkpoints/
91
+ *.ipynb
.gitignore ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .gitignore untuk Hugging Face Space
2
+
3
+ # Python
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+ *.so
8
+ .Python
9
+ build/
10
+ develop-eggs/
11
+ dist/
12
+ downloads/
13
+ eggs/
14
+ .eggs/
15
+ lib/
16
+ lib64/
17
+ parts/
18
+ sdist/
19
+ var/
20
+ wheels/
21
+ *.egg-info/
22
+ .installed.cfg
23
+ *.egg
24
+
25
+ # Virtual Environment
26
+ venv/
27
+ env/
28
+ ENV/
29
+
30
+ # IDE
31
+ .vscode/
32
+ .idea/
33
+ *.swp
34
+ *.swo
35
+ *~
36
+
37
+ # OS
38
+ .DS_Store
39
+ Thumbs.db
40
+
41
+ # Model files (jika sudah di-upload ke HF Hub)
42
+ models/indobert/*.bin
43
+ models/indobert/*.safetensors
44
+ models/indobert/pytorch_model.bin
45
+
46
+ # Logs
47
+ *.log
48
+ logs/
49
+
50
+ # Environment variables
51
+ .env
52
+ .env.local
53
+
54
+ # Test files
55
+ test_*.py
56
+ tests/
57
+
58
+ # Temporary files
59
+ *.tmp
60
+ tmp/
61
+ temp/
Dockerfile ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Space - IndoBERT Fake News Detection
2
+ # Base image dengan Python 3.10
3
+ FROM python:3.10-slim
4
+
5
+ # Set working directory
6
+ WORKDIR /app
7
+
8
+ # Install system dependencies
9
+ RUN apt-get update && apt-get install -y \
10
+ git \
11
+ build-essential \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Copy requirements first untuk caching
15
+ COPY requirements.txt .
16
+ RUN pip install --no-cache-dir -r requirements.txt
17
+
18
+ # Copy application code (hanya file yang diperlukan)
19
+ COPY app.py .
20
+
21
+ # Model akan di-load dari HuggingFace Hub, tidak perlu copy lokal
22
+ # Environment variable HF_MODEL_REPO akan di-set di Space settings
23
+
24
+ # Expose port 7860 (default untuk HF Spaces)
25
+ EXPOSE 7860
26
+
27
+ # Set environment variables
28
+ ENV GRADIO_SERVER_NAME="0.0.0.0"
29
+ ENV GRADIO_SERVER_PORT=7860
30
+ ENV HF_MODEL_REPO="Davidbio/fakenewsdetection"
31
+
32
+ # Run the application
33
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,11 +1,90 @@
1
- ---
2
- title: Fakenewsdetection
3
- emoji: 🏢
4
- colorFrom: gray
5
- colorTo: green
6
- sdk: docker
7
- pinned: false
8
- license: mit
9
- ---
10
-
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: IndoBERT Fake News Detection
3
+ emoji: 🔍
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ app_port: 7860
10
+ tags:
11
+ - indonesian
12
+ - fake-news
13
+ - bert
14
+ - classification
15
+ - nlp
16
+ - text-classification
17
+ models:
18
+ - Davidbio/fakenewsdetection
19
+ ---
20
+
21
+ # 🔍 IndoBERT Fake News Detection
22
+
23
+ Aplikasi deteksi berita hoax berbahasa Indonesia menggunakan model IndoBERT.
24
+
25
+ ## 📖 Deskripsi
26
+
27
+ Model ini menggunakan **IndoBERT** (Indonesian BERT) yang telah di-fine-tune pada dataset berita Indonesia untuk mengklasifikasikan berita sebagai **Real** atau **Hoax (Fake News)**.
28
+
29
+ ### ✨ Fitur
30
+
31
+ - 🤖 Deteksi otomatis berita hoax menggunakan deep learning
32
+ - 📊 Menampilkan confidence score dan probabilitas detail
33
+ - 🇮🇩 Dioptimalkan untuk teks berbahasa Indonesia
34
+ - ⚡ Interface yang mudah digunakan dengan Gradio
35
+
36
+ ## 🚀 Cara Penggunaan
37
+
38
+ 1. Masukkan teks berita pada kotak input
39
+ 2. Klik tombol "🔍 Deteksi Berita"
40
+ 3. Lihat hasil analisis:
41
+ - Label prediksi (Real/Hoax)
42
+ - Confidence score
43
+ - Distribusi probabilitas
44
+
45
+ ## 🎯 Model Information
46
+
47
+ - **Base Model:** indobenchmark/indobert-base-p1
48
+ - **Task:** Binary Text Classification
49
+ - **Classes:**
50
+ - 0: Real News
51
+ - 1: Fake News (Hoax)
52
+ - **Max Sequence Length:** 256 tokens
53
+ - **Framework:** PyTorch + Transformers
54
+
55
+ ## ⚠️ Disclaimer
56
+
57
+ Model ini adalah **alat bantu** dan tidak menjamin akurasi 100%. Selalu verifikasi informasi dari sumber terpercaya sebelum menyimpulkan sebuah berita sebagai hoax.
58
+
59
+ ## 📚 Dataset
60
+
61
+ Model dilatih menggunakan dataset berita Indonesia yang telah dilabeli sebagai real atau hoax.
62
+
63
+ ## 🛠️ Technology Stack
64
+
65
+ - **Framework:** Gradio
66
+ - **Model:** IndoBERT (Transformers)
67
+ - **Backend:** PyTorch
68
+ - **Deployment:** Hugging Face Spaces (Docker)
69
+
70
+ ## 📝 Citation
71
+
72
+ Jika menggunakan model ini, mohon cantumkan:
73
+
74
+ ```bibtex
75
+ @misc{indobert-fakenews,
76
+ title={IndoBERT Fake News Detection},
77
+ author={Your Name},
78
+ year={2025},
79
+ publisher={Hugging Face},
80
+ howpublished={\url{https://huggingface.co/spaces/your-username/indobert-fakenews}}
81
+ }
82
+ ```
83
+
84
+ ## 📄 License
85
+
86
+ MIT License
87
+
88
+ ---
89
+
90
+ **Developed with ❤️ for Indonesian NLP Community**
app.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Space Application - IndoBERT Fake News Detection
3
+ Menggunakan Gradio untuk interface yang user-friendly
4
+ """
5
+
6
+ import gradio as gr
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
9
+ import numpy as np
10
+ from pathlib import Path
11
+ import os
12
+ import logging
13
+
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Konfigurasi - Model dari HuggingFace Hub
18
+ MODEL_REPO = "Davidbio/fakenewsdetection" # Model yang sudah di-upload
19
+ MODEL_DIR = Path(__file__).parent / "models" / "indobert" # Fallback lokal
20
+
21
+
22
+ class FakeNewsDetector:
23
+ def __init__(self):
24
+ self.tokenizer = None
25
+ self.model = None
26
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
+ self.load_model()
28
+
29
+ def load_model(self):
30
+ """Load model dari HuggingFace Hub atau lokal"""
31
+ try:
32
+ # Load dari HuggingFace Hub (prioritas utama)
33
+ hf_repo = os.environ.get("HF_MODEL_REPO", MODEL_REPO)
34
+ logger.info(f"Loading model dari HuggingFace Hub: {hf_repo}")
35
+
36
+ try:
37
+ self.tokenizer = AutoTokenizer.from_pretrained(hf_repo)
38
+ self.model = AutoModelForSequenceClassification.from_pretrained(hf_repo)
39
+ logger.info("✅ Model loaded dari HuggingFace Hub")
40
+ except Exception as hub_error:
41
+ # Fallback ke lokal jika HF Hub gagal
42
+ if MODEL_DIR.exists() and any(MODEL_DIR.iterdir()):
43
+ logger.warning(f"HF Hub failed, loading from local: {hub_error}")
44
+ self.tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
45
+ self.model = AutoModelForSequenceClassification.from_pretrained(
46
+ MODEL_DIR
47
+ )
48
+ logger.info("✅ Model loaded dari lokal")
49
+ else:
50
+ raise hub_error
51
+
52
+ self.model.eval()
53
+ self.model.to(self.device)
54
+ logger.info(f"Model berhasil dimuat di {self.device}")
55
+ except Exception as e:
56
+ logger.error(f"Error loading model: {e}")
57
+ raise
58
+
59
+ def predict(self, text: str):
60
+ """
61
+ Prediksi apakah berita adalah hoax atau bukan
62
+ Returns: (label, confidence, probabilities)
63
+ """
64
+ if not text or len(text.strip()) < 10:
65
+ return (
66
+ "Error",
67
+ 0.0,
68
+ {"Real": 0.0, "Hoax": 0.0},
69
+ "⚠️ Teks terlalu pendek. Minimal 10 karakter.",
70
+ )
71
+
72
+ try:
73
+ # Tokenisasi
74
+ encoded = self.tokenizer(
75
+ text, truncation=True, max_length=256, return_tensors="pt"
76
+ ).to(self.device)
77
+
78
+ # Prediksi
79
+ with torch.no_grad():
80
+ logits = self.model(**encoded).logits
81
+ probs = torch.softmax(logits, dim=-1).cpu().numpy()[0]
82
+
83
+ # Ekstrak hasil
84
+ prob_real = float(probs[0])
85
+ prob_hoax = float(probs[1])
86
+ predicted_label = int(np.argmax(probs))
87
+ confidence = float(probs[predicted_label])
88
+
89
+ # Label dan warning
90
+ label_text = "🚨 HOAX" if predicted_label == 1 else "✅ REAL"
91
+
92
+ # Confidence level
93
+ if confidence >= 0.9:
94
+ confidence_level = "Sangat Tinggi"
95
+ elif confidence >= 0.75:
96
+ confidence_level = "Tinggi"
97
+ elif confidence >= 0.6:
98
+ confidence_level = "Sedang"
99
+ else:
100
+ confidence_level = "Rendah"
101
+
102
+ # Warning message
103
+ warning = ""
104
+ if confidence < 0.6:
105
+ warning = "⚠️ Confidence rendah. Hasil mungkin tidak akurat. Silakan verifikasi secara manual."
106
+
107
+ # Format hasil
108
+ result_text = f"""
109
+ ### Hasil Deteksi: {label_text}
110
+
111
+ **Confidence:** {confidence:.2%} ({confidence_level})
112
+
113
+ **Probabilitas Detail:**
114
+ - Real News: {prob_real:.2%}
115
+ - Fake News (Hoax): {prob_hoax:.2%}
116
+
117
+ {warning}
118
+ """
119
+
120
+ return (
121
+ result_text,
122
+ confidence,
123
+ {"Real News": prob_real, "Fake News (Hoax)": prob_hoax},
124
+ warning,
125
+ )
126
+
127
+ except Exception as e:
128
+ logger.error(f"Error during prediction: {e}")
129
+ return f"❌ Error: {str(e)}", 0.0, {"Real": 0.0, "Hoax": 0.0}, ""
130
+
131
+
132
+ # Inisialisasi detector
133
+ detector = FakeNewsDetector()
134
+
135
+
136
+ def predict_news(text: str):
137
+ """Wrapper function untuk Gradio"""
138
+ result_text, confidence, probs, warning = detector.predict(text)
139
+ return result_text, probs
140
+
141
+
142
+ # Contoh teks untuk demo
143
+ examples = [
144
+ [
145
+ "Pemerintah mengumumkan kebijakan baru untuk meningkatkan ekonomi rakyat dengan subsidi langsung kepada UMKM."
146
+ ],
147
+ ["BREAKING: Alien mendarat di Jakarta dan bertemu dengan presiden!"],
148
+ [
149
+ "Menteri Kesehatan mengimbau masyarakat untuk tetap menjaga protokol kesehatan di tengah musim hujan."
150
+ ],
151
+ ]
152
+
153
+ # Buat Gradio Interface
154
+ with gr.Blocks(title="IndoBERT Fake News Detection", theme=gr.themes.Soft()) as demo:
155
+ gr.Markdown("""
156
+ # 🔍 IndoBERT Fake News Detection
157
+
158
+ Deteksi berita hoax menggunakan model IndoBERT yang telah dilatih pada dataset berita Indonesia.
159
+
160
+ **Cara Penggunaan:**
161
+ 1. Masukkan teks berita pada kotak di bawah
162
+ 2. Klik tombol "🔍 Deteksi Berita"
163
+ 3. Lihat hasil analisis dan tingkat confidence
164
+
165
+ ⚠️ **Catatan:** Model ini adalah alat bantu dan tidak 100% akurat. Selalu verifikasi dari sumber terpercaya.
166
+ """)
167
+
168
+ with gr.Row():
169
+ with gr.Column(scale=2):
170
+ input_text = gr.Textbox(
171
+ label="📝 Masukkan Teks Berita",
172
+ placeholder="Ketik atau paste teks berita di sini...",
173
+ lines=8,
174
+ max_lines=15,
175
+ )
176
+
177
+ with gr.Row():
178
+ clear_btn = gr.Button("🗑️ Clear", variant="secondary")
179
+ submit_btn = gr.Button("🔍 Deteksi Berita", variant="primary")
180
+
181
+ with gr.Column(scale=1):
182
+ output_text = gr.Markdown(label="Hasil Deteksi")
183
+ output_plot = gr.Label(label="Distribusi Probabilitas", num_top_classes=2)
184
+
185
+ # Examples
186
+ gr.Markdown("### 📋 Contoh Teks")
187
+ gr.Examples(examples=examples, inputs=input_text, label="Klik untuk mencoba contoh")
188
+
189
+ # Event handlers
190
+ submit_btn.click(
191
+ fn=predict_news, inputs=input_text, outputs=[output_text, output_plot]
192
+ )
193
+
194
+ clear_btn.click(
195
+ fn=lambda: ("", "", {}),
196
+ inputs=None,
197
+ outputs=[input_text, output_text, output_plot],
198
+ )
199
+
200
+ gr.Markdown("""
201
+ ---
202
+ ### ℹ️ Tentang Model
203
+
204
+ Model ini menggunakan **IndoBERT** (Indonesian BERT) yang telah di-fine-tune pada dataset berita Indonesia
205
+ untuk klasifikasi berita real vs hoax.
206
+
207
+ - **Base Model:** indobenchmark/indobert-base-p1
208
+ - **Task:** Binary Classification (Real/Hoax)
209
+ - **Max Length:** 256 tokens
210
+
211
+ ### 🤝 Kontribusi & Feedback
212
+
213
+ Jika menemukan hasil yang kurang akurat, silakan laporkan untuk membantu meningkatkan model ini.
214
+ """)
215
+
216
+ # Launch app
217
+ if __name__ == "__main__":
218
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Space Requirements
2
+ # Python 3.10+
3
+
4
+ # Web Framework - Gradio untuk HF Spaces
5
+ gradio>=4.0.0
6
+
7
+ # Model & ML Dependencies
8
+ torch>=2.0.0
9
+ transformers>=4.30.0
10
+ huggingface-hub>=0.18.0
11
+
12
+ # Data Processing
13
+ numpy>=1.24.0
14
+ pandas>=2.0.0
15
+
16
+ # Utilities
17
+ python-dotenv>=1.0.0