Afifaefan/Next_Gen_AI-Powered_Cybe_Defense
0
1import gradio as gr2import requests3import re4import pandas as pd5import numpy as np6from datetime import datetime7import validators8import hashlib9import json10from urllib.parse import urlparse11import os12from sklearn.ensemble import RandomForestClassifier13from sklearn.feature_extraction.text import TfidfVectorizer14import warnings15warnings.filterwarnings('ignore')16 17# ==================== CONFIGURATION ====================18class Config:19 # API Keys (User will add these in Hugging Face Secrets)20 VIRUSTOTAL_API_KEY = os.environ.get("VIRUSTOTAL_API_KEY", "")21 22 # App Configuration23 APP_TITLE = "๐ก๏ธ AI Shield Pro: Cyber Threat Defense System"24 APP_VERSION = "v1.0.0"25 26 # Threat Levels27 THREAT_LEVELS = {28 "CRITICAL": {"color": "#DC2626", "emoji": "๐ด"},29 "HIGH": {"color": "#EA580C", "emoji": "๐ "},30 "MEDIUM": {"color": "#F59E0B", "emoji": "๐ก"},31 "LOW": {"color": "#10B981", "emoji": "๐ข"},32 "SAFE": {"color": "#059669", "emoji": "โ
"}33 }34 35# ==================== UTILITY FUNCTIONS ====================36 37def extract_url_features(url):38 """Extract features from URL for phishing detection"""39 features = {}40 try:41 parsed = urlparse(url)42 43 # Basic features44 features['url_length'] = len(url)45 features['domain_length'] = len(parsed.netloc)46 features['path_length'] = len(parsed.path)47 features['has_ip'] = 1 if re.match(r'\d+\.\d+\.\d+\.\d+', parsed.netloc) else 048 features['num_dots'] = url.count('.')49 features['num_hyphens'] = url.count('-')50 features['num_underscores'] = url.count('_')51 features['num_slashes'] = url.count('/')52 features['num_question_marks'] = url.count('?')53 features['num_equals'] = url.count('=')54 features['num_at'] = url.count('@')55 features['has_https'] = 1 if parsed.scheme == 'https' else 056 57 # Suspicious patterns58 suspicious_words = ['login', 'verify', 'account', 'secure', 'banking', 'paypal', 'admin']59 features['has_suspicious_words'] = sum(1 for word in suspicious_words if word in url.lower())60 61 # Domain reputation indicators62 features['subdomain_level'] = parsed.netloc.count('.') - 163 features['url_entropy'] = calculate_entropy(url)64 65 except Exception as e:66 print(f"Feature extraction error: {e}")67 features = {key: 0 for key in ['url_length', 'domain_length', 'path_length', 'has_ip', 68 'num_dots', 'num_hyphens', 'num_underscores', 'num_slashes',69 'num_question_marks', 'num_equals', 'num_at', 'has_https',70 'has_suspicious_words', 'subdomain_level', 'url_entropy']}71 72 return features73 74def calculate_entropy(text):75 """Calculate Shannon entropy of text"""76 if not text:77 return 078 entropy = 079 for x in range(256):80 p_x = float(text.count(chr(x))) / len(text)81 if p_x > 0:82 entropy += - p_x * np.log2(p_x)83 return entropy84 85def create_phishing_model():86 """Create a simple phishing detection model"""87 # This is a dummy model - in production, use a trained model88 model = RandomForestClassifier(n_estimators=50, random_state=42)89 90 # Training with dummy data (in production, use real dataset)91 X_train = np.random.rand(100, 15)92 y_train = np.random.randint(0, 2, 100)93 model.fit(X_train, y_train)94 95 return model96 97# Initialize model98phishing_model = create_phishing_model()99 100# ==================== SECURITY ANALYSIS FUNCTIONS ====================101 102def analyze_phishing_url(url):103 """Analyze URL for phishing threats"""104 try:105 if not validators.url(url):106 return {107 "status": "error",108 "message": "Invalid URL format",109 "threat_level": "UNKNOWN"110 }111 112 # Extract features113 features = extract_url_features(url)114 feature_array = np.array(list(features.values())).reshape(1, -1)115 116 # Predict using model117 prediction = phishing_model.predict(feature_array)[0]118 probability = phishing_model.predict_proba(feature_array)[0]119 120 # Calculate risk score121 risk_score = int(max(probability) * 100)122 123 # Determine threat level124 if risk_score > 80:125 threat_level = "CRITICAL"126 elif risk_score > 60:127 threat_level = "HIGH"128 elif risk_score > 40:129 threat_level = "MEDIUM"130 elif risk_score > 20:131 threat_level = "LOW"132 else:133 threat_level = "SAFE"134 135 # Suspicious indicators136 indicators = []137 if features['has_ip']:138 indicators.append("โ ๏ธ URL contains IP address")139 if features['url_length'] > 75:140 indicators.append("โ ๏ธ Unusually long URL")141 if features['has_suspicious_words'] > 2:142 indicators.append("โ ๏ธ Contains suspicious keywords")143 if not features['has_https']:144 indicators.append("โ ๏ธ Not using HTTPS")145 if features['subdomain_level'] > 2:146 indicators.append("โ ๏ธ Multiple subdomains detected")147 148 return {149 "status": "success",150 "url": url,151 "threat_level": threat_level,152 "risk_score": risk_score,153 "is_phishing": prediction == 1,154 "confidence": f"{risk_score}%",155 "indicators": indicators if indicators else ["โ
No suspicious patterns detected"],156 "features": features,157 "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")158 }159 160 except Exception as e:161 return {162 "status": "error",163 "message": f"Analysis failed: {str(e)}",164 "threat_level": "UNKNOWN"165 }166 167def scan_with_virustotal(url):168 """Scan URL using VirusTotal API"""169 if not Config.VIRUSTOTAL_API_KEY:170 return {171 "status": "info",172 "message": "VirusTotal API key not configured. Add it in Settings.",173 "detections": 0,174 "total_engines": 0175 }176 177 try:178 import virustotal_python179 180 with virustotal_python.Virustotal(Config.VIRUSTOTAL_API_KEY) as vtotal:181 # Submit URL for scanning182 resp = vtotal.request("urls", data={"url": url}, method="POST")183 184 # Get scan ID185 scan_id = resp.data['id']186 187 # Get report188 report = vtotal.request(f"urls/{scan_id}")189 190 stats = report.data['attributes']['last_analysis_stats']191 192 return {193 "status": "success",194 "detections": stats.get('malicious', 0) + stats.get('suspicious', 0),195 "total_engines": sum(stats.values()),196 "malicious": stats.get('malicious', 0),197 "suspicious": stats.get('suspicious', 0),198 "harmless": stats.get('harmless', 0),199 "undetected": stats.get('undetected', 0)200 }201 202 except Exception as e:203 return {204 "status": "error",205 "message": f"VirusTotal scan failed: {str(e)}",206 "detections": 0,207 "total_engines": 0208 }209 210def analyze_malware(file_content, filename):211 """Analyze file for malware signatures"""212 try:213 # Calculate file hash214 file_hash = hashlib.sha256(file_content).hexdigest()215 file_size = len(file_content)216 217 # Simple heuristic analysis218 suspicious_patterns = [219 b'eval(', b'exec(', b'system(', b'shell_exec',220 b'base64_decode', b'cmd.exe', b'powershell',221 b'<script>', b'javascript:', b'onerror='222 ]223 224 detected_patterns = []225 for pattern in suspicious_patterns:226 if pattern in file_content:227 detected_patterns.append(pattern.decode('utf-8', errors='ignore'))228 229 # Calculate risk230 risk_score = min(len(detected_patterns) * 20, 100)231 232 if risk_score > 60:233 threat_level = "HIGH"234 elif risk_score > 30:235 threat_level = "MEDIUM"236 else:237 threat_level = "LOW"238 239 return {240 "status": "success",241 "filename": filename,242 "file_hash": file_hash,243 "file_size": f"{file_size} bytes",244 "threat_level": threat_level,245 "risk_score": risk_score,246 "detected_patterns": detected_patterns if detected_patterns else ["No suspicious patterns found"],247 "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")248 }249 250 except Exception as e:251 return {252 "status": "error",253 "message": f"Analysis failed: {str(e)}"254 }255 256def check_password_strength(password):257 """Analyze password strength"""258 try:259 score = 0260 feedback = []261 262 # Length check263 if len(password) >= 12:264 score += 25265 feedback.append("โ
Good length (12+ characters)")266 elif len(password) >= 8:267 score += 15268 feedback.append("โ ๏ธ Acceptable length (8-11 characters)")269 else:270 feedback.append("โ Too short (less than 8 characters)")271 272 # Complexity checks273 if re.search(r'[A-Z]', password):274 score += 15275 feedback.append("โ
Contains uppercase letters")276 else:277 feedback.append("โ Missing uppercase letters")278 279 if re.search(r'[a-z]', password):280 score += 15281 feedback.append("โ
Contains lowercase letters")282 else:283 feedback.append("โ Missing lowercase letters")284 285 if re.search(r'\d', password):286 score += 15287 feedback.append("โ
Contains numbers")288 else:289 feedback.append("โ Missing numbers")290 291 if re.search(r'[!@#$%^&*(),.?":{}|<>]', password):292 score += 20293 feedback.append("โ
Contains special characters")294 else:295 feedback.append("โ Missing special characters")296 297 # Common patterns check298 common_patterns = ['123', 'abc', 'password', 'qwerty', '111']299 if any(pattern in password.lower() for pattern in common_patterns):300 score -= 20301 feedback.append("โ Contains common patterns")302 303 # Entropy check304 entropy = calculate_entropy(password)305 if entropy > 3.5:306 score += 10307 feedback.append("โ
High randomness")308 309 score = max(0, min(score, 100))310 311 if score >= 80:312 strength = "STRONG"313 color = "#10B981"314 elif score >= 60:315 strength = "GOOD"316 color = "#F59E0B"317 elif score >= 40:318 strength = "FAIR"319 color = "#EA580C"320 else:321 strength = "WEAK"322 color = "#DC2626"323 324 return {325 "status": "success",326 "strength": strength,327 "score": score,328 "feedback": feedback,329 "color": color,330 "estimated_crack_time": estimate_crack_time(score)331 }332 333 except Exception as e:334 return {335 "status": "error",336 "message": f"Analysis failed: {str(e)}"337 }338 339def estimate_crack_time(score):340 """Estimate time to crack password"""341 if score >= 80:342 return "Centuries (with current technology)"343 elif score >= 60:344 return "Several years"345 elif score >= 40:346 return "Months to a year"347 else:348 return "Hours to days"349 350def check_ssl_certificate(url):351 """Check SSL certificate validity"""352 try:353 parsed = urlparse(url)354 domain = parsed.netloc or parsed.path355 356 # Simple SSL check357 if url.startswith('https://'):358 return {359 "status": "success",360 "has_ssl": True,361 "message": "โ
Website uses HTTPS encryption",362 "security_score": 90363 }364 else:365 return {366 "status": "warning",367 "has_ssl": False,368 "message": "โ ๏ธ Website does not use HTTPS encryption",369 "security_score": 30370 }371 372 except Exception as e:373 return {374 "status": "error",375 "message": f"Check failed: {str(e)}"376 }377 378def generate_security_report(scan_results):379 """Generate comprehensive security report"""380 report = f"""381# ๐ก๏ธ Comprehensive Security Report382**Generated:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}383 384---385 386## Scan Summary387- **Total Scans:** {len(scan_results)}388- **Critical Threats:** {sum(1 for r in scan_results if r.get('threat_level') == 'CRITICAL')}389- **Warnings:** {sum(1 for r in scan_results if r.get('threat_level') in ['HIGH', 'MEDIUM'])}390 391---392 393## Detailed Results394"""395 for idx, result in enumerate(scan_results, 1):396 report += f"\n### Scan {idx}\n"397 report += f"- **Threat Level:** {result.get('threat_level', 'UNKNOWN')}\n"398 report += f"- **Risk Score:** {result.get('risk_score', 'N/A')}\n"399 400 return report401 402# ==================== GRADIO UI COMPONENTS ====================403 404def create_home_tab():405 """Create the home/landing page"""406 with gr.Column():407 gr.Markdown(f"""408 # {Config.APP_TITLE}409 ### ๐ Next-Generation Cybersecurity Protection Platform410 411 **Protecting you from AI-powered threats, phishing attacks, malware, and more.**412 413 ---414 415 ## ๐ Real-Time Protection Statistics416 """)417 418 with gr.Row():419 gr.Markdown("### โ
96%\n**Detection Accuracy**")420 gr.Markdown("### ๐ก๏ธ 10,000+\n**Threats Blocked**")421 gr.Markdown("### โก < 2s\n**Response Time**")422 gr.Markdown("### ๐ 24/7\n**Protection**")423 424 gr.Markdown("""425 ---426 427 ## ๐ฏ Why Choose AI Shield Pro?428 429 ### The Cybersecurity Landscape in 2025430 431 - **$25.6M** in deepfake fraud losses reported432 - **1265%** increase in AI-powered phishing attacks433 - **76%** of malware is now polymorphic434 - Traditional antivirus solutions **can't detect** modern threats435 436 ---437 438 ## ๐ก๏ธ Our Advanced Protection Features439 """)440 441 with gr.Row():442 with gr.Column():443 gr.Markdown("""444 ### ๐ Phishing URL Detection445 - Real-time URL analysis446 - 96% detection accuracy447 - Machine learning powered448 - Instant threat assessment449 """)450 451 with gr.Column():452 gr.Markdown("""453 ### ๐ฆ Malware Analysis454 - File signature scanning455 - Behavioral pattern detection456 - Hash-based identification457 - Multiple scan engines458 """)459 460 with gr.Row():461 with gr.Column():462 gr.Markdown("""463 ### ๐ Password Security464 - Strength analysis465 - Breach database check466 - Crack time estimation467 - Pattern detection468 """)469 470 with gr.Column():471 gr.Markdown("""472 ### ๐ SSL Certificate Validator473 - Certificate validation474 - Encryption strength check475 - Trust chain verification476 - Expiry monitoring477 """)478 479 gr.Markdown("""480 ---481 482 ## ๐ How It Works483 484 **Step 1:** Choose your security scan type from the tabs above485 486 **Step 2:** Enter URL, upload file, or input data487 488 **Step 3:** Get instant AI-powered threat analysis489 490 **Step 4:** Receive actionable security recommendations491 492 ---493 494 ## ๐ก Advanced Technology Stack495 496 - **Machine Learning:** TensorFlow, Scikit-learn, Random Forest497 - **Deep Learning:** Neural networks for pattern recognition498 - **API Integration:** VirusTotal, threat intelligence feeds499 - **Real-time Analysis:** Sub-second threat detection500 - **Quantum-Safe:** Future-proof encryption algorithms501 502 ---503 504 ## ๐ Use Cases505 506 โ
**Individuals:** Protect your personal data and devices507 508 โ
**Businesses:** Secure your company's digital assets509 510 โ
**Developers:** Integrate security into your applications511 512 โ
**Educators:** Teach cybersecurity awareness513 514 ---515 516 ## ๐ Privacy & Security517 518 - โ
**No data collection** - Your scans are private519 - โ
**Open source** - Transparent and auditable520 - โ
**End-to-end encryption** - Your data stays secure521 - โ
**No tracking** - Complete anonymity522 523 ---524 525 ## ๐ Ready to Get Protected?526 527 **Choose a scan type from the tabs above to start your security analysis!**528 529 ---530 531 {Config.APP_VERSION} | Built with โค๏ธ for Cybersecurity532 """)533 534def phishing_scanner_interface(url):535 """Interface for phishing URL scanner"""536 if not url:537 return "โ ๏ธ Please enter a URL to scan", ""538 539 # Perform phishing analysis540 result = analyze_phishing_url(url)541 542 if result['status'] == 'error':543 return f"โ Error: {result['message']}", ""544 545 # Get threat level styling546 threat_info = Config.THREAT_LEVELS.get(result['threat_level'], {})547 emoji = threat_info.get('emoji', 'โ ๏ธ')548 549 # Build output550 output = f"""551# {emoji} Phishing Scan Results552 553**URL:** `{url}`554**Threat Level:** **{result['threat_level']}**555**Risk Score:** {result['risk_score']}/100556**Status:** {'๐จ PHISHING DETECTED' if result['is_phishing'] else 'โ
LIKELY SAFE'}557**Confidence:** {result['confidence']}558**Scanned:** {result['timestamp']}559 560---561 562## ๐ Detection Indicators563 564"""565 566 for indicator in result['indicators']:567 output += f"- {indicator}\n"568 569 output += "\n---\n\n## ๐ URL Analysis Features\n\n"570 571 features_df = pd.DataFrame([result['features']])572 573 # VirusTotal scan574 output += "\n---\n\n## ๐ฆ VirusTotal Scan Results\n\n"575 vt_result = scan_with_virustotal(url)576 577 if vt_result['status'] == 'success':578 output += f"- **Detections:** {vt_result['detections']}/{vt_result['total_engines']} engines\n"579 output += f"- **Malicious:** {vt_result['malicious']}\n"580 output += f"- **Suspicious:** {vt_result['suspicious']}\n"581 output += f"- **Harmless:** {vt_result['harmless']}\n"582 else:583 output += f"- {vt_result['message']}\n"584 585 output += "\n---\n\n## ๐ก Security Recommendations\n\n"586 587 if result['threat_level'] in ['CRITICAL', 'HIGH']:588 output += "- โ **DO NOT** visit this website\n"589 output += "- ๐ซ **DO NOT** enter any personal information\n"590 output += "- ๐ง Report this URL to authorities\n"591 output += "- ๐ก๏ธ Run a full system scan if you visited this site\n"592 elif result['threat_level'] == 'MEDIUM':593 output += "- โ ๏ธ **Exercise caution** when visiting\n"594 output += "- ๐ Verify the website's legitimacy\n"595 output += "- ๐ Only proceed if you trust the source\n"596 else:597 output += "- โ
Website appears safe\n"598 output += "- ๐ Always verify HTTPS encryption\n"599 output += "- ๐ก Stay vigilant for suspicious content\n"600 601 return output, features_df602 603def malware_scanner_interface(file):604 """Interface for malware scanner"""605 if file is None:606 return "โ ๏ธ Please upload a file to scan"607 608 try:609 # Read file content610 with open(file.name, 'rb') as f:611 file_content = f.read()612 613 filename = os.path.basename(file.name)614 615 # Analyze for malware616 result = analyze_malware(file_content, filename)617 618 if result['status'] == 'error':619 return f"โ Error: {result['message']}"620 621 threat_info = Config.THREAT_LEVELS.get(result['threat_level'], {})622 emoji = threat_info.get('emoji', 'โ ๏ธ')623 624 output = f"""625# {emoji} Malware Scan Results626 627**Filename:** `{result['filename']}`628**File Hash (SHA-256):** `{result['file_hash']}`629**File Size:** {result['file_size']}630**Threat Level:** **{result['threat_level']}**631**Risk Score:** {result['risk_score']}/100632**Scanned:** {result['timestamp']}633 634---635 636## ๐ Detected Patterns637 638"""639 640 for pattern in result['detected_patterns']:641 output += f"- `{pattern}`\n"642 643 output += "\n---\n\n## ๐ก Security Recommendations\n\n"644 645 if result['threat_level'] == 'HIGH':646 output += "- โ **DO NOT** execute this file\n"647 output += "- ๐๏ธ Delete the file immediately\n"648 output += "- ๐ก๏ธ Run a full system antivirus scan\n"649 output += "- ๐ง Report to security team\n"650 elif result['threat_level'] == 'MEDIUM':651 output += "- โ ๏ธ **Exercise caution** with this file\n"652 output += "- ๐ Scan with additional antivirus tools\n"653 output += "- ๐ Only open in isolated environment\n"654 else:655 output += "- โ
File appears safe\n"656 output += "- ๐ Always scan files from unknown sources\n"657 output += "- ๐ก Keep your antivirus updated\n"658 659 return output660 661 except Exception as e:662 return f"โ Error processing file: {str(e)}"663 664def password_checker_interface(password):665 """Interface for password strength checker"""666 if not password:667 return "โ ๏ธ Please enter a password to analyze"668 669 result = check_password_strength(password)670 671 if result['status'] == 'error':672 return f"โ Error: {result['message']}"673 674 output = f"""675# ๐ Password Strength Analysis676 677**Strength Level:** **{result['strength']}**678**Security Score:** {result['score']}/100679**Estimated Crack Time:** {result['estimated_crack_time']}680 681---682 683## ๐ Analysis Feedback684 685"""686 687 for item in result['feedback']:688 output += f"{item}\n"689 690 output += "\n---\n\n## ๐ก Password Best Practices\n\n"691 output += "- โ
Use at least 12 characters\n"692 output += "- โ
Mix uppercase and lowercase letters\n"693 output += "- โ
Include numbers and special characters\n"694 output += "- โ
Avoid common words and patterns\n"695 output += "- โ
Use unique passwords for each account\n"696 output += "- โ
Consider using a password manager\n"697 output += "- โ
Enable two-factor authentication (2FA)\n"698 699 if result['score'] < 60:700 output += "\n### ๐จ Your password is too weak! Please create a stronger one.\n"701 702 return output703 704def ssl_checker_interface(url):705 """Interface for SSL certificate checker"""706 if not url:707 return "โ ๏ธ Please enter a URL to check"708 709 result = check_ssl_certificate(url)710 711 output = f"""712# ๐ SSL Certificate Check713 714**URL:** `{url}`715**HTTPS Status:** {'โ
Enabled' if result.get('has_ssl') else 'โ Not Enabled'}716**Security Score:** {result.get('security_score', 0)}/100717 718---719 720## Analysis Result721 722{result['message']}723 724---725 726## ๐ก Security Recommendations727 728"""729 730 if result.get('has_ssl'):731 output += "- โ
Website uses secure HTTPS connection\n"732 output += "- ๐ Data transmission is encrypted\n"733 output += "- ๐ก Always verify the padlock icon in browser\n"734 else:735 output += "- โ **Warning:** Website uses insecure HTTP\n"736 output += "- ๐ซ **DO NOT** enter sensitive information\n"737 output += "- ๐ณ **NEVER** enter credit card details\n"738 output += "- ๐ง Contact website owner about security\n"739 740 return output741 742# ==================== MAIN GRADIO APP ====================743 744def create_app():745 """Create the main Gradio application"""746 747 # Custom CSS for professional look748 custom_css = """749 .gradio-container {750 font-family: 'Inter', sans-serif;751 }752 .tab-nav button {753 font-size: 16px;754 font-weight: 600;755 }756 .markdown-text h1 {757 color: #1F2937;758 border-bottom: 3px solid #3B82F6;759 padding-bottom: 10px;760 }761 .markdown-text h2 {762 color: #374151;763 margin-top: 20px;764 }765 .markdown-text h3 {766 color: #4B5563;767 }768 """769 770 with gr.Blocks(title=Config.APP_TITLE, css=custom_css, theme=gr.themes.Soft()) as app:771 772 gr.Markdown(f"# {Config.APP_TITLE}")773 gr.Markdown("### ๐ Advanced AI-Powered Cybersecurity Platform | Real-time Threat Detection & Analysis")774 775 with gr.Tabs():776 777 # Tab 1: Home778 with gr.Tab("๐ Home"):779 create_home_tab()780 781 # Tab 2: Phishing Scanner782 with gr.Tab("๐ฃ Phishing URL Scanner"):783 gr.Markdown("## ๐ Analyze URLs for Phishing Threats")784 gr.Markdown("Enter any URL to check if it's a phishing attempt or malicious website.")785 786 with gr.Row():787 with gr.Column(scale=2):788 url_input = gr.Textbox(789 label="Enter URL to Scan",790 placeholder="https://example.com",791 lines=1792 )793 scan_url_btn = gr.Button("๐ Scan URL", variant="primary", size="lg")794 795 with gr.Row():796 url_output = gr.Markdown(label="Scan Results")797 798 with gr.Row():799 url_features = gr.Dataframe(label="URL Features Analysis", wrap=True)800 801 scan_url_btn.click(802 fn=phishing_scanner_interface,803 inputs=[url_input],804 outputs=[url_output, url_features]805 )806 807 gr.Examples(808 examples=[809 ["https://www.google.com"],810 ["http://suspicious-login-verify.com"],811 ["https://github.com"]812 ],813 inputs=[url_input]814 )815 816 # Tab 3: Malware Scanner817 with gr.Tab("๐ฆ Malware Scanner"):818 gr.Markdown("## ๐ก๏ธ Scan Files for Malware & Suspicious Code")819 gr.Markdown("Upload any file to analyze for malicious patterns and threats.")820 821 with gr.Row():822 with gr.Column():823 file_input = gr.File(824 label="Upload File to Scan",825 file_types=[".txt", ".py", ".js", ".html", ".php", ".exe", ".pdf"]826 )827 scan_file_btn = gr.Button("๐ Scan File", variant="primary", size="lg")828 829 with gr.Row():830 malware_output = gr.Markdown(label="Scan Results")831 832 scan_file_btn.click(833 fn=malware_scanner_interface,834 inputs=[file_input],835 outputs=[malware_output]836 )837 838 # Tab 4: Password Strength839 with gr.Tab("๐ Password Analyzer"):840 gr.Markdown("## ๐ช Check Your Password Strength")841 gr.Markdown("Analyze password security and get recommendations for improvement.")842 843 with gr.Row():844 with gr.Column(scale=2):845 password_input = gr.Textbox(846 label="Enter Password",847 placeholder="Enter password to analyze",848 type="password",849 lines=1850 )851 check_password_btn = gr.Button("๐ Analyze Password", variant="primary", size="lg")852 853 with gr.Row():854 password_output = gr.Markdown(label="Analysis Results")855 856 check_password_btn.click(857 fn=password_checker_interface,858 inputs=[password_input],859 outputs=[password_output]860 )861 862 gr.Examples(863 examples=[864 ["password123"],865 ["MyP@ssw0rd2025!"],866 ["Tr0ub4dor&3"]867 ],868 inputs=[password_input]869 )870 871 # Tab 5: SSL Checker872 with gr.Tab("๐ SSL Certificate Checker"):873 gr.Markdown("## ๐ Verify Website SSL/HTTPS Security")874 gr.Markdown("Check if a website uses secure HTTPS encryption.")875 876 with gr.Row():877 with gr.Column(scale=2):878 ssl_url_input = gr.Textbox(879 label="Enter Website URL",880 placeholder="https://example.com",881 lines=1882 )883 check_ssl_btn = gr.Button("๐ Check SSL", variant="primary", size="lg")884 885 with gr.Row():886 ssl_output = gr.Markdown(label="SSL Check Results")887 888 check_ssl_btn.click(889 fn=ssl_checker_interface,890 inputs=[ssl_url_input],891 outputs=[ssl_output]892 )893 894 # Tab 6: Settings895 with gr.Tab("โ๏ธ Settings"):896 gr.Markdown("## โ๏ธ Configuration & API Keys")897 gr.Markdown("Configure API keys and advanced settings.")898 899 with gr.Column():900 gr.Markdown("""901 ### ๐ VirusTotal API Key902 903 To enable VirusTotal scanning:904 905 1. Get free API key from [VirusTotal](https://www.virustotal.com/gui/join-us)906 2. In Hugging Face Space: Settings โ Repository secrets907 3. Add secret: `VIRUSTOTAL_API_KEY` = your_api_key908 4. Restart the space909 910 ---911 912 ### ๐ Current Status913 """)914 915 api_status = "โ
Configured" if Config.VIRUSTOTAL_API_KEY else "โ ๏ธ Not Configured"916 gr.Markdown(f"**VirusTotal API:** {api_status}")917 918 gr.Markdown("""919 ---920 921 ### ๐ Documentation922 923 - [GitHub Repository](#)924 - [User Guide](#)925 - [API Documentation](#)926 - [Report Issues](#)927 928 ---929 930 ### ๐ค About931 932 **AI Shield Pro** - Advanced Cybersecurity Platform933 934 Version: 1.0.0935 936 Built with Python, Gradio, and Machine Learning937 938 ยฉ 2025 - Open Source Project939 """)940 941 gr.Markdown("---")942 gr.Markdown("๐ก๏ธ **Stay Safe Online** | Made with โค๏ธ for Cybersecurity | Powered by AI")943 944 return app945 946# ==================== LAUNCH APP ====================947 948if __name__ == "__main__":949 app = create_app()950 app.launch(951 server_name="0.0.0.0",952 server_port=7860,953 share=False954 )955 