Nuhin23 commited on
Commit
6cac6cb
·
verified ·
1 Parent(s): 7eefeb4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -66
app.py CHANGED
@@ -1,82 +1,76 @@
1
- import gradio as gr
 
 
 
 
 
2
  from transformers import pipeline
 
 
 
3
 
4
- # Load a better model for Bangla & English fake news detection
 
5
  classifier = pipeline(
6
  "text-classification",
7
- model="armansakif/bengali-fake-news",
8
- tokenizer="armansakif/bengali-fake-news"
9
  )
10
 
11
  def predict_news(text):
12
- if text.strip() == "":
13
- return "<span style='color:red;'>⚠️ Please enter news text</span>", 0
14
-
15
- # Run classification
16
- try:
17
- result = classifier(text)[0]
18
- except Exception as e:
19
- return f"<span style='color:red;'>Error: {str(e)}</span>", 0
 
 
 
20
 
21
- label = result["label"]
22
- confidence = round(result["score"] * 100, 2)
23
-
24
- # Map labels to understandable text
25
- if label.upper() in ["LABEL_0", "fake", "Fake"]:
26
- display_label = "🟥 Fake News"
27
- color = "red"
28
  else:
29
- display_label = "🟩 Real News"
30
- color = "green"
31
-
32
- html_output = f"""
33
- <div style="
34
- font-size: 28px;
35
- font-weight: bold;
36
- color: {color};
37
- text-align: center;
38
- padding: 20px;
39
- ">
40
- {display_label} — {confidence}%
41
- </div>
42
- """
43
 
44
- return html_output, confidence
 
 
 
45
 
46
- # ================= UI LAYOUT =================
47
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- gr.Markdown(
50
- """
51
- # 📰 Fake News Detection System
52
- **AI‑powered fake vs real news classifier (English & Bangla)**
53
- """
54
- )
55
-
56
- with gr.Row():
57
- with gr.Column(scale=2):
58
- news_input = gr.Textbox(
59
- label="Enter News Text",
60
- placeholder="Paste English or Bangla news here...",
61
- lines=10
62
- )
63
- submit_btn = gr.Button("Submit", variant="primary")
64
-
65
- with gr.Column(scale=1):
66
- prediction_output = gr.HTML(label="Prediction")
67
- confidence_bar = gr.Slider(
68
- minimum=0,
69
- maximum=100,
70
- label="Confidence Percentage",
71
- interactive=False
72
- )
73
 
74
- submit_btn.click(
75
- fn=predict_news,
76
- inputs=news_input,
77
- outputs=[prediction_output, confidence_bar]
78
- )
79
 
80
- demo.launch()
81
 
82
 
 
1
+ # ===============================
2
+ # Fake/Real News Detection App
3
+ # Supports English and Bangla
4
+ # ===============================
5
+
6
+ import gradio as gr
7
  from transformers import pipeline
8
+ import matplotlib.pyplot as plt
9
+ import io
10
+ import base64
11
 
12
+ # Load the model (Hugging Face)
13
+ # Make sure you have internet and the model exists on HF
14
  classifier = pipeline(
15
  "text-classification",
16
+ model="mrm8488/bert-tiny-finetuned-fake-news-detection",
17
+ return_all_scores=True
18
  )
19
 
20
  def predict_news(text):
21
+ if not text.strip():
22
+ return "<span style='color:red;'>Please enter news text!</span>", None
23
+
24
+ # Get prediction
25
+ results = classifier(text)[0] # List of dicts with label & score
26
+ # Sort to get highest probability
27
+ results = sorted(results, key=lambda x: x['score'], reverse=True)
28
+
29
+ label = results[0]['label']
30
+ score = results[0]['score']
31
+ percent = round(score * 100, 2)
32
 
33
+ # Color coding
34
+ if label.lower() == "real":
35
+ output_text = f"<span style='color:green;'>Real {percent}%</span>"
 
 
 
 
36
  else:
37
+ output_text = f"<span style='color:red;'>Fake {percent}%</span>"
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # Generate chart
40
+ labels = [r['label'] for r in results]
41
+ scores = [r['score']*100 for r in results]
42
+ colors = ['green' if l.lower() == 'real' else 'red' for l in labels]
43
 
44
+ fig, ax = plt.subplots(figsize=(4,2))
45
+ ax.bar(labels, scores, color=colors)
46
+ ax.set_ylim([0, 100])
47
+ ax.set_ylabel('Confidence (%)')
48
+ ax.set_title('Prediction Confidence')
49
+
50
+ # Convert chart to image for Gradio
51
+ buf = io.BytesIO()
52
+ plt.tight_layout()
53
+ plt.savefig(buf, format='png')
54
+ buf.seek(0)
55
+ chart_base64 = base64.b64encode(buf.getvalue()).decode("utf-8")
56
+ chart_html = f'<img src="data:image/png;base64,{chart_base64}"/>'
57
+
58
+ return output_text, chart_html
59
 
60
+ # Gradio Interface
61
+ app = gr.Interface(
62
+ fn=predict_news,
63
+ inputs=gr.Textbox(lines=6, placeholder="Enter news text in English or Bangla..."),
64
+ outputs=[
65
+ gr.HTML(label="Prediction"),
66
+ gr.HTML(label="Confidence Chart")
67
+ ],
68
+ title="Fake/Real News Detection",
69
+ description="Enter news text in English or Bangla and see if it's Fake or Real with confidence."
70
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ # Launch the app
73
+ app.launch()
 
 
 
74
 
 
75
 
76