Spaces:
Running
Running
File size: 7,523 Bytes
f36a10a 94a65e4 f36a10a 94a65e4 f36a10a 5e58061 f36a10a 94a65e4 f36a10a 207a2e4 94a65e4 207a2e4 94a65e4 207a2e4 1a2b17f 94a65e4 f36a10a 5e58061 f36a10a 207a2e4 f36a10a 207a2e4 f36a10a 94a65e4 f36a10a 207a2e4 f36a10a 207a2e4 94a65e4 207a2e4 94a65e4 f36a10a 207a2e4 116a946 f36a10a 207a2e4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification, DebertaV2Tokenizer
import networkx as nx
import spacy
import pickle
import google.generativeai as genai
import json
import os
import dotenv
import plotly.graph_objects as go
# Load environment variables
dotenv.load_dotenv()
def load_models():
"""Load all required ML models"""
nlp = spacy.load("en_core_web_sm")
model_path = "./results/checkpoint-753"
tokenizer = DebertaV2Tokenizer.from_pretrained('microsoft/deberta-v3-small')
model = AutoModelForSequenceClassification.from_pretrained(model_path)
model.eval()
return nlp, tokenizer, model
def load_knowledge_graph():
"""Load and initialize knowledge graph"""
graph_path = "./knowledge_graph_final.pkl"
with open(graph_path, 'rb') as f:
graph_data = pickle.load(f)
knowledge_graph = nx.DiGraph()
knowledge_graph.add_nodes_from(graph_data['nodes'].items())
for u, edges in graph_data['edges'].items():
for v, data in edges.items():
knowledge_graph.add_edge(u, v, **data)
return knowledge_graph
class KnowledgeGraphBuilder:
def __init__(self):
self.knowledge_graph = nx.DiGraph()
def update_knowledge_graph(self, text, is_real, nlp):
entities = extract_entities(text, nlp)
for entity, entity_type in entities:
if not self.knowledge_graph.has_node(entity):
self.knowledge_graph.add_node(
entity,
type=entity_type,
real_count=1 if is_real else 0,
fake_count=0 if is_real else 1
)
else:
if is_real:
self.knowledge_graph.nodes[entity]['real_count'] += 1
else:
self.knowledge_graph.nodes[entity]['fake_count'] += 1
for i, (entity1, _) in enumerate(entities):
for entity2, _ in entities[i+1:]:
if not self.knowledge_graph.has_edge(entity1, entity2):
self.knowledge_graph.add_edge(
entity1,
entity2,
weight=1,
is_real=is_real
)
else:
self.knowledge_graph[entity1][entity2]['weight'] += 1
def setup_gemini():
"""Initialize Gemini model"""
genai.configure(api_key=os.getenv("GEMINI_API"))
model = genai.GenerativeModel('gemini-pro')
return model
def predict_with_model(text, tokenizer, model):
"""Make predictions using the ML model"""
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
with torch.no_grad():
outputs = model(**inputs)
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
predicted_label = torch.argmax(probabilities, dim=-1).item()
confidence = probabilities[0][predicted_label].item() * 100
return "FAKE" if predicted_label == 1 else "REAL", confidence
def extract_entities(text, nlp):
"""Extract named entities from text"""
doc = nlp(text)
entities = [(ent.text, ent.label_) for ent in doc.ents]
return entities
def update_knowledge_graph(text, is_real, knowledge_graph, nlp):
"""Update knowledge graph with new information"""
entities = extract_entities(text, nlp)
for entity, entity_type in entities:
if not knowledge_graph.has_node(entity):
knowledge_graph.add_node(
entity,
type=entity_type,
real_count=1 if is_real else 0,
fake_count=0 if is_real else 1
)
else:
if is_real:
knowledge_graph.nodes[entity]['real_count'] += 1
else:
knowledge_graph.nodes[entity]['fake_count'] += 1
for i, (entity1, _) in enumerate(entities):
for entity2, _ in entities[i+1:]:
if not knowledge_graph.has_edge(entity1, entity2):
knowledge_graph.add_edge(
entity1,
entity2,
weight=1,
is_real=is_real
)
else:
knowledge_graph[entity1][entity2]['weight'] += 1
def predict_with_knowledge_graph(text, knowledge_graph, nlp):
"""Make predictions using the knowledge graph"""
entities = extract_entities(text, nlp)
real_score = 0
fake_score = 0
for entity, _ in entities:
if knowledge_graph.has_node(entity):
real_count = knowledge_graph.nodes[entity].get('real_count', 0)
fake_count = knowledge_graph.nodes[entity].get('fake_count', 0)
total = real_count + fake_count
if total > 0:
real_score += real_count / total
fake_score += fake_count / total
total_score = real_score + fake_score
if total_score == 0:
return "UNCERTAIN", 50.0
if real_score > fake_score:
confidence = (real_score / total_score) * 100
return "REAL", confidence
else:
confidence = (fake_score / total_score) * 100
return "FAKE", confidence
def analyze_content_gemini(model, text):
"""Analyze content using Gemini model"""
prompt = f"""Analyze this news text and return a JSON object with the following exact structure:
{{
"gemini_analysis": {{
"predicted_classification": "Real or Fake",
"confidence_score": "0-100",
"reasoning": ["point1", "point2"]
}},
"text_classification": {{
"category": "",
"writing_style": "Formal/Informal/Clickbait",
"target_audience": "",
"content_type": "news/opinion/editorial"
}},
"sentiment_analysis": {{
"primary_emotion": "",
"emotional_intensity": "1-10",
"sensationalism_level": "High/Medium/Low",
"bias_indicators": ["bias1", "bias2"],
"tone": {{"formality": "formal/informal", "style": "Professional/Emotional/Neutral"}},
"emotional_triggers": ["trigger1", "trigger2"]
}},
"entity_recognition": {{
"source_credibility": "High/Medium/Low",
"people": ["person1", "person2"],
"organizations": ["org1", "org2"],
"locations": ["location1", "location2"],
"dates": ["date1", "date2"],
"statistics": ["stat1", "stat2"]
}},
"context": {{
"main_narrative": "",
"supporting_elements": ["element1", "element2"],
"key_claims": ["claim1", "claim2"],
"narrative_structure": ""
}},
"fact_checking": {{
"verifiable_claims": ["claim1", "claim2"],
"evidence_present": "Yes/No",
"fact_check_score": "0-100"
}}
}}
Analyze this text and return only the JSON response: {text}"""
response = model.generate_content(prompt)
try:
cleaned_text = response.text.strip()
if cleaned_text.startswith('```json'):
cleaned_text = cleaned_text[7:-3]
return json.loads(cleaned_text)
except json.JSONDecodeError:
return {
"gemini_analysis": {
"predicted_classification": "UNCERTAIN",
"confidence_score": "50",
"reasoning": ["Analysis failed to generate valid JSON"]
}
}
|