from flask import Flask, render_template, request, jsonify from datetime import datetime import os import time from langchain.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTemplate app = Flask(__name__) # Initialize AI client openai_api_key = os.environ.get("OPENAI_API_KEY") llm = ChatOpenAI( temperature=0, model_name="gpt-3.5-turbo", openai_api_key=openai_api_key ) # --- Scam Analyzer --- class ScamSignalVerifier: def __init__(self): self.llm = llm def ai_analyze_scam(self, text: str, url: str = None) -> dict: prompt = f""" You are a scam detection assistant. Analyze the following message and output strictly JSON with these fields: - risk_score: integer 0-100 - classification: "HIGH RISK", "MEDIUM RISK", "LOW RISK", or "SAFE" - red_flags: list of detected warning signs (keywords, urgent threats, links, personal info requests) - recommendations: list of safety steps - ai_insights: include confidence (0-100), scam_type (if applicable), and explanation Message: \"\"\"{text}\"\"\" URL: \"{url if url else 'None'}\" Check explicitly for: - Prize or Money Offer - Urgency / Threats - Request for Personal/Financial Info - Phishing Link / Suspicious URL - Suspicious Contact Info Calculate risk_score based on these factors: - 80-100: HIGH RISK - 50-79: MEDIUM RISK - 20-49: LOW RISK - 0-19: SAFE Return JSON only. """ try: response = self.llm.predict(prompt) import json return json.loads(response) except Exception as e: return { "risk_score": 0, "classification": "SAFE", "red_flags": [], "recommendations": ["Unable to analyze message, please check manually."], "ai_insights": { "available": True, "confidence": 0, "scam_type": "N/A", "explanation": f"AI analysis failed: {str(e)}" } } def analyze_message(self, text: str, url: str = None) -> dict: # Step 1: AI analysis ai_result = self.ai_analyze_scam(text, url) # Step 2: Prepare explanation object for frontend explanation = { 'risk_score': ai_result.get('risk_score', 0), 'classification': ai_result.get('classification', 'SAFE'), 'summary': f"Message classified as {ai_result.get('classification', 'SAFE')} with risk score {ai_result.get('risk_score', 0)}.", 'red_flags': ai_result.get('red_flags', []), 'recommendations': ai_result.get('recommendations', []), 'ai_insights': ai_result.get('ai_insights', {}) } # Simple report template explanation['report_template'] = f""" SCAM REPORT TEMPLATE: Subject: Reporting Suspicious Message/Scam Attempt Date Received: {datetime.now().strftime('%Y-%m-%d %H:%M')} Message Content: {text} URL: {url if url else 'N/A'} Red Flags: {', '.join(explanation['red_flags'])} Please investigate and take appropriate action. Best regards, [Your Name] """.strip() return { 'claims': {}, 'verification': {}, 'ai_analysis': ai_result, 'explanation': explanation, 'analysis_method': 'AI', 'timestamp': datetime.now().isoformat() } verifier = ScamSignalVerifier() # --- Flask Routes --- @app.route('/') def index(): return render_template('index.html') @app.route('/analyze', methods=['POST']) def analyze(): try: data = request.get_json() message_text = data.get('message', '').strip() message_url = data.get('url', '').strip() if not message_text and not message_url: return jsonify({'error': 'Please provide a message or URL'}), 400 time.sleep(0.3) # minor delay result = verifier.analyze_message(message_text, message_url if message_url else None) return jsonify(result) except Exception as e: return jsonify({'error': f'Analysis failed: {str(e)}'}), 500 @app.route('/health') def health(): ai_status = "available" if llm else "unavailable" api_key_present = "yes" if openai_api_key else "no" return jsonify({ 'status': 'healthy', 'ai_status': ai_status, 'api_key_present': api_key_present, 'timestamp': datetime.now().isoformat() }) if __name__ == '__main__': port = int(os.environ.get('PORT', 7860)) app.run(host='0.0.0.0', port=port, debug=False)