s o i will gave you code
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))}
Get max values from environment variables
L_MAX = float(os.getenv("L_MAX", 300))
THROUGHPUT_MAX = float(os.getenv("THROUGHPUT_MAX", 1000))
Define request body
class QoERequest(BaseModel):
category: str
throughput: float
latency: float
packet_loss: float
return {"QoE Score": qoe_score}
Use code with caution.
if name == "main":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
so here is changes class QoERequest(BaseModel):
category: str
throughput: float
latency: float
packet_loss: float
instead of throuput you will use bytes_transferred, duration, latency, and packet_loss. The throughput is calculated internally.
s ohere is my tasks update score api to add bytes and latency as input and perform internal calculation
and add max latency and mac throughput detection to api
i will gave you a guide will hep you
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:
Assistant
Categories:
Internet Privacy (VPN, Tor)
Social Media
Domain Name Service (DNS)
Browsing
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.
Modify the weights for specific categories if necessary.
Input network metrics for each application category.
Run the script to calculate QoE scores.
Interpret the QoE score (0 = poor, 1 = excellent).
Requirements
Python 3.x
Libraries: numpy (for normalization and calculation)
Contribution
Feel free to submit pull requests if you'd like to improve the QoE calculation framework or add new categories.
so recreate full code with these cahnegs updated completed
use please the env already code uses it
.env
672 B
Categories and their corresponding weights
CATEGORIES="Internet Privacy,Domain Name Service,Social Media,Browsing,Streaming,File Sharing,Instant Messaging,Net Admin,Ads & Trackers,Webmail,Gaming,Music Streaming,Voice & Video Calls,Location Based Services,Email,FTP,IM File Transfer,Trading,One Click Hosting,Other,Unknown"
Weights for each category
WEIGHTS="0.3,0.5,0.2;0.1,0.7,0.2;0.5,0.3,0.2;0.4,0.4,0.2;0.6,0.3,0.1;0.7,0.1,0.2;0.4,0.4,0.2;0.5,0.3,0.2;0.2,0.5,0.3;0.4,0.4,0.2;0.3,0.6,0.1;0.5,0.4,0.1;0.3,0.5,0.2;0.4,0.4,0.2;0.6,0.3,0.1;0.5,0.4,0.1;0.2,0.7,0.1;0.7,0.2,0.1;0.33,0.33,0.34;0.33,0.33,0.34"
Max values for normalization
L_MAX=300
THROUGHPUT_MAX=1000
give complete code with explanation and do my tasks
Sure, here's the updated code with the requested changes and explanations.
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, validator
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.strip(): {"w_T": float(w[0]), "w_L": float(w[1]), "w_P": float(w[2])}
for cat, w in zip(categories, (w.strip().split(",") for w in weights_raw))
}
# Get max values from environment variables
L_MAX = float(os.getenv("L_MAX", 300))
THROUGHPUT_MAX = float(os.getenv("THROUGHPUT_MAX", 1000))
# Define request body with updated fields
class QoERequest(BaseModel):
category: str
bytes_transferred: float
duration: float
latency: float
packet_loss: float
# Validations to ensure proper input values
@validator('bytes_transferred')
def bytes_transferred_must_be_non_negative(cls, v):
if v < 0:
raise ValueError('bytes_transferred must be non-negative')
return v
@validator('duration')
def duration_must_be_positive(cls, v):
if v <= 0:
raise ValueError('duration must be positive and non-zero')
return v
@validator('latency')
def latency_must_be_non_negative(cls, v):
if v < 0:
raise ValueError('latency must be non-negative')
return v
@validator('packet_loss')
def packet_loss_must_be_between_0_and_100(cls, v):
if not 0 <= v <= 100:
raise ValueError('packet_loss must be between 0 and 100')
return v
@app.post("/calculate_qoe/")
async def calculate_qoe(request: QoERequest):
category = request.category.strip()
bytes_transferred = request.bytes_transferred
duration = request.duration
latency = request.latency
packet_loss = request.packet_loss
# Check if the category is valid
if category not in weights:
raise HTTPException(status_code=400, detail="Invalid application category.")
# Calculate throughput internally
throughput = bytes_transferred / duration # in bytes per second
# Initialize flags for max value detection
throughput_capped = False
latency_capped = False
# Check and cap throughput at THROUGHPUT_MAX
if throughput > THROUGHPUT_MAX:
throughput = THROUGHPUT_MAX
throughput_capped = True
# Check and cap latency at L_MAX
if latency > L_MAX:
latency = L_MAX
latency_capped = True
# Get weights for the category
w_T = weights[category]["w_T"]
w_L = weights[category]["w_L"]
w_P = weights[category]["w_P"]
# Normalize the parameters
f_throughput = throughput / THROUGHPUT_MAX # Normalized to [0, 1]
f_latency = (L_MAX - latency) / L_MAX # Higher latency results in lower QoE
f_packet_loss = 1 - (packet_loss / 100) # Packet loss as a percentage
# Ensure normalized values are within [0, 1]
f_throughput = max(0, min(f_throughput, 1))
f_latency = max(0, min(f_latency, 1))
f_packet_loss = max(0, min(f_packet_loss, 1))
# Calculate the QoE score based on weights and normalized values
qoe_score = w_T * f_throughput + w_L * f_latency + w_P * f_packet_loss
return {
"QoE Score": qoe_score,
"throughput": throughput,
"throughput_capped": throughput_capped,
"latency": latency,
"latency_capped": latency_capped,
"normalized_values": {
"f_throughput": f_throughput,
"f_latency": f_latency,
"f_packet_loss": f_packet_loss,
},
"weights": {
"throughput_weight": w_T,
"latency_weight": w_L,
"packet_loss_weight": w_P,
}
}
if __name__ == "__main__":
import uvicorn
# Run the app on host 0.0.0.0 and port 8000
uvicorn.run(app, host="0.0.0.0", port=8000)
Explanation of the Updates
Input Parameters Update: The QoERequest class has been updated to accept bytes_transferred and duration instead of throughput. The throughput is calculated internally within the calculate_qoe function.
Validation of Input Parameters: Validators have been added to ensure that:
bytes_transferred is non-negative.
duration is positive and non-zero to avoid division by zero.
latency is non-negative.
packet_loss is between 0 and 100%.
Throughput Calculation and Max Throughput Detection:
Throughput is calculated as bytes_transferred / duration.
If the calculated throughput exceeds THROUGHPUT_MAX, it is capped at THROUGHPUT_MAX, and a flag throughput_capped is set to True.
Latency Max Value Detection:
If the provided latency exceeds L_MAX, it is capped at L_MAX, and a flag latency_capped is set to True.
Normalization:
Throughput is normalized by dividing by THROUGHPUT_MAX.
Latency is normalized using (L_MAX - latency) / L_MAX to ensure that lower latency results in a higher QoE score.
Packet loss is normalized using 1 - (packet_loss / 100) since higher packet loss negatively impacts QoE.
QoE Score Calculation:
The QoE score is calculated using the formula:
[
QoE = w_T \cdot f_{\text{throughput}} + w_L \cdot f_{\text{latency}} + w_P \cdot f_{\text{packet_loss}}
]
The weights w_T, w_L, and w_P are retrieved based on the application category.
Response Enhancement:
Returns additional information including:
Whether throughput and latency were capped.
The actual throughput and latency values used in the calculation.
The normalized values of throughput, latency, and packet loss.
The weights used for the calculation.
Using the .env File
The .env file is utilized to store:
Categories: A comma-separated list of application categories.
Weights: A semicolon-separated list of weight tuples for each category in the order of throughput, latency, and packet loss weights.
Max Values: L_MAX and THROUGHPUT_MAX for normalization purposes.
The code reads these values using the os.getenv function and parses them appropriately.
Error Handling
Appropriate error handling has been implemented to ensure that:
Invalid application categories result in a 400 Bad Request error.
Invalid input values raise descriptive errors.
Running the Application
To run the application:
Ensure that all dependencies are installed (fastapi, pydantic, uvicorn, python-dotenv).
Run the script using the command:
uvicorn your_script_name:app --reload
Replace your_script_name with the name of your Python file.