import gradio as gr
import datetime
# ============================================================================
# DETECTION FUNCTION
# ============================================================================
def detect_ddos(flow_duration, total_packets):
"""
Detect DDoS based on Packets Per Second (PPS)
"""
# Convert microseconds to seconds
duration_seconds = flow_duration / 1_000_000
# Calculate PPS
if duration_seconds > 0:
pps = total_packets / duration_seconds
else:
pps = 0
# Determine status based on PPS
if pps < 500:
status = "โ
NORMAL"
severity = "Low"
color = "#00ff88"
risk = "No threat detected"
attack_type = "Normal Traffic"
emoji = "๐ข"
recommendation = "Continue monitoring"
elif pps < 2000:
status = "โ ๏ธ SUSPICIOUS"
severity = "Medium"
color = "#f9ca24"
risk = "Monitor traffic closely"
attack_type = "Suspicious Activity"
emoji = "๐ก"
recommendation = "Enable IDS/IPS monitoring"
elif pps < 10000:
status = "๐จ HIGH TRAFFIC"
severity = "High"
color = "#f0932b"
risk = "Possible DDoS attack"
attack_type = "Potential DDoS"
emoji = "๐ "
recommendation = "Apply rate limiting, check firewall"
else:
status = "๐ฅ DDoS ATTACK!"
severity = "Critical"
color = "#eb4d4b"
risk = "Immediate action required"
attack_type = "DDoS Attack"
emoji = "๐ด"
recommendation = "Block IPs, enable SYN cookies, contact SOC"
result = {
'status': status,
'severity': severity,
'color': color,
'risk': risk,
'attack_type': attack_type,
'emoji': emoji,
'recommendation': recommendation,
'pps': pps,
'total_packets': int(total_packets),
'duration_us': flow_duration,
'duration_ms': flow_duration / 1000,
'duration_sec': duration_seconds,
'is_attack': pps > 1000,
'timestamp': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
return result
# ============================================================================
# PREDICTION FUNCTION
# ============================================================================
def predict(flow_duration, total_packets):
"""
Gradio prediction function
"""
# Validate inputs
if flow_duration <= 0 or total_packets <= 0:
return """
โ Please enter positive values for both fields!
"""
# Get detection result
result = detect_ddos(flow_duration, total_packets)
# Format output with HTML
color = result['color']
pps_display = f"{int(result['pps']):,}"
output = f"""
{result['emoji']} {result['status']}
{pps_display}
Packets Per Second (PPS)
{result['total_packets']:,}
Total Packets
{result['duration_ms']:.1f} ms
Flow Duration
{result['attack_type']}
{result['severity']} Severity
{result['risk']}
๐ก Recommendation:
{result['recommendation']}
Detected at {result['timestamp']}
"""
return output
# ============================================================================
# CUSTOM CSS
# ============================================================================
custom_css = """
.gradio-container {
background: linear-gradient(135deg, #0a0e17 0%, #0d1a2b 50%, #0a0e17 100%) !important;
}
.gr-box {
border: 1px solid rgba(0, 212, 255, 0.1) !important;
border-radius: 12px !important;
background: rgba(255, 255, 255, 0.02) !important;
}
input[type="number"] {
background: rgba(255, 255, 255, 0.05) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
color: #e0e0e0 !important;
}
input[type="number"]:focus {
border-color: #00d4ff !important;
box-shadow: 0 0 20px rgba(0, 212, 255, 0.1) !important;
}
label {
color: #8a8fa8 !important;
font-weight: 600 !important;
}
button {
font-weight: 600 !important;
}
"""
# ============================================================================
# CREATE GRADIO INTERFACE
# ============================================================================
def create_interface():
with gr.Blocks(
title="DDoS Detection System",
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="purple",
neutral_hue="slate",
),
css=custom_css
) as demo:
gr.Markdown("""
# ๐ก๏ธ DDoS Detection System
### Detect DDoS attacks using Packets Per Second (PPS) calculation
Enter the **Flow Duration** and **Total Packets** to instantly calculate PPS and detect attacks.
""")
with gr.Row():
with gr.Column(scale=1):
flow_duration = gr.Number(
label="โฑ๏ธ Flow Duration (microseconds)",
value=98,
minimum=1,
step=1,
info="Time duration of the network flow in microseconds (ยตs)"
)
total_packets = gr.Number(
label="๐ฆ Total Packets",
value=15,
minimum=1,
step=1,
info="Total number of packets in this flow (Fwd + Bwd)"
)
with gr.Row():
detect_btn = gr.Button("๐ Detect Attack", variant="primary", size="lg")
clear_btn = gr.Button("๐ Reset", variant="secondary", size="lg")
gr.Markdown("""
---
### ๐ PPS Thresholds
| PPS Range | Status |
|-----------|--------|
| < 500 | โ
NORMAL |
| 500 - 2,000 | โ ๏ธ SUSPICIOUS |
| 2,000 - 10,000 | ๐จ HIGH TRAFFIC |
| > 10,000 | ๐ฅ DDoS ATTACK! |
---
### ๐ก Example Values
- **Normal:** 1,000,000ยตs, 100 packets โ 100 PPS โ โ
NORMAL
- **Suspicious:** 100,000ยตs, 100 packets โ 1,000 PPS โ โ ๏ธ SUSPICIOUS
- **Attack:** 98ยตs, 15 packets โ 153,061 PPS โ ๐ฅ DDoS ATTACK!
""")
with gr.Column(scale=2):
output = gr.HTML(
value="""
๐
Enter values and click "Detect Attack"
Results will appear here
""",
label="Detection Result"
)
# Event handlers
detect_btn.click(
fn=predict,
inputs=[flow_duration, total_packets],
outputs=output
)
clear_btn.click(
fn=lambda: (
98,
15,
'๐
Enter values and click "Detect Attack"
Results will appear here
'
),
inputs=[],
outputs=[flow_duration, total_packets, output]
)
flow_duration.submit(fn=predict, inputs=[flow_duration, total_packets], outputs=output)
total_packets.submit(fn=predict, inputs=[flow_duration, total_packets], outputs=output)
return demo
# ============================================================================
# LAUNCH
# ============================================================================
demo = create_interface()
# Hugging Face Spaces requires demo.launch() with no arguments
demo.launch()