KenLumod commited on
Commit
5cc26f5
·
verified ·
1 Parent(s): 34012c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -53
app.py CHANGED
@@ -1,61 +1,31 @@
1
- import gradio as gr
2
  import torch
3
- from transformers import AutoModel, AutoTokenizer
4
 
5
- # 1. Model Architecture (Matches Your Training)
6
- class BERTFakeNewsDetector(torch.nn.Module):
7
- def __init__(self):
 
 
 
 
 
 
 
 
8
  super().__init__()
9
- self.bert = AutoModel.from_pretrained("bert-base-uncased")
10
- self.classifier = torch.nn.Sequential(
11
- torch.nn.Dropout(0.1),
12
- torch.nn.Linear(768, 512),
13
- torch.nn.ReLU(),
14
- torch.nn.Linear(512, 2),
15
- torch.nn.LogSoftmax(dim=1)
16
  )
17
 
18
  def forward(self, input_ids, attention_mask):
19
  outputs = self.bert(input_ids, attention_mask=attention_mask)
20
- return self.classifier(outputs.last_hidden_state[:, 0, 🙂)
21
-
22
- # 2. Loading Function (Updated for model_state.bin)
23
- def load_model():
24
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
-
26
- # Initialize model
27
- model = BERTFakeNewsDetector()
28
-
29
- # Load weights - using model_state.bin instead of pytorch_model.bin
30
- state_dict = torch.hub.load_state_dict_from_url(
31
- "https://huggingface.co/KenLumod/ML-Fake-Real-News-Detector-Final/resolve/main/model_state.bin",
32
- map_location=device
33
- )
34
- model.load_state_dict(state_dict)
35
- model.to(device).eval()
36
-
37
- tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
38
- return model, tokenizer, device
39
-
40
- # 3. Gradio App
41
- model, tokenizer, device = load_model()
42
-
43
- def predict(text):
44
- inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=256).to(device)
45
- with torch.no_grad():
46
- logits = model(**inputs)
47
- probs = torch.exp(logits).cpu().numpy()[0]
48
- return {"REAL": float(probs[0]), "FAKE": float(probs[1])}
49
 
50
- gr.Interface(
51
- fn=predict,
52
- inputs=gr.Textbox(label="News Content", lines=3, placeholder="Paste article text..."),
53
- outputs=gr.Label(label="Prediction"),
54
- examples=[
55
- ["Breaking: Scientists discover chocolate prevents all diseases!"],
56
- ["Congress passes new infrastructure bill with bipartisan support"]
57
- ],
58
- title="Fake News Detector",
59
- description="Classifies news content using BERT",
60
- allow_flagging="never"
61
- ).launch()
 
1
+ from transformers import AutoModel, AutoTokenizer, AutoConfig
2
  import torch
3
+ import torch.nn as nn
4
 
5
+ # 1. Load base components
6
+ model_name = "KenLumod/ML-Fake-Real-News-Detector-Final"
7
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
8
+ config = AutoConfig.from_pretrained(model_name)
9
+
10
+ # 2. Load base BERT (without classification head)
11
+ bert = AutoModel.from_pretrained(model_name)
12
+
13
+ # 3. Add your custom classifier (must match training architecture)
14
+ class FakeNewsClassifier(nn.Module):
15
+ def __init__(self, bert_model):
16
  super().__init__()
17
+ self.bert = bert_model
18
+ self.classifier = nn.Sequential(
19
+ nn.Dropout(0.1),
20
+ nn.Linear(768, 512), # Match your hidden layer size
21
+ nn.ReLU(),
22
+ nn.Linear(512, config.num_labels), # Uses config's label count
23
+ nn.LogSoftmax(dim=1)
24
  )
25
 
26
  def forward(self, input_ids, attention_mask):
27
  outputs = self.bert(input_ids, attention_mask=attention_mask)
28
+ return self.classifier(outputs.last_hidden_state[:, 0, 🙂) # CLS token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ # 4. Create complete model
31
+ model = FakeNewsClassifier(bert).eval()