Aishani03 commited on
Commit
2fa7bd3
Β·
verified Β·
1 Parent(s): b169320

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -0
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Fake News Generator & Detector.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1k_GVU6WO9Mggr87RxntJFq2S1M6R4dI0
8
+
9
+ # πŸ“° **Fake News Generator & Detector**
10
+
11
+ This educational and awareness-focused Generative AI application explores the dual power of AI in creating and detecting fake news. It allows users to generate fake news headlines based on a selected category (e.g., politics, tech), a subject or entity (e.g., Apple, Government), and number of headlines. It also provides a detection system where users can input a news snippet to check whether it is likely to be fake or real using a fine-tuned BERT model.
12
+
13
+ **The application is built using:**
14
+
15
+ Transformers library
16
+ (For GPT-2 based fake news generation and BERT-based fake news classification)
17
+
18
+ Gradio
19
+ (To create a clean, tabbed web interface for both generation and detection)
20
+
21
+ Google Colab / Python
22
+ (For backend development, model training/fine-tuning, and deployment)
23
+
24
+ **This project aims to:**
25
+
26
+ ✨ Demonstrate the capabilities and risks of large language models
27
+
28
+ πŸ” Raise awareness about misinformation in media
29
+
30
+ 🧠 Promote responsible AI development through practical exploration
31
+
32
+ This project showcases how AI can both contribute to and combat misinformation, serving as a tool for learning, experimentation, and ethics in AI."""
33
+
34
+ # app.py
35
+
36
+ import torch
37
+ import torch.nn.functional as F
38
+ from transformers import (
39
+ GPT2LMHeadModel,
40
+ GPT2Tokenizer,
41
+ AutoTokenizer,
42
+ AutoModelForSequenceClassification
43
+ )
44
+ import gradio as gr
45
+
46
+ # Device setup
47
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
48
+
49
+ # Load GPT-2 for Fake News Generation
50
+ gpt2_tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
51
+ gpt2_model = GPT2LMHeadModel.from_pretrained("gpt2").to(device)
52
+ gpt2_model.eval()
53
+
54
+ # Headline generation function
55
+ def generate_fake_headlines(category, subject, num_headlines=1, max_length=20):
56
+ headlines = []
57
+ for i in range(num_headlines):
58
+ prompt = f"Write a fake {category} news headline about {subject}:\n"
59
+ input_ids = gpt2_tokenizer.encode(prompt, return_tensors='pt').to(device)
60
+
61
+ output = gpt2_model.generate(
62
+ input_ids,
63
+ max_length=len(input_ids[0]) + max_length,
64
+ temperature=0.9,
65
+ top_p=0.9,
66
+ do_sample=True,
67
+ pad_token_id=gpt2_tokenizer.eos_token_id,
68
+ no_repeat_ngram_size=2,
69
+ early_stopping=True
70
+ )
71
+
72
+ generated_text = gpt2_tokenizer.decode(output[0], skip_special_tokens=True)
73
+ headline = generated_text.replace(prompt, "").strip().split("\n")[0]
74
+ headlines.append(headline)
75
+ return headlines
76
+
77
+ # Gradio function wrapper
78
+ def gradio_fake_news_generator(category, subject, num_headlines):
79
+ try:
80
+ num = int(num_headlines)
81
+ if num <= 0 or num > 10:
82
+ return "Please enter a number between 1 and 10."
83
+ except:
84
+ return "Invalid input for number of headlines."
85
+
86
+ headlines = generate_fake_headlines(category, subject, num)
87
+ return "\n".join([f"{i+1}. {h}" for i, h in enumerate(headlines)])
88
+
89
+ # Load BERT model for fake news detection (no token required)
90
+ bert_tokenizer = AutoTokenizer.from_pretrained("Pulk17/Fake-News-Detection")
91
+ bert_model = AutoModelForSequenceClassification.from_pretrained("Pulk17/Fake-News-Detection").to(device)
92
+ bert_model.eval()
93
+
94
+ # Detection function
95
+ def detect_fake_news(text):
96
+ inputs = bert_tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512).to(device)
97
+ outputs = bert_model(**inputs)
98
+ probs = F.softmax(outputs.logits, dim=1)
99
+ predicted_class = torch.argmax(probs, dim=1).item()
100
+ confidence = torch.max(probs).item()
101
+ label = "FAKE πŸŸ₯" if predicted_class == 0 else "REAL 🟩"
102
+ return f"Prediction: {label} ({confidence*100:.2f}% confidence)"
103
+
104
+ # Gradio interfaces
105
+ generator_interface = gr.Interface(
106
+ fn=gradio_fake_news_generator,
107
+ inputs=[
108
+ gr.Textbox(label="News Category (e.g., politics, tech)"),
109
+ gr.Textbox(label="Main Subject / Entity (e.g., Apple, Government)"),
110
+ gr.Textbox(label="Number of Headlines (1-10)")
111
+ ],
112
+ outputs=gr.Textbox(label="Generated Fake News Headlines"),
113
+ title="πŸ“° Fake News Generator",
114
+ description="Generate fake news headlines using GPT-2"
115
+ )
116
+
117
+ detector_interface = gr.Interface(
118
+ fn=detect_fake_news,
119
+ inputs=gr.Textbox(lines=5, label="Enter full news text"),
120
+ outputs=gr.Textbox(label="Fake News Detection Result"),
121
+ title="πŸ” Fake News Detector",
122
+ description="Detect whether a news article is FAKE or REAL using BERT"
123
+ )
124
+
125
+ # Combine both interfaces
126
+ gr.TabbedInterface([generator_interface, detector_interface],
127
+ tab_names=["πŸ“° Generator", "πŸ” Detector"]).launch()
128
+