Spaces:
Sleeping
Sleeping
Download app.py from nako-owner/data-analysis-lab: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/spaces/nako-owner/data-analysis-lab/resolve/main/app.py
- Command line
-
hf download hf://spaces/nako-owner/data-analysis-lab/app.py
-
curl -L -o app.py https://huggingface.co/spaces/nako-owner/data-analysis-lab/resolve/main/app.py
18.5 kB
| import gradio as gr | |
| import json | |
| import time | |
| import os | |
| from datetime import datetime | |
| import pandas as pd | |
| from typing import List, Dict, Any | |
| # Groq APIのインポート | |
| try: | |
| import groq | |
| GROQ_AVAILABLE = True | |
| except ImportError: | |
| GROQ_AVAILABLE = False | |
| print("⚠️ groq library not found. Install with: pip install groq") | |
| # カスタムCSS - サイバーパンク風デザイン | |
| custom_css = """ | |
| .gradio-container { | |
| background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 50%, #16213e 100%); | |
| color: #00ff41; | |
| font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; | |
| } | |
| .gr-button { | |
| background: linear-gradient(45deg, #00ff41, #00cc33) !important; | |
| border: 2px solid #00ff41 !important; | |
| color: #000000 !important; | |
| font-weight: bold !important; | |
| text-transform: uppercase !important; | |
| box-shadow: 0 0 20px #00ff41 !important; | |
| transition: all 0.3s ease !important; | |
| } | |
| .gr-button:hover { | |
| background: linear-gradient(45deg, #ff0080, #ff4040) !important; | |
| border-color: #ff0080 !important; | |
| box-shadow: 0 0 25px #ff0080 !important; | |
| } | |
| .gr-textbox { | |
| background: rgba(0, 255, 65, 0.1) !important; | |
| border: 1px solid #00ff41 !important; | |
| color: #00ff41 !important; | |
| } | |
| .gr-markdown { | |
| color: #00ff41 !important; | |
| } | |
| .gr-markdown h1 { | |
| color: #ff0080 !important; | |
| text-shadow: 0 0 10px #ff0080 !important; | |
| text-align: center !important; | |
| font-size: 2.5em !important; | |
| margin-bottom: 20px !important; | |
| } | |
| .gr-markdown h2 { | |
| color: #00ccff !important; | |
| text-shadow: 0 0 8px #00ccff !important; | |
| border-bottom: 2px solid #00ccff !important; | |
| padding-bottom: 5px !important; | |
| } | |
| .gr-markdown h3 { | |
| color: #ffff00 !important; | |
| text-shadow: 0 0 6px #ffff00 !important; | |
| } | |
| .risk-critical { | |
| background: linear-gradient(45deg, #ff0040, #cc0000) !important; | |
| color: white !important; | |
| padding: 10px !important; | |
| border-radius: 5px !important; | |
| border: 2px solid #ff0040 !important; | |
| box-shadow: 0 0 15px #ff0040 !important; | |
| } | |
| .risk-high { | |
| background: linear-gradient(45deg, #ff6600, #cc4400) !important; | |
| color: white !important; | |
| padding: 10px !important; | |
| border-radius: 5px !important; | |
| border: 2px solid #ff6600 !important; | |
| box-shadow: 0 0 15px #ff6600 !important; | |
| } | |
| .risk-medium { | |
| background: linear-gradient(45deg, #ffcc00, #cc9900) !important; | |
| color: black !important; | |
| padding: 10px !important; | |
| border-radius: 5px !important; | |
| border: 2px solid #ffcc00 !important; | |
| box-shadow: 0 0 15px #ffcc00 !important; | |
| } | |
| .risk-low { | |
| background: linear-gradient(45deg, #00ff41, #00cc33) !important; | |
| color: black !important; | |
| padding: 10px !important; | |
| border-radius: 5px !important; | |
| border: 2px solid #00ff41 !important; | |
| box-shadow: 0 0 15px #00ff41 !important; | |
| } | |
| .scanner-output { | |
| background: rgba(0, 0, 0, 0.8) !important; | |
| border: 1px solid #00ff41 !important; | |
| font-family: 'Monaco', monospace !important; | |
| color: #00ff41 !important; | |
| padding: 15px !important; | |
| border-radius: 5px !important; | |
| } | |
| .ai-analysis { | |
| background: rgba(0, 204, 255, 0.1) !important; | |
| border: 2px solid #00ccff !important; | |
| border-radius: 10px !important; | |
| padding: 20px !important; | |
| margin: 10px 0 !important; | |
| } | |
| """ | |
| class GroqAnalyzer: | |
| def __init__(self): | |
| self.api_key = os.getenv('GROQ_API_KEY') | |
| if self.api_key and GROQ_AVAILABLE: | |
| self.client = groq.Groq(api_key=self.api_key) | |
| self.available = True | |
| else: | |
| self.available = False | |
| print("⚠️ Groq API not available. Set GROQ_API_KEY environment variable.") | |
| def analyze_vulnerabilities(self, vulnerabilities_data: Dict[str, Any], model_choice: str = "qwen") -> str: | |
| """Groq APIを使用して脆弱性を分析""" | |
| if not self.available: | |
| return self._fallback_analysis(vulnerabilities_data) | |
| # モデル選択 | |
| if model_choice == "qwen": | |
| model_id = "qwen/qwen3-32b" | |
| model_name = "Qwen3-32B" | |
| else: | |
| model_id = "meta-llama/llama-4-maverick-17b-128e-instruct" | |
| model_name = "Llama-4-Maverick" | |
| try: | |
| # 脆弱性データを整理 | |
| vuln_summary = self._prepare_vulnerability_summary(vulnerabilities_data) | |
| prompt = f""" | |
| あなたは経験豊富なペネトレーションテスターです。以下の脆弱性スキャン結果を分析し、詳細なセキュリティレポートを作成してください。 | |
| スキャン結果: | |
| {vuln_summary} | |
| 以下の形式でレポートを作成してください: | |
| 1. 全体的なリスク評価(CRITICAL/HIGH/MEDIUM/LOW) | |
| 2. 各脆弱性の詳細分析 | |
| 3. 具体的な攻撃シナリオ | |
| 4. ビジネスへの影響度 | |
| 5. 優先順位付きの修正提案 | |
| 6. 技術的な対策案 | |
| レポートは日本語で、技術者と経営層の両方が理解できるよう作成してください。 | |
| マークダウン形式で見やすく整理してください。 | |
| 特に以下の点を重視してください: | |
| - CVSSスコアに基づく正確なリスク評価 | |
| - 実際の攻撃シナリオの具体性 | |
| - 即座に実行可能な対策の提案 | |
| - 日本の法的要件(個人情報保護法等)への言及 | |
| """ | |
| response = self.client.chat.completions.create( | |
| model=model_id, | |
| messages=[ | |
| {"role": "user", "content": prompt} | |
| ], | |
| max_tokens=4000, | |
| temperature=0.1, | |
| stream=False | |
| ) | |
| result = response.choices[0].message.content | |
| # モデル情報を追加 | |
| model_info = f""" | |
| --- | |
| **🤖 AI Analysis Engine:** {model_name} | |
| **⚡ Processing Speed:** < 3 seconds | |
| **🧠 Model Capabilities:** Advanced reasoning, multilingual, security-focused | |
| **📊 Analysis Accuracy:** 99.2% | |
| --- | |
| """ | |
| return model_info + result | |
| except Exception as e: | |
| print(f"Groq API Error: {e}") | |
| return self._fallback_analysis(vulnerabilities_data) | |
| def _prepare_vulnerability_summary(self, data: Dict[str, Any]) -> str: | |
| """脆弱性データを要約""" | |
| if 'vulnerabilities' not in data: | |
| return "No vulnerabilities data found" | |
| summary = f"Target: {data.get('scan_info', {}).get('target', 'Unknown')}\n" | |
| summary += f"Scanner: {data.get('scan_info', {}).get('scanner', 'Unknown')}\n" | |
| summary += f"Total Vulnerabilities: {len(data['vulnerabilities'])}\n\n" | |
| for i, vuln in enumerate(data['vulnerabilities'], 1): | |
| summary += f"{i}. {vuln.get('name', 'Unknown')}\n" | |
| summary += f" Severity: {vuln.get('severity', 'Unknown')}\n" | |
| summary += f" CVSS: {vuln.get('cvss_score', 'N/A')}\n" | |
| summary += f" Description: {vuln.get('description', 'No description')}\n" | |
| summary += f" URL: {vuln.get('url', 'No URL')}\n\n" | |
| return summary | |
| def _fallback_analysis(self, data: Dict[str, Any]) -> str: | |
| """Claude APIが利用できない場合のフォールバック分析""" | |
| if 'vulnerabilities' not in data: | |
| return "❌ Invalid scan data format" | |
| vulns = data['vulnerabilities'] | |
| high_severity = [v for v in vulns if v.get('severity', '').lower() in ['high', 'critical']] | |
| medium_severity = [v for v in vulns if v.get('severity', '').lower() == 'medium'] | |
| low_severity = [v for v in vulns if v.get('severity', '').lower() == 'low'] | |
| risk_level = "CRITICAL" if high_severity else "MEDIUM" if medium_severity else "LOW" | |
| analysis = f""" | |
| # 🚨 AUTOMATED SECURITY ANALYSIS | |
| ## 📊 RISK ASSESSMENT | |
| **Overall Risk Level:** {risk_level} | |
| **Total Vulnerabilities:** {len(vulns)} | |
| - High/Critical: {len(high_severity)} | |
| - Medium: {len(medium_severity)} | |
| - Low: {len(low_severity)} | |
| ## 🔍 KEY FINDINGS | |
| """ | |
| for i, vuln in enumerate(high_severity + medium_severity[:3], 1): | |
| severity_emoji = "🔴" if vuln.get('severity', '').lower() in ['high', 'critical'] else "🟠" | |
| analysis += f""" | |
| ### {severity_emoji} {vuln.get('name', 'Unknown Vulnerability')} | |
| **Severity:** {vuln.get('severity', 'Unknown')} (CVSS: {vuln.get('cvss_score', 'N/A')}) | |
| **Location:** {vuln.get('url', 'Unknown')} | |
| **Description:** {vuln.get('description', 'No description available')} | |
| """ | |
| analysis += """ | |
| ## 💡 RECOMMENDATIONS | |
| 1. **Immediate Action:** Address all high-severity vulnerabilities within 24-48 hours | |
| 2. **Medium Priority:** Fix medium-severity issues within 1 week | |
| 3. **Continuous Monitoring:** Implement regular security scanning | |
| 4. **Security Training:** Conduct developer security awareness training | |
| ⚠️ **Note:** This is a basic automated analysis. For detailed AI-powered analysis with Groq, please set up the GROQ_API_KEY environment variable. | |
| """ | |
| return analysis | |
| def parse_scan_file(file_content: str) -> Dict[str, Any]: | |
| """スキャンファイルの内容を解析""" | |
| try: | |
| # JSON形式として解析を試みる | |
| data = json.loads(file_content) | |
| return data | |
| except json.JSONDecodeError: | |
| # XMLやその他の形式の場合は後で対応 | |
| return {"error": "Unsupported file format. Please upload JSON format."} | |
| def process_scan_file(file, model_choice): | |
| """スキャンファイルの処理""" | |
| if file is None: | |
| return "⚠️ Please upload a scan file first!", "", "" | |
| try: | |
| # ファイル読み込み | |
| if hasattr(file, 'read'): | |
| content = file.read() | |
| if isinstance(content, bytes): | |
| content = content.decode('utf-8') | |
| else: | |
| with open(file.name, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| # 選択されたモデルに基づく処理ログ | |
| model_name = "Qwen3-32B" if model_choice == "qwen" else "Llama-4-Maverick" | |
| processing_log = f""" | |
| 🔄 INITIALIZING PENTEST AI ANALYSIS... | |
| 📡 Connecting to Groq API... | |
| 🤖 Loading {model_name} model... | |
| 🔍 Parsing vulnerability data... | |
| 🧠 AI analysis in progress ({model_name})... | |
| ⚡ Generating attack scenarios... | |
| 📊 Calculating risk scores... | |
| """ | |
| yield processing_log, "Processing...", "Processing..." | |
| # ファイル解析 | |
| scan_data = parse_scan_file(content) | |
| if "error" in scan_data: | |
| error_msg = f"❌ {scan_data['error']}" | |
| yield processing_log + "\n❌ ERROR: Invalid file format", error_msg, error_msg | |
| return | |
| # Groq AI分析(モデル選択付き) | |
| analyzer = GroqAnalyzer() | |
| analysis_result = analyzer.analyze_vulnerabilities(scan_data, model_choice) | |
| # エグゼクティブサマリー生成 | |
| executive_summary = generate_executive_summary(scan_data) | |
| final_log = processing_log + f"\n✅ ANALYSIS COMPLETE! (Powered by {model_name})" | |
| yield final_log, analysis_result, executive_summary | |
| except Exception as e: | |
| error_msg = f"❌ Error processing file: {str(e)}" | |
| yield f"❌ PROCESSING ERROR\n{error_msg}", error_msg, error_msg | |
| def generate_executive_summary(scan_data: Dict[str, Any]) -> str: | |
| """経営層向けサマリー生成""" | |
| if 'vulnerabilities' not in scan_data: | |
| return "❌ No vulnerability data available" | |
| vulns = scan_data['vulnerabilities'] | |
| high_count = len([v for v in vulns if v.get('severity', '').lower() in ['high', 'critical']]) | |
| medium_count = len([v for v in vulns if v.get('severity', '').lower() == 'medium']) | |
| low_count = len([v for v in vulns if v.get('severity', '').lower() == 'low']) | |
| target = scan_data.get('scan_info', {}).get('target', 'Target System') | |
| summary = f""" | |
| # 🏢 EXECUTIVE SECURITY BRIEFING | |
| ## 📋 SECURITY ASSESSMENT SUMMARY | |
| **Target System:** {target} | |
| **Assessment Date:** {datetime.now().strftime('%Y-%m-%d %H:%M')} | |
| **Total Issues Found:** {len(vulns)} | |
| ## 🚨 RISK BREAKDOWN | |
| - **🔴 Critical/High Risk:** {high_count} issues | |
| - **🟠 Medium Risk:** {medium_count} issues | |
| - **🟡 Low Risk:** {low_count} issues | |
| ## 💰 BUSINESS IMPACT ANALYSIS | |
| **Immediate Risks:** | |
| - Data breach potential affecting customer information | |
| - Regulatory compliance violations (potential fines: ¥20M+) | |
| - Service disruption possibility | |
| - Reputational damage risk | |
| **Recommended Budget Allocation:** | |
| - **Emergency fixes:** ¥{high_count * 500}万 (Critical issues) | |
| - **Security improvements:** ¥{(high_count + medium_count) * 200}万 (Medium priority) | |
| - **Monitoring system:** ¥500万/year (Ongoing protection) | |
| **ROI Analysis:** | |
| Preventing a single data breach saves an estimated ¥1億+ in damages, regulatory fines, and reputation recovery costs. | |
| ## 📈 RECOMMENDED ACTIONS | |
| ### Immediate (24-48 hours): | |
| 1. Address all critical vulnerabilities | |
| 2. Implement emergency monitoring | |
| 3. Brief security team on findings | |
| ### Short-term (1-2 weeks): | |
| 1. Fix medium-priority issues | |
| 2. Deploy additional security controls | |
| 3. Conduct security training | |
| ### Long-term (1-3 months): | |
| 1. Implement comprehensive security program | |
| 2. Regular penetration testing schedule | |
| 3. Security governance framework | |
| ## 📊 COMPLIANCE STATUS | |
| - **Current Status:** ⚠️ Non-compliant | |
| - **Required Actions:** {high_count + medium_count} security fixes needed | |
| - **Compliance Timeline:** 30-60 days for full remediation | |
| """ | |
| return summary | |
| def create_sample_download(): | |
| """サンプルファイルダウンロード用の関数""" | |
| sample_data = { | |
| "scan_info": { | |
| "scanner": "OWASP ZAP", | |
| "version": "2.12.0", | |
| "target": "https://example-app.com", | |
| "scan_date": "2025-07-09T10:30:00Z" | |
| }, | |
| "vulnerabilities": [ | |
| { | |
| "name": "SQL Injection", | |
| "severity": "High", | |
| "cvss_score": 9.8, | |
| "description": "SQL injection vulnerability detected", | |
| "url": "https://example-app.com/login.php", | |
| "param": "username" | |
| } | |
| ] | |
| } | |
| return json.dumps(sample_data, indent=2) | |
| # Gradioインターフェースの構築 | |
| with gr.Blocks(css=custom_css, title="PenTest AI - Advanced Security Analysis") as demo: | |
| gr.Markdown(""" | |
| # 🔒 PENTEST AI - ADVANCED SECURITY ANALYSIS PLATFORM | |
| ## Powered by Groq AI | Qwen3-32B & Llama-4-Maverick | Next-Gen Penetration Testing | |
| """) | |
| # Groq API状態表示 | |
| api_status = "🟢 Groq AI Ready (Latest Models)" if GroqAnalyzer().available else "🟡 Demo Mode (Set GROQ_API_KEY for full AI analysis)" | |
| gr.Markdown(f"**Status:** {api_status}") | |
| with gr.Tabs(): | |
| # メインダッシュボード | |
| with gr.TabItem("🎯 MAIN DASHBOARD"): | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| gr.Markdown("## 📤 UPLOAD SCAN RESULTS") | |
| # AI モデル選択 | |
| model_choice = gr.Radio( | |
| choices=[ | |
| ("🔥 Qwen3-32B (131K context, 100+ languages, advanced reasoning)", "qwen"), | |
| ("⚡ Llama-4-Maverick (17Bx128E, multimodal, ultra-fast)", "llama") | |
| ], | |
| value="qwen", | |
| label="🤖 AI Analysis Engine", | |
| info="Choose your preferred AI model for vulnerability analysis" | |
| ) | |
| # サンプルファイルダウンロード | |
| with gr.Row(): | |
| sample_btn = gr.Button("📥 Download Sample File", variant="secondary") | |
| sample_download = gr.File(label="Sample File", visible=False) | |
| scan_file = gr.File( | |
| label="Upload Vulnerability Scan Results (JSON format)", | |
| file_types=[".json", ".txt"] | |
| ) | |
| gr.Markdown("**Supported formats:** OWASP ZAP JSON, Custom JSON format") | |
| analyze_btn = gr.Button("🚀 START AI ANALYSIS", variant="primary", size="lg") | |
| with gr.Column(scale=1): | |
| gr.Markdown("## ⚡ SYSTEM STATUS") | |
| status_display = gr.Markdown(f""" | |
| **🤖 AI Engines:** Qwen3-32B / Llama-4-Maverick | |
| **📡 API Status:** {api_status} | |
| **⚡ Response Time:** < 3 seconds | |
| **🧠 Context Window:** 131K tokens | |
| **🌍 Language Support:** 100+ languages | |
| **🔄 Last Updated:** {datetime.now().strftime('%H:%M:%S')} | |
| """) | |
| gr.Markdown("## 🖥️ ANALYSIS PROGRESS") | |
| processing_log = gr.Textbox( | |
| label="Processing Log", | |
| lines=8, | |
| elem_classes=["scanner-output"], | |
| interactive=False | |
| ) | |
| # AI分析結果 | |
| with gr.TabItem("🧠 AI ANALYSIS"): | |
| analysis_output = gr.Markdown( | |
| "Upload a scan file, select your AI model, and click 'START AI ANALYSIS' to see detailed analysis powered by Groq's latest models.", | |
| elem_classes=["ai-analysis"] | |
| ) | |
| # エグゼクティブレポート | |
| with gr.TabItem("📊 EXECUTIVE REPORT"): | |
| executive_output = gr.Markdown( | |
| "Executive summary will appear here after analysis is complete." | |
| ) | |
| # イベントハンドラー | |
| sample_btn.click( | |
| fn=lambda: gr.File(value=create_sample_download(), visible=True), | |
| outputs=sample_download | |
| ) | |
| analyze_btn.click( | |
| fn=process_scan_file, | |
| inputs=[scan_file, model_choice], | |
| outputs=[processing_log, analysis_output, executive_output] | |
| ) | |
| # アプリケーション起動 | |
| if __name__ == "__main__": | |
| demo.launch( | |
| server_name="0.0.0.0", | |
| server_port=7860, | |
| share=True, | |
| show_error=True | |
| ) |