Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,20 +1,52 @@
|
|
1 |
-
import os
|
2 |
-
import sys
|
3 |
-
|
4 |
import gradio as gr
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch
|
3 |
+
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from transformers import BertTokenizer, BertForSequenceClassification
|
6 |
+
|
7 |
+
|
8 |
+
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
9 |
+
model.load_state_dict(torch.load('/content/Fake-news-detection-bert-based-uncased/model_after_train.pt', map_location=torch.device('cpu')), strict=False)
|
10 |
+
model.eval()
|
11 |
+
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
|
12 |
+
|
13 |
+
|
14 |
+
def preprocess_text(text):
|
15 |
+
parts = []
|
16 |
+
|
17 |
+
text_len = len(text.split(' '))
|
18 |
+
delta = 300
|
19 |
+
max_parts = 5
|
20 |
+
nb_cuts = int(text_len / delta)
|
21 |
+
nb_cuts = min(nb_cuts, max_parts)
|
22 |
+
|
23 |
+
|
24 |
+
for i in range(nb_cuts + 1):
|
25 |
+
text_part = ' '.join(text.split(' ')[i * delta: (i + 1) * delta])
|
26 |
+
parts.append(tokenizer.encode(text_part, return_tensors="pt", max_length=500).to(device))
|
27 |
+
|
28 |
+
return parts
|
29 |
+
|
30 |
+
def test(text):
|
31 |
+
text_parts = preprocess_text(text)
|
32 |
+
overall_output = torch.zeros((1,2)).to(device)
|
33 |
+
try:
|
34 |
+
for part in text_parts:
|
35 |
+
if len(part) > 0:
|
36 |
+
overall_output += model(part.reshape(1, -1))[0]
|
37 |
+
except RuntimeError:
|
38 |
+
print("GPU out of memory, skipping this entry.")
|
39 |
+
|
40 |
+
overall_output = F.softmax(overall_output[0], dim=-1)
|
41 |
+
|
42 |
+
value, result = overall_output.max(0)
|
43 |
+
|
44 |
+
term = "fake"
|
45 |
+
if result.item() == 0:
|
46 |
+
term = "real"
|
47 |
+
|
48 |
+
return term + " at " + str(int(value.item()*100)) + " %"
|
49 |
+
|
50 |
+
|
51 |
+
iface = gr.Interface(fn=test, inputs="text", outputs="text")
|
52 |
+
iface.launch()
|