import sys
import types
import re
# 🚨 DYNAMIC FIX: Python 3.13 Compatibility Patches
if 'audioop' not in sys.modules:
dummy_audioop = types.ModuleType('audioop')
dummy_audioop.error = Exception
sys.modules['audioop'] = dummy_audioop
import gradio as gr
def scan_dark_patterns(raw_html_or_text):
if not raw_html_or_text.strip():
return "
⚠️ Error: Please paste website HTML or text content to audit!
"
text_to_scan = raw_html_or_text.strip()
# 🔍 Technical Heuristics Matrix
patterns = {
"False Urgency & Fake Timers": [
r"(?i)ends in \d+m", r"(?i)hurry up", r"(?i)limited time offer",
r"(?i)only \d+ left", r"(?i)demand is high", r"(?i)selling fast",
r"stock running low", r"buying right now"
],
"Social Proof Manipulation": [
r"(?i)verified buyer", r"(?i)everyone else bought", r"(?i)someone from .* just purchased",
r"(?i)5-star rated by thousand", r"trusted by millions"
],
"Hidden Charges & Sneaking": [
r"(?i)hidden fee", r"(?i)service charge added", r"(?i)protection plan auto-renew",
r"(?i)convenience fee", r"handling charges apply at checkout"
],
"Forced Continuity": [
r"(?i)subscription auto-renews", r"(?i)no thanks, i hate saving money",
r"(?i)keep insurance active", r"cancel anytime\* condition"
]
}
detected_rows = ""
total_violations = 0
# Analyze string patterns natively and generate clean HTML rows
for category, regex_list in patterns.items():
matched_triggers = []
for regex in regex_list:
matches = re.findall(regex, text_to_scan)
if matches:
matched_triggers.extend([f"\"{m}\"" for m in matches])
total_violations += len(matches)
if matched_triggers:
icon = "🚨" if "Charges" in category or "Urgency" in category else "⚠️"
unique_triggers = list(set(matched_triggers)) # Deduplicate for clean view
detected_rows += f"""
| {icon} {category} |
{", ".join(unique_triggers)}
|
"""
# Risk Scoring Formula
risk_score = min(100, total_violations * 25)
if risk_score >= 75:
verdict = "🔴 HIGH RISK (Highly Manipulative Tactics)"
verdict_color = "#ef4444"
bg_verdict = "#fef2f2"
elif risk_score >= 40:
verdict = "🟡 MEDIUM RISK (Deceptive Tricks Identified)"
verdict_color = "#d97706"
bg_verdict = "#fffbeb"
else:
verdict = "🟢 CLEAN / LOW RISK (Fair Consumer Practice)"
verdict_color = "#16a34a"
bg_verdict = "#f0fdf4"
# Full Screen Render Pipeline Override (Eliminating code block leakage)
if total_violations == 0:
final_layout = """
🛡️ Compliance Status: SECURE
No consumer manipulation or hidden traps detected.
Consumer Threat Index: 0% Risk
"""
else:
final_layout = f"""
{verdict}
Forensic data metrics verified inside local edge matrix footprint.
Consumer Threat Index:
{risk_score}% Threat Level
🔍 Deceptive Breakdown (فریب کاری کی تفصیل):
| Category |
Detected Trigger Tokens |
{detected_rows}
💡 Shield Advice: Do not make panic purchases based on artificial countdown clocks or pre-checked hidden checkboxes.
"""
return final_layout
# Premium Cyber-Shield Workspace Stylesheet Injection
custom_css = """
body, .gradio-container { background-color: #f8fafc !important; color: #0f172a !important; font-family: 'Segoe UI', system-ui, sans-serif; }
.shield-btn { background-color: #2563eb !important; color: #ffffff !important; font-weight: bold !important; border-radius: 8px !important; font-size: 16px !important; border: none !important; margin-top: 10px; height: 45px; }
.shield-btn:hover { background-color: #1d4ed8 !important; box-shadow: 0 4px 12px rgba(37,99,235,0.2); }
.panel-layout { border: 1px solid #e2e8f0 !important; border-radius: 12px; padding: 20px; background: #ffffff !important; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
textarea { background-color: #ffffff !important; color: #0f172a !important; border: 1px solid #cbd5e1 !important; font-size: 14px !important; }
label { color: #334155 !important; font-weight: 600 !important; }
"""
with gr.Blocks(title="Consumer Shield v1.0", css=custom_css, theme=gr.themes.Default(primary_hue="blue", secondary_hue="slate")) as demo:
gr.HTML(
"""
🛡️ DARK-PATTERNS CONSUMER SHIELD
Serverless E-Commerce Protection & Pattern Audit Matrix // Zero-Latency Scanner
"""
)
with gr.Row():
with gr.Column(scale=5, elem_classes="panel-layout"):
gr.Markdown("### 🌐 Web Scraping & Ingestion Node")
source_input = gr.Textbox(
label="Paste Store Copy, Product Descriptions, or Web Raw HTML",
placeholder="Paste content here...",
lines=12
)
scan_btn = gr.Button("🛡️ Launch Real-Time Forensic Audit", elem_classes="shield-btn")
with gr.Column(scale=4, elem_classes="panel-layout"):
gr.Markdown("### 📊 Shield Compliance Output Dashboard")
# 🔥 FIXED: Changed component type to dynamic gr.HTML to properly execute layout layers
audit_output = gr.HTML(
"Security Engine active. Waiting for raw e-commerce matrix data streams...
"
)
scan_btn.click(
fn=scan_dark_patterns,
inputs=[source_input],
outputs=[audit_output]
)
demo.launch()