import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Dict
from dotenv import load_dotenv
Load environment variables from .env file
load_dotenv()
app = FastAPI()
Get categories and weights from environment variables
categories = os.getenv("CATEGORIES").split(",")
weights_raw = os.getenv("WEIGHTS").split(";")
weights = {cat: {"w_T": float(w[0]), "w_L": float(w[1]), "w_P": float(w[2])}
for cat, w in zip(categories, (w.split(",") for w in weights_raw))}
if category not in weights:
raise HTTPException(status_code=400, detail="Invalid application category.")
# Get weights
w_T = weights[category]["w_T"]
w_L = weights[category]["w_L"]
w_P = weights[category]["w_P"]
# Normalize values
f_throughput = throughput / THROUGHPUT_MAX # Example normalization factor for throughput
f_latency = (L_MAX - latency) / L_MAX
f_packet_loss = 1 - (packet_loss / 100) # Assuming packet loss is given in percentage
# Calculate QoE score
qoe_score = w_T * f_throughput + w_L * f_latency + w_P * f_packet_loss
return {"QoE Score": qoe_score}
if name == "main":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
you will add update score api to add bytes and latency as input and perform internal
calculation
so you wil ladd bytes and latency as input and internal calculation will be in code
so here is documentaion tha twil help you of calculaion
Here is an expanded version of the README.md file, covering the additional categories you provided:
QoE Calculation Framework
This project provides a framework for calculating Quality of Experience (QoE) scores for various application categories based on network metrics such as throughput, latency, and packet loss. The framework supports categories like Internet Privacy, Social Media, Streaming, Webmail, Gaming, and many more.
Overview
Quality of Experience (QoE) is a measure of how well a network meets the performance needs of a particular application or service, as perceived by the end-user. This project calculates QoE for the following categories based on weighted contributions from throughput, latency, and packet loss:
Categories:
Internet Privacy (VPN, Tor)
Social Media
Domain Name Service (DNS)
Browsing
Assistant
Streaming (Video, Audio)
File Sharing (P2P, Cloud)
Instant Messaging
Net Admin (Network Administration)
Ads & Trackers
Webmail (e.g., Gmail, Outlook)
Gaming
Music Streaming
Voice & Video Calls
Location-Based Services
Email
FTP
IM File Transfer (Instant Messaging File Transfer)
Trading
One Click Hosting
Other
Unknown
Formula
The generic formula for QoE calculation is as follows:
[
QoE = w_T \cdot f_{throughput}(T) + w_L \cdot f_{latency}(L) + w_P \cdot f_{packet_loss}(P)
]
Where:
( w_T ), ( w_L ), and ( w_P ) are the weights for throughput, latency, and packet loss respectively.
( f_{throughput}(T) ), ( f_{latency}(L) ), and ( f_{packet_loss}(P) ) are normalized functions that map throughput, latency, and packet loss into the range [0, 1].
Application Categories and Weight Distribution
Each application category has different weights for throughput, latency, and packet loss based on how critical these factors are for the application's performance.
For categories not listed, you may define custom weight values based on the criticality of throughput, latency, and packet loss for that specific application.
3.21 Unknown
When the application category is unknown, equal weights are applied.
def get_log_level(level_str: str) -> int:
"""
Convert a string log level to a logging level.
"""
level_str = level_str.upper()
if level_str == "INFO":
return logging.INFO
elif level_str == "DEBUG":
return logging.DEBUG
elif level_str == "ERROR":
return logging.ERROR
elif level_str == "CRITICAL":
return logging.CRITICAL
elif level_str == "FATAL":
return logging.FATAL
else:
return logging.INFO # Default level
so recreate it with these changes completed updated and explanation and whanges i say to you
Here's the updated code with the requested changes, explanations, and modifications:
import os
import logging
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Dict
from dotenv import load_dotenv
from threading import Lock
# Load environment variables from .env file
load_dotenv()
app = FastAPI()
# ==================== Logging Configuration ====================
def get_log_level(level_str: str) -> int:
"""
Convert a string log level to a logging level.
"""
level_str = level_str.upper()
if level_str == "INFO":
return logging.INFO
elif level_str == "DEBUG":
return logging.DEBUG
elif level_str == "ERROR":
return logging.ERROR
elif level_str == "CRITICAL":
return logging.CRITICAL
elif level_str == "FATAL":
return logging.FATAL
else:
return logging.INFO # Default level
# Set the log level (You can set via environment variable or default to INFO)
LOG_LEVEL = get_log_level(os.getenv("LOG_LEVEL", "INFO"))
logging.basicConfig(level=LOG_LEVEL)
logger = logging.getLogger(__name__)
# ==================== Application Categories and Weights ====================
categories_weights = {
"Internet Privacy": {"w_T": 0.3, "w_L": 0.5, "w_P": 0.2},
"Domain Name Service": {"w_T": 0.1, "w_L": 0.7, "w_P": 0.2},
"Social Media": {"w_T": 0.5, "w_L": 0.3, "w_P": 0.2},
"Browsing": {"w_T": 0.4, "w_L": 0.4, "w_P": 0.2},
"Streaming": {"w_T": 0.6, "w_L": 0.3, "w_P": 0.1},
"File Sharing": {"w_T": 0.7, "w_L": 0.1, "w_P": 0.2},
"Instant Messaging": {"w_T": 0.4, "w_L": 0.4, "w_P": 0.2},
"Net Admin": {"w_T": 0.5, "w_L": 0.3, "w_P": 0.2},
"Ads & Trackers": {"w_T": 0.2, "w_L": 0.5, "w_P": 0.3},
"Webmail": {"w_T": 0.4, "w_L": 0.4, "w_P": 0.2},
"Gaming": {"w_T": 0.3, "w_L": 0.6, "w_P": 0.1},
"Music Streaming": {"w_T": 0.5, "w_L": 0.4, "w_P": 0.1},
"Voice & Video Calls": {"w_T": 0.3, "w_L": 0.6, "w_P": 0.1},
"Location Based Services": {"w_T": 0.3, "w_L": 0.5, "w_P": 0.2},
"Email": {"w_T": 0.4, "w_L": 0.4, "w_P": 0.2},
"FTP": {"w_T": 0.6, "w_L": 0.3, "w_P": 0.1},
"IM File Transfer": {"w_T": 0.5, "w_L": 0.4, "w_P": 0.1},
"Trading": {"w_T": 0.2, "w_L": 0.7, "w_P": 0.1},
"One Click Hosting": {"w_T": 0.7, "w_L": 0.2, "w_P": 0.1},
"Other": {"w_T": 0.33, "w_L": 0.33, "w_P": 0.34},
"Unknown": {"w_T": 0.33, "w_L": 0.33, "w_P": 0.34},
}
categories = list(categories_weights.keys())
# ==================== Max Latency and Throughput Detection ====================
# Initialize Locks for thread safety
latency_lock = Lock()
throughput_lock = Lock()
# Get initial max values from environment or default
L_MAX = float(os.getenv("L_MAX", 300))
THROUGHPUT_MAX = float(os.getenv("THROUGHPUT_MAX", 1000))
# Observed max values
observed_L_MAX = L_MAX
observed_THROUGHPUT_MAX = THROUGHPUT_MAX
logger.debug(f"Initial L_MAX: {L_MAX}, THROUGHPUT_MAX: {THROUGHPUT_MAX}")
# ==================== Request Models ====================
class QoERequest(BaseModel):
category: str
throughput: float # in Mbps
latency: float # in ms
packet_loss: float # in percentage (0-100)
class UpdateScoreRequest(BaseModel):
category: str
bytes_transferred: float # in bytes
duration: float # in seconds
latency: float # in ms
packet_loss: float # in percentage (0-100)
# ==================== Helper Functions ====================
def calculate_normalized_throughput(throughput):
"""
Normalize throughput value between 0 and 1.
"""
with throughput_lock:
global observed_THROUGHPUT_MAX
if throughput > observed_THROUGHPUT_MAX:
observed_THROUGHPUT_MAX = throughput
logger.debug(f"Updated observed_THROUGHPUT_MAX to {observed_THROUGHPUT_MAX}")
normalized_throughput = throughput / observed_THROUGHPUT_MAX
return normalized_throughput
def calculate_normalized_latency(latency):
"""
Normalize latency value between 0 and 1.
"""
with latency_lock:
global observed_L_MAX
if latency > observed_L_MAX:
observed_L_MAX = latency
logger.debug(f"Updated observed_L_MAX to {observed_L_MAX}")
normalized_latency = (observed_L_MAX - latency) / observed_L_MAX
return normalized_latency
def calculate_normalized_packet_loss(packet_loss):
"""
Normalize packet loss value between 0 and 1.
"""
# Assuming packet loss is given in percentage (0-100)
normalized_packet_loss = 1 - (packet_loss / 100)
return normalized_packet_loss
def calculate_qoe_score(category, throughput, latency, packet_loss):
"""
Calculate QoE score based on the category and network parameters.
"""
if category not in categories_weights:
raise HTTPException(status_code=400, detail="Invalid application category.")
w_T = categories_weights[category]["w_T"]
w_L = categories_weights[category]["w_L"]
w_P = categories_weights[category]["w_P"]
# Normalization
f_throughput = calculate_normalized_throughput(throughput)
f_latency = calculate_normalized_latency(latency)
f_packet_loss = calculate_normalized_packet_loss(packet_loss)
# Ensure normalized values are between 0 and 1
f_throughput = min(max(f_throughput, 0), 1)
f_latency = min(max(f_latency, 0), 1)
f_packet_loss = min(max(f_packet_loss, 0), 1)
# Calculate QoE score
qoe_score = w_T * f_throughput + w_L * f_latency + w_P * f_packet_loss
logger.info(f"Calculated QoE score for category '{category}': {qoe_score}")
logger.debug(f"Weights: w_T={w_T}, w_L={w_L}, w_P={w_P}")
logger.debug(f"Normalized values: f_throughput={f_throughput}, f_latency={f_latency}, f_packet_loss={f_packet_loss}")
return qoe_score
# ==================== API Endpoints ====================
@app.post("/calculate_qoe/")
async def calculate_qoe(request: QoERequest):
"""
Calculate QoE score based on throughput, latency, and packet loss.
"""
qoe_score = calculate_qoe_score(
category=request.category,
throughput=request.throughput,
latency=request.latency,
packet_loss=request.packet_loss,
)
return {"QoE Score": qoe_score}
@app.post("/update_score/")
async def update_score(request: UpdateScoreRequest):
"""
Update score based on bytes transferred, duration, latency, and packet loss.
Throughput is calculated internally from bytes and duration.
"""
# Validate duration
if request.duration <= 0:
raise HTTPException(status_code=400, detail="Duration must be greater than zero.")
# Calculate throughput in Mbps
throughput = (request.bytes_transferred * 8) / request.duration / 1e6 # Convert to Mbps
logger.debug(f"Calculated throughput: {throughput} Mbps from bytes {request.bytes_transferred} and duration {request.duration} seconds.")
# Calculate QoE score
qoe_score = calculate_qoe_score(
category=request.category,
throughput=throughput,
latency=request.latency,
packet_loss=request.packet_loss,
)
return {"QoE Score": qoe_score}
if __name__ == "__main__":
import uvicorn
uvicorn.run("your_script_name:app", host="0.0.0.0", port=8000)
Explanation of Changes:
Logging Configuration: Added logging configuration using the provided prototype. The get_log_level function translates a string to a logging level, and we set up the logger accordingly. This allows for dynamic adjustment of logging levels via an environment variable.
Application Categories and Weights: Defined a dictionary categories_weights containing all the application categories and their respective weights as provided in the documentation. This replaces the previous method of loading categories and weights from environment variables.
Max Latency and Throughput Detection:
Introduced locks (latency_lock and throughput_lock) to ensure thread safety when updating the maximum observed latency (observed_L_MAX) and throughput (observed_THROUGHPUT_MAX).
Initialized observed_L_MAX and observed_THROUGHPUT_MAX with default values from environment variables or fallbacks.
In the normalization functions, if the incoming value exceeds the observed maximum, we update it and log the change.
Request Models:
QoERequest: Used for the /calculate_qoe/ endpoint, takes in throughput, latency, and packet_loss.
UpdateScoreRequest: Used for the new /update_score/ endpoint, takes in bytes_transferred, duration, latency, and packet_loss. The throughput is calculated internally.
Helper Functions:
calculate_normalized_throughput: Normalizes the throughput and updates the observed maximum if the current throughput is higher.
calculate_normalized_latency: Normalizes the latency and updates the observed maximum if the current latency is higher.
calculate_normalized_packet_loss: Normalizes the packet loss percentage to a value between 0 and 1.
calculate_qoe_score: General function to calculate the QoE score using the weights and normalized values. It includes logging of the calculated score and intermediate values.
API Endpoints:
/calculate_qoe/: Existing endpoint updated to use the new function.
Summary of What Has Been Accomplished:
Added an Update Score API: The /update_score/ endpoint allows users to input bytes_transferred and latency (along with duration and packet loss), and performs the internal computation of throughput before calculating the QoE score.
Performed Internal Calculation: The code now includes internal calculations for throughput based on the provided bytes_transferred and duration.
Updated QoE Calculations: Adjusted the QoE calculation framework to support a wide range of application categories with their specific weights as per the documentation.
Implemented Max Latency and Throughput Detection: The application now dynamically updates and uses the maximum observed latency and throughput values in its normalization calculations.
Added Logging Management in Console: Integrated logging throughout the application, including different log levels and detailed debug statements to trace computation values step-by-step.
Ensured Code is Self-Contained and Clear: All necessary configurations and data are included within the code, making it easier to understand and maintain.
This implementation meets the requirements specified and provides a robust framework for calculating QoE scores based on dynamic inputs and internal computations.
/update_score/: New endpoint that takes in bytes_transferred and duration (along with other parameters), calculates the throughput internally, and then calculates the QoE score.
Logging Statements: Added logging throughout the code to track the computation of throughput, updates to maximum observed values, and the calculation of QoE scores.
Error Handling: Added checks to ensure that duration is greater than zero to avoid division by zero. Also, ensured that normalized values stay within the [0, 1] range.