Spaces:
Sleeping
Sleeping
| import json | |
| import os | |
| import re | |
| class ReputationEngine: | |
| def __init__(self, db_path=None): | |
| if not db_path: | |
| db_path = os.path.join(os.path.dirname(__file__), 'data', 'source_reputation.json') | |
| self.db_path = db_path | |
| self.reputation_data = {} | |
| self.load_db() | |
| def load_db(self): | |
| if os.path.exists(self.db_path): | |
| with open(self.db_path, 'r') as f: | |
| self.reputation_data = json.load(f) | |
| else: | |
| print(f"Warning: Reputation database not found at {self.db_path}") | |
| def get_source_stats(self, identifier): | |
| """ | |
| identifier can be a speaker name (e.g. 'john-mccain') | |
| or a domain (e.g. 'reuters.com'). | |
| """ | |
| # Clean identifier | |
| slug = identifier.lower().strip().replace(' ', '-') | |
| # Try direct match | |
| if slug in self.reputation_data: | |
| return self.reputation_data[slug] | |
| # Try regex search for domains in URLs/metadata | |
| for key in self.reputation_data: | |
| if key in slug or slug in key: | |
| return self.reputation_data[key] | |
| return None | |
| def analyze_source(self, text, speaker=None, context=None): | |
| """ | |
| Returns a dictionary with trust_score, bias, and label. | |
| """ | |
| target = speaker or "unknown" | |
| stats = self.get_source_stats(target) | |
| # Fallback: check context for domain-like strings | |
| if not stats and context: | |
| domains = re.findall(r'([a-z0-9]+(?:-[a-z0-9]+)*\.[a-z]{2,})', context.lower()) | |
| for d in domains: | |
| stats = self.get_source_stats(d) | |
| if stats: break | |
| if stats: | |
| score = stats.get('trust_score', 0) | |
| party = stats.get('metadata', {}).get('party', 'unknown').lower() | |
| # Simple bias mapping | |
| bias = "Center" | |
| if 'republican' in party: bias = "Right-Leaning" | |
| elif 'democrat' in party: bias = "Left-Leaning" | |
| elif 'libertarian' in party: bias = "Libertarian" | |
| # Labeling | |
| label = "Unknown" | |
| if score >= 90: label = "EXCEPTIONAL" | |
| elif score >= 75: label = "HIGHLY RELIABLE" | |
| elif score >= 50: label = "MIXED RECORD" | |
| elif score >= 30: label = "QUESTIONABLE" | |
| else: label = "LOW CREIBILITY" | |
| return { | |
| "source_name": stats.get('name', target), | |
| "trust_score": score, | |
| "bias": bias, | |
| "veracity_label": label, | |
| "total_history": stats.get('total_claims', 0), | |
| "counts": stats.get('counts', {}) | |
| } | |
| return { | |
| "source_name": target, | |
| "trust_score": 0, | |
| "bias": "Undetermined", | |
| "veracity_label": "NO DATA", | |
| "total_history": 0, | |
| "counts": {} | |
| } | |