Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from transformers import pipeline | |
| import os | |
| # --- 1. SETUP & CONFIGURATION --- | |
| # Force CPU usage to avoid memory crashes on free tier | |
| os.environ['CUDA_VISIBLE_DEVICES'] = '-1' | |
| print("--- STARTING ELDERGUARD (HIGH ACCURACY) ---") | |
| # Load the LARGER, smarter AI model | |
| try: | |
| print("Loading Roberta-Spam Model (This may take a moment)...") | |
| # We use 'mshenoda/roberta-spam' which is ~500MB but much smarter | |
| classifier = pipeline("text-classification", model="mshenoda/roberta-spam", device=-1) | |
| print("Model loaded successfully!") | |
| except Exception as e: | |
| print(f"CRITICAL ERROR LOADING MODEL: {e}") | |
| classifier = None | |
| # --- 2. THE SAFE LIST ENGINE (The "Whitelist") --- | |
| # New Layer: Checks for known safe patterns to prevent False Positives | |
| def check_safelist(text): | |
| text = text.lower() | |
| # Safe Rule 1: Work Meetings (Zoom/Teams/Webex) | |
| # Context: "Urgent meeting" is common in business, so we allow it if the platform is named. | |
| if "meeting" in text and any(x in text for x in ["zoom", "teams", "webex", "google meet"]): | |
| return True, "✅ SAFE: This looks like a standard work meeting invitation." | |
| # Safe Rule 2: 2FA Verification Codes | |
| # Context: Security codes often use "urgent" language but are safe if from known providers. | |
| if "code" in text and any(x in text for x in ["verification", "verify"]) and \ | |
| any(x in text for x in ["google", "apple", "microsoft", "amazon"]): | |
| return True, "✅ SAFE: This appears to be a standard security verification code." | |
| return False, None | |
| # --- 3. THE RULE-BASED ENGINE (The "Expert" Layer) --- | |
| # Optimization: If rules catch the scam, we skip the heavy AI analysis. | |
| def check_rules(text): | |
| text = text.lower() | |
| # Rule 1: Delivery Scams (Moved to TOP to prevent misclassification) | |
| # Checks for specific delivery services + specific delivery issues | |
| if any(x in text for x in ["usps", "fedex", "delivery", "package", "warehouse"]) and \ | |
| any(x in text for x in ["incomplete", "address", "update", "link", "suspended", "tracking"]): | |
| return True, "⚠️ CAUTION: SCAM DETECTED\nReason: Fake delivery notification trying to steal info." | |
| # Rule 2: Prizes & Winnings | |
| if any(x in text for x in ["winner", "congrats", "won", "prize", "gift card", "lottery", "claim"]) and \ | |
| any(x in text for x in ["walmart", "amazon", "cash", "money"]): | |
| return True, "⚠️ CAUTION: SCAM DETECTED\nReason: Promises 'too good to be true' rewards." | |
| # Rule 3: Government & Legal Threats (Refined to reduce false positives) | |
| # Now requires BOTH an Entity (FBI/Police) AND a Threat (Arrest/Warrant) | |
| govt_entities = ["irs", "police", "fbi", "government", "law enforcement"] | |
| threat_words = ["warrant", "arrest", "lawsuit", "tax fraud", "legal action", "jail", "behind bars"] | |
| if any(entity in text for entity in govt_entities) and any(threat in text for threat in threat_words): | |
| return True, "⚠️ CAUTION: SCAM DETECTED\nReason: Pretends to be government/police to scare you." | |
| # Rule 4: Financial & Urgency | |
| if any(x in text for x in ["bank account", "verify your identity", "locked", "suspended", "unauthorized"]) and \ | |
| any(x in text for x in ["urgent", "immediately", "click here", "link", "login"]): | |
| return True, "⚠️ CAUTION: SCAM DETECTED\nReason: Uses fake banking threats to create panic." | |
| return False, None | |
| # --- 4. MAIN ANALYZER FUNCTION --- | |
| def analyze(message): | |
| if not message.strip(): | |
| return "Please enter a message." | |
| # STEP 0: Check Safe List (Whitelist) | |
| is_safe, safe_reason = check_safelist(message) | |
| if is_safe: | |
| return safe_reason + "\n(Confidence: 100% - Flagged by Safe Rules)" | |
| # STEP 1: Check Scam Rules (Blacklist) | |
| is_scam, reason = check_rules(message) | |
| if is_scam: | |
| return reason + "\n(Confidence: 100% - Flagged by Safety Rules)" | |
| # STEP 2: Ask the AI (General Detection) | |
| if classifier: | |
| try: | |
| result = classifier(message)[0] | |
| label = result['label'] | |
| score = int(result['score'] * 100) | |
| # This specific model uses "LABEL_1" for Scam | |
| if label == "LABEL_1": | |
| return f"⚠️ CAUTION: THIS LOOKS SUSPICIOUS.\nReason: The AI detected spam patterns in the writing style.\n(Confidence: {score}%)" | |
| else: | |
| return f"✅ SAFE: This message looks normal.\n(Confidence: {score}%)" | |
| except Exception as e: | |
| return f"Error with AI analysis: {e}" | |
| return "System Error: AI model failed to load." | |
| # --- 5. USER INTERFACE --- | |
| demo = gr.Interface( | |
| fn=analyze, | |
| inputs=gr.Textbox(lines=5, placeholder="Paste suspicious text here..."), | |
| outputs=gr.Textbox(lines=5, label="Analysis Result"), | |
| title="ElderGuard (High Accuracy)", | |
| description="Checks messages using a Hybrid System (Safe Rules + Scam Rules + Roberta AI)." | |
| ) | |
| if __name__ == "__main__": | |
| # Force server binding to prevent timeouts | |
| demo.launch(server_name="0.0.0.0", server_port=7860) |