Программа постоянно выдает одно и то же значение: "Риск DDoS-атаки: 84.44%" Перепиши её полностью и исправь ошибки.

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import threading
import psutil
import pyshark
import time
import asyncio
from datetime import datetime, timedelta
from collections import deque

# Определение входных переменных и выходной переменной

# 1. Скорость входящего трафика
traffic_rate = ctrl.Antecedent(np.arange(0, 10001, 1), 'traffic_rate')

# 2. Количество уникальных IP-адресов
unique_ips = ctrl.Antecedent(np.arange(0, 5001, 1), 'unique_ips')

# 3. Среднее время между пакетами
inter_arrival_time = ctrl.Antecedent(np.arange(0, 101, 1), 'inter_arrival_time')

# 4. Процент неудачных попыток соединения
failed_conn = ctrl.Antecedent(np.arange(0, 101, 1), 'failed_conn')

# 5. Процент аномальных размеров пакетов
anomalous_packet = ctrl.Antecedent(np.arange(0, 101, 1), 'anomalous_packet')

# 6. Количество запросов к одному ресурсу
requests_per_resource = ctrl.Antecedent(np.arange(0, 10001, 1), 'requests_per_resource')

# 7. Вариация размера пакетов
packet_size_variance = ctrl.Antecedent(np.arange(0, 101, 1), 'packet_size_variance')

# 8. Скорость SYN-пакетов
syn_rate = ctrl.Antecedent(np.arange(0, 10001, 1), 'syn_rate')

# 9. Скорость UDP-пакетов
udp_rate = ctrl.Antecedent(np.arange(0, 10001, 1), 'udp_rate')

# 10. Скорость ICMP-пакетов
icmp_rate = ctrl.Antecedent(np.arange(0, 10001, 1), 'icmp_rate')

# 11. Процент новых соединений
new_conn_percent = ctrl.Antecedent(np.arange(0, 101, 1), 'new_conn_percent')

# 12. Загрузка CPU
cpu_usage = ctrl.Antecedent(np.arange(0, 101, 1), 'cpu_usage')

# 13. Использование памяти
memory_usage = ctrl.Antecedent(np.arange(0, 101, 1), 'memory_usage')

# 14. Вариация длительности соединений
conn_duration_variance = ctrl.Antecedent(np.arange(0, 101, 1), 'conn_duration_variance')

# 15. Количество полуоткрытых соединений
half_open_conn = ctrl.Antecedent(np.arange(0, 10001, 1), 'half_open_conn')

# 16. Частота ошибок пакетов
error_rate = ctrl.Antecedent(np.arange(0, 101, 1), 'error_rate')

# 17. Количество протокольных аномалий
protocol_anomalies = ctrl.Antecedent(np.arange(0, 1001, 1), 'protocol_anomalies')

# 18. Активность на критических портах
critical_port_activity = ctrl.Antecedent(np.arange(0, 10001, 1), 'critical_port_activity')

# 19. Отношение входящего к исходящему трафику
in_out_ratio = ctrl.Antecedent(np.arange(0, 11, 0.1), 'in_out_ratio')

# 20. Необычное использование протоколов
unusual_protocol_usage = ctrl.Antecedent(np.arange(0, 101, 1), 'unusual_protocol_usage')

# Определение выходной переменной
ddos_risk = ctrl.Consequent(np.arange(0, 101, 1), 'ddos_risk')

variables = [traffic_rate, unique_ips, inter_arrival_time, failed_conn, anomalous_packet,
             requests_per_resource, packet_size_variance, syn_rate, udp_rate, icmp_rate,
             new_conn_percent, cpu_usage, memory_usage, conn_duration_variance,
             half_open_conn, error_rate, protocol_anomalies, critical_port_activity,
             in_out_ratio, unusual_protocol_usage, ddos_risk]

# Функции принадлежности (оставляем ваши исходные определения)
# ... (здесь должны быть ваши определения функций принадлежности)

# Пример для одной переменной:
# traffic_rate['low'] = fuzz.trapmf(traffic_rate.universe, [0, 0, 1000, 3000])
# ...
# 1. Скорость входящего трафика
traffic_rate['low'] = fuzz.trapmf(traffic_rate.universe, [0, 0, 1000, 3000])
traffic_rate['medium'] = fuzz.trimf(traffic_rate.universe, [2000, 5000, 8000])
traffic_rate['high'] = fuzz.trapmf(traffic_rate.universe, [7000, 9000, 10000, 10000])

# 2. Количество уникальных IP-адресов
unique_ips['few'] = fuzz.trapmf(unique_ips.universe, [0, 0, 200, 600])
unique_ips['moderate'] = fuzz.trimf(unique_ips.universe, [500, 1500, 2500])
unique_ips['many'] = fuzz.trapmf(unique_ips.universe, [2000, 3000, 5000, 5000])

# 3. Среднее время между пакетами
inter_arrival_time['long'] = fuzz.trapmf(inter_arrival_time.universe, [30, 50, 100, 100])
inter_arrival_time['average'] = fuzz.trimf(inter_arrival_time.universe, [10, 30, 50])
inter_arrival_time['short'] = fuzz.trapmf(inter_arrival_time.universe, [0, 0, 10, 20])

# 4. Процент неудачных попыток соединения
failed_conn['low'] = fuzz.trapmf(failed_conn.universe, [0, 0, 10, 30])
failed_conn['medium'] = fuzz.trimf(failed_conn.universe, [20, 50, 80])
failed_conn['high'] = fuzz.trapmf(failed_conn.universe, [70, 90, 100, 100])

# 5. Процент аномальных размеров пакетов
anomalous_packet['normal'] = fuzz.trapmf(anomalous_packet.universe, [0, 0, 5, 15])
anomalous_packet['elevated'] = fuzz.trimf(anomalous_packet.universe, [10, 30, 50])
anomalous_packet['high'] = fuzz.trapmf(anomalous_packet.universe, [40, 60, 100, 100])

# 6. Количество запросов к одному ресурсу
requests_per_resource['low'] = fuzz.trapmf(requests_per_resource.universe, [0, 0, 1000, 3000])
requests_per_resource['medium'] = fuzz.trimf(requests_per_resource.universe, [2000, 5000, 8000])
requests_per_resource['high'] = fuzz.trapmf(requests_per_resource.universe, [7000, 9000, 10000, 10000])

# 7. Вариация размера пакетов
packet_size_variance['low'] = fuzz.trapmf(packet_size_variance.universe, [0, 0, 10, 30])
packet_size_variance['medium'] = fuzz.trimf(packet_size_variance.universe, [20, 50, 80])
packet_size_variance['high'] = fuzz.trapmf(packet_size_variance.universe, [70, 90, 100, 100])

# 8. Скорость SYN-пакетов
syn_rate['low'] = fuzz.trapmf(syn_rate.universe, [0, 0, 1000, 3000])
syn_rate['medium'] = fuzz.trimf(syn_rate.universe, [2000, 5000, 8000])
syn_rate['high'] = fuzz.trapmf(syn_rate.universe, [7000, 9000, 10000, 10000])

# 9. Скорость UDP-пакетов
udp_rate['low'] = fuzz.trapmf(udp_rate.universe, [0, 0, 1000, 3000])
udp_rate['medium'] = fuzz.trimf(udp_rate.universe, [2000, 5000, 8000])
udp_rate['high'] = fuzz.trapmf(udp_rate.universe, [7000, 9000, 10000, 10000])

# 10. Скорость ICMP-пакетов
icmp_rate['low'] = fuzz.trapmf(icmp_rate.universe, [0, 0, 100, 300])
icmp_rate['medium'] = fuzz.trimf(icmp_rate.universe, [200, 500, 800])
icmp_rate['high'] = fuzz.trapmf(icmp_rate.universe, [700, 900, 10000, 10000])

# 11. Процент новых соединений
new_conn_percent['low'] = fuzz.trapmf(new_conn_percent.universe, [0, 0, 10, 30])
new_conn_percent['medium'] = fuzz.trimf(new_conn_percent.universe, [20, 50, 80])
new_conn_percent['high'] = fuzz.trapmf(new_conn_percent.universe, [70, 90, 100, 100])

# 12. Загрузка CPU
cpu_usage['low'] = fuzz.trapmf(cpu_usage.universe, [0, 0, 20, 40])
cpu_usage['medium'] = fuzz.trimf(cpu_usage.universe, [30, 50, 70])
cpu_usage['high'] = fuzz.trapmf(cpu_usage.universe, [60, 80, 100, 100])

# 13. Использование памяти
memory_usage['low'] = fuzz.trapmf(memory_usage.universe, [0, 0, 20, 40])
memory_usage['medium'] = fuzz.trimf(memory_usage.universe, [30, 50, 70])
memory_usage['high'] = fuzz.trapmf(memory_usage.universe, [60, 80, 100, 100])

# 14. Вариация длительности соединений
conn_duration_variance['low'] = fuzz.trapmf(conn_duration_variance.universe, [0, 0, 10, 30])
conn_duration_variance['medium'] = fuzz.trimf(conn_duration_variance.universe, [20, 50, 80])
conn_duration_variance['high'] = fuzz.trapmf(conn_duration_variance.universe, [70, 90, 100, 100])

# 15. Количество полуоткрытых соединений
half_open_conn['low'] = fuzz.trapmf(half_open_conn.universe, [0, 0, 1000, 3000])
half_open_conn['medium'] = fuzz.trimf(half_open_conn.universe, [2000, 5000, 8000])
half_open_conn['high'] = fuzz.trapmf(half_open_conn.universe, [7000, 9000, 10000, 10000])

# 16. Частота ошибок пакетов
error_rate['low'] = fuzz.trapmf(error_rate.universe, [0, 0, 10, 30])
error_rate['medium'] = fuzz.trimf(error_rate.universe, [20, 50, 80])
error_rate['high'] = fuzz.trapmf(error_rate.universe, [70, 90, 100, 100])

# 17. Количество протокольных аномалий
protocol_anomalies['low'] = fuzz.trapmf(protocol_anomalies.universe, [0, 0, 10, 30])
protocol_anomalies['medium'] = fuzz.trimf(protocol_anomalies.universe, [20, 50, 80])
protocol_anomalies['high'] = fuzz.trapmf(protocol_anomalies.universe, [70, 90, 1000, 1000])

# 18. Активность на критических портах
critical_port_activity['low'] = fuzz.trapmf(critical_port_activity.universe, [0, 0, 100, 300])
critical_port_activity['medium'] = fuzz.trimf(critical_port_activity.universe, [200, 500, 800])
critical_port_activity['high'] = fuzz.trapmf(critical_port_activity.universe, [700, 900, 10000, 10000])

# 19. Отношение входящего к исходящему трафику
in_out_ratio['low'] = fuzz.trapmf(in_out_ratio.universe, [0, 0, 0.5, 1.5])
in_out_ratio['balanced'] = fuzz.trimf(in_out_ratio.universe, [1, 2.5, 4])
in_out_ratio['high'] = fuzz.trapmf(in_out_ratio.universe, [3.5, 5, 10, 10])

# 20. Необычное использование протоколов
unusual_protocol_usage['normal'] = fuzz.trapmf(unusual_protocol_usage.universe, [0, 0, 5, 15])
unusual_protocol_usage['elevated'] = fuzz.trimf(unusual_protocol_usage.universe, [10, 30, 50])
unusual_protocol_usage['high'] = fuzz.trapmf(unusual_protocol_usage.universe, [40, 60, 100, 100])

# Функции принадлежности для выходной переменной

ddos_risk['low'] = fuzz.trapmf(ddos_risk.universe, [0, 0, 20, 40])
ddos_risk['medium'] = fuzz.trimf(ddos_risk.universe, [30, 50, 70])
ddos_risk['high'] = fuzz.trapmf(ddos_risk.universe, [60, 80, 100, 100])

# Определение правил нечеткой логики
rule1 = ctrl.Rule(
    traffic_rate['high'] &
    unique_ips['many'] &
    inter_arrival_time['short'] &
    failed_conn['high'] &
    anomalous_packet['high'] &
    requests_per_resource['high'] &
    syn_rate['high'] &
    half_open_conn['high'] &
    cpu_usage['high'] &
    error_rate['high'],
    ddos_risk['high'])

rule2 = ctrl.Rule(
    udp_rate['high'] &
    protocol_anomalies['high'] &
    unusual_protocol_usage['high'],
    ddos_risk['high'])

rule3 = ctrl.Rule(
    traffic_rate['medium'] &
    unique_ips['moderate'] &
    inter_arrival_time['average'] &
    failed_conn['medium'] &
    syn_rate['medium'] &
    cpu_usage['medium'] &
    memory_usage['medium'],
    ddos_risk['medium'])

rule4 = ctrl.Rule(
    traffic_rate['low'] &
    unique_ips['few'] &
    inter_arrival_time['long'] &
    failed_conn['low'] &
    anomalous_packet['normal'] &
    cpu_usage['low'] &
    memory_usage['low'],
    ddos_risk['low'])

rule5 = ctrl.Rule(
    icmp_rate['high'] &
    protocol_anomalies['medium'] &
    unusual_protocol_usage['elevated'],
    ddos_risk['medium'])

rule6 = ctrl.Rule(
    in_out_ratio['high'],
    ddos_risk['high'])

rule7 = ctrl.Rule(
    critical_port_activity['high'],
    ddos_risk['high'])

rule8 = ctrl.Rule(
    conn_duration_variance['high'] &
    packet_size_variance['high'],
    ddos_risk['high'])

rule9 = ctrl.Rule(
    cpu_usage['high'] &
    memory_usage['high'],
    ddos_risk['high'])

rule10 = ctrl.Rule(
    new_conn_percent['high'] &
    traffic_rate['high'],
    ddos_risk['high'])

# Ваши существующие правила
# rule1 = ctrl.Rule(...)
# rule2 = ctrl.Rule(...)
# ...
# Добавляем более общие правила и правило по умолчанию

rule11 = ctrl.Rule(
    (traffic_rate['medium'] & unique_ips['moderate']) |
    (cpu_usage['medium'] & memory_usage['medium']),
    ddos_risk['medium'],
    label='MediumRiskRule'
)

rule12 = ctrl.Rule(
    (traffic_rate['low'] & unique_ips['few']) &
    (cpu_usage['low'] & memory_usage['low']),
    ddos_risk['low'],
    label='LowRiskRule'
)

rule_default = ctrl.Rule(
    antecedent=(cpu_usage['low'] & memory_usage['low']),
    consequent=ddos_risk['low'],
    label='DefaultRule'
)

# Обновляем список правил
rules = [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule_default]

# Создание системы управления и симуляции
ddos_ctrl = ctrl.ControlSystem(rules)
ddos_simulation = ctrl.ControlSystemSimulation(ddos_ctrl)

# Параметры для обработки трафика в реальном времени
TIME_WINDOW = 10  # Вы можете настроить это значение
interface = 'vEthernet (Default Switch)'  # Укажите имя вашего сетевого интерфейса

# Инициализация структур данных
packet_times = deque()
packet_sizes_list = deque()
source_ips = deque()
syn_packets = deque()
udp_packets = deque()
icmp_packets = deque()
half_open_conns = set()
critical_port_activity_times = deque()
packet_errors_times = deque()
conn_durations = []
conn_start_times = {}
total_packets = 0
total_protocols = 0
unusual_protocols = 0

CRITICAL_PORTS = {80, 443, 22, 21, 23}

def process_packet(pkt):
    global total_packets, total_protocols, unusual_protocols
    try:
        packet_time = datetime.fromtimestamp(float(pkt.sniff_timestamp))

        # Удаляем устаревшие данные из очередей
        while packet_times and packet_times[0] < packet_time - timedelta(seconds=TIME_WINDOW):
            packet_times.popleft()
            packet_sizes_list.popleft()

        # Добавляем новый пакет
        packet_times.append(packet_time)
        packet_size = int(pkt.length)
        packet_sizes_list.append(packet_size)

        # Сбор IP-адресов
        if hasattr(pkt, 'ip'):
            src_ip = pkt.ip.src
            source_ips.append((src_ip, packet_time))
            while source_ips and source_ips[0][1] < packet_time - timedelta(seconds=TIME_WINDOW):
                source_ips.popleft()

        # Обработка протоколов
        protocol = pkt.highest_layer
        total_protocols += 1

        if protocol == 'TCP':
            flags = int(pkt.tcp.flags_hex, 16)
            syn_flag = flags & 0x02
            ack_flag = flags & 0x10

            if syn_flag and not ack_flag:
                syn_packets.append(packet_time)
                while syn_packets and syn_packets[0] < packet_time - timedelta(seconds=TIME_WINDOW):
                    syn_packets.popleft()

                src_ip = pkt.ip.src
                dst_ip = pkt.ip.dst
                src_port = pkt.tcp.srcport
                dst_port = pkt.tcp.dstport
                conn_id = (src_ip, src_port, dst_ip, dst_port)
                half_open_conns.add(conn_id)
                conn_start_times[conn_id] = packet_time

            elif syn_flag and ack_flag:
                src_ip = pkt.ip.src
                dst_ip = pkt.ip.dst
                src_port = pkt.tcp.srcport
                dst_port = pkt.tcp.dstport
                conn_id = (dst_ip, dst_port, src_ip, src_port)
                if conn_id in half_open_conns:
                    half_open_conns.remove(conn_id)
                    duration = packet_time - conn_start_times.get(conn_id, packet_time)
                    conn_durations.append(duration.total_seconds())
                    conn_start_times.pop(conn_id, None)

            dst_port = int(pkt.tcp.dstport)
            if dst_port in CRITICAL_PORTS:
                critical_port_activity_times.append(packet_time)
                while critical_port_activity_times and critical_port_activity_times[0] < packet_time - timedelta(seconds=TIME_WINDOW):
                    critical_port_activity_times.popleft()

        elif protocol == 'UDP':
            udp_packets.append(packet_time)
            while udp_packets and udp_packets[0] < packet_time - timedelta(seconds=TIME_WINDOW):
                udp_packets.popleft()

        elif protocol == 'ICMP':
            icmp_packets.append(packet_time)
            while icmp_packets and icmp_packets[0] < packet_time - timedelta(seconds=TIME_WINDOW):
                icmp_packets.popleft()
        else:
            unusual_protocols += 1

        # Обработка ошибок пакетов
        if 'MALFORMED' in pkt:
            packet_errors_times.append(packet_time)
            while packet_errors_times and packet_errors_times[0] < packet_time - timedelta(seconds=TIME_WINDOW):
                packet_errors_times.popleft()

        total_packets += 1
    except Exception:
        pass  # Игнорируем ошибки обработки отдельных пакетов

def compute_variables():
    try:
        if not packet_times:
            return

        time_window = TIME_WINDOW

        # 1. Скорость входящего трафика
        traffic_rate_val = len(packet_times) / time_window  # Пакеты в секунду

        # 2. Количество уникальных IP-адресов
        unique_ips_set = set(ip for ip, t in source_ips)
        unique_ips_val = len(unique_ips_set)

        # 3. Среднее время между пакетами
        packet_times_list = list(packet_times)
        if len(packet_times_list) > 1:
            intervals = [(packet_times_list[i] - packet_times_list[i-1]).total_seconds() * 1000 for i in range(1, len(packet_times_list))]
            inter_arrival_time_val = sum(intervals) / len(intervals)
        else:
            inter_arrival_time_val = 0

        # 4. Процент неудачных попыток соединения
        if len(syn_packets) > 0:
            failed_conn_val = len(half_open_conns) / len(syn_packets) * 100
        else:
            failed_conn_val = 0

        # 5. Процент аномальных размеров пакетов
        packet_sizes_list_local = list(packet_sizes_list)
        if packet_sizes_list_local:
            avg_size = sum(packet_sizes_list_local) / len(packet_sizes_list_local)
            std_size = np.std(packet_sizes_list_local)
            anomalous_packets = [size for size in packet_sizes_list_local if abs(size - avg_size) > 2 * std_size]
            anomalous_packet_val = len(anomalous_packets) / len(packet_sizes_list_local) * 100
        else:
            anomalous_packet_val = 0

        # Устанавливаем средние значения для переменных, которые не реализованы
        requests_per_resource_val = 5000
        new_conn_percent_val = 50
        protocol_anomalies_val = 500
        in_out_ratio_val = 5

        # 7. Вариация размера пакетов
        if packet_sizes_list_local and avg_size != 0:
            packet_size_variance_val = np.var(packet_sizes_list_local) / avg_size * 100
        else:
            packet_size_variance_val = 0

        # 8. Скорость SYN-пакетов
        syn_rate_val = len(syn_packets) / time_window

        # 9. Скорость UDP-пакетов
        udp_rate_val = len(udp_packets) / time_window

        # 10. Скорость ICMP-пакетов
        icmp_rate_val = len(icmp_packets) / time_window

        # 12. Загрузка CPU
        cpu_usage_val = psutil.cpu_percent(interval=None)

        # 13. Использование памяти
        memory_usage_val = psutil.virtual_memory().percent

        # 14. Вариация длительности соединений
        if conn_durations:
            avg_duration = np.mean(conn_durations)
            conn_duration_variance_val = np.var(conn_durations) / avg_duration * 100 if avg_duration != 0 else 0
        else:
            conn_duration_variance_val = 0

        # 15. Количество полуоткрытых соединений
        half_open_conn_val = len(half_open_conns)

        # 16. Частота ошибок пакетов
        if total_packets > 0:
            error_rate_val = len(packet_errors_times) / total_packets * 100
        else:
            error_rate_val = 0

        # 18. Активность на критических портах
        critical_port_activity_val = len(critical_port_activity_times)

        # 20. Необычное использование протоколов
        if total_protocols > 0:
            unusual_protocol_usage_val = unusual_protocols / total_protocols * 100
        else:
            unusual_protocol_usage_val = 0

        # Ограничиваем значения переменных в пределах универсумов
        traffic_rate_val = min(max(traffic_rate_val, 0), 10000)
        unique_ips_val = min(max(unique_ips_val, 0), 5000)
        inter_arrival_time_val = min(max(inter_arrival_time_val, 0), 100)
        failed_conn_val = min(max(failed_conn_val, 0), 100)
        anomalous_packet_val = min(max(anomalous_packet_val, 0), 100)
        packet_size_variance_val = min(max(packet_size_variance_val, 0), 100)
        syn_rate_val = min(max(syn_rate_val, 0), 10000)
        udp_rate_val = min(max(udp_rate_val, 0), 10000)
        icmp_rate_val = min(max(icmp_rate_val, 0), 10000)
        cpu_usage_val = min(max(cpu_usage_val, 0), 100)
        memory_usage_val = min(max(memory_usage_val, 0), 100)
        conn_duration_variance_val = min(max(conn_duration_variance_val, 0), 100)
        half_open_conn_val = min(max(half_open_conn_val, 0), 10000)
        error_rate_val = min(max(error_rate_val, 0), 100)
        critical_port_activity_val = min(max(critical_port_activity_val, 0), 10000)
        in_out_ratio_val = min(max(in_out_ratio_val, 0), 10)
        unusual_protocol_usage_val = min(max(unusual_protocol_usage_val, 0), 100)

        # Сброс симуляции перед новым вычислением
        ddos_simulation.reset()

        # Ввод значений в модель нечеткой логики
        ddos_simulation.input['traffic_rate'] = traffic_rate_val
        ddos_simulation.input['unique_ips'] = unique_ips_val
        ddos_simulation.input['inter_arrival_time'] = inter_arrival_time_val
        ddos_simulation.input['failed_conn'] = failed_conn_val
        ddos_simulation.input['anomalous_packet'] = anomalous_packet_val
        ddos_simulation.input['requests_per_resource'] = requests_per_resource_val
        ddos_simulation.input['packet_size_variance'] = packet_size_variance_val
        ddos_simulation.input['syn_rate'] = syn_rate_val
        ddos_simulation.input['udp_rate'] = udp_rate_val
        ddos_simulation.input['icmp_rate'] = icmp_rate_val
        ddos_simulation.input['new_conn_percent'] = new_conn_percent_val
        ddos_simulation.input['cpu_usage'] = cpu_usage_val
        ddos_simulation.input['memory_usage'] = memory_usage_val
        ddos_simulation.input['conn_duration_variance'] = conn_duration_variance_val
        ddos_simulation.input['half_open_conn'] = half_open_conn_val
        ddos_simulation.input['error_rate'] = error_rate_val
        ddos_simulation.input['protocol_anomalies'] = protocol_anomalies_val
        ddos_simulation.input['critical_port_activity'] = critical_port_activity_val
        ddos_simulation.input['in_out_ratio'] = in_out_ratio_val
        ddos_simulation.input['unusual_protocol_usage'] = unusual_protocol_usage_val

        # Вычисление
        try:
            ddos_simulation.compute()
            ddos_risk_value = ddos_simulation.output.get('ddos_risk', None)
            if ddos_risk_value is not None and not np.isnan(ddos_risk_value):
                print(f"Риск DDoS-атаки: {ddos_risk_value:.2f}%")
            else:
                print("Не удалось вычислить 'ddos_risk'. Проверьте корректность входных данных и правил.")
        except Exception as e:
            print(f"Ошибка при вычислении модели нечеткой логики: {e}")
    except Exception as e:
        print(f"Ошибка в функции compute_variables: {e}")

def capture_packets():
    asyncio.set_event_loop(asyncio.new_event_loop())
    capture = pyshark.LiveCapture(interface=interface)
    for packet in capture.sniff_continuously():
        process_packet(packet)

if __name__ == "__main__":
    # Запускаем поток для захвата пакетов
    capture_thread = threading.Thread(target=capture_packets)
    capture_thread.start()

    # Каждую секунду вычисляем значения входных переменных и риск DDoS-атаки
    while True:
        compute_variables()
        time.sleep(1)