Objectif global :
Concevoir et implémenter une base de données SQLite3 pour suivre et prédire les durées de dédouanement douanier de colis expédiés via des vols cargo réguliers.
Les données seront collectées en temps réel via des requêtes API et injectées dans la base.
L'objectif final est d'analyser et modéliser les facteurs influençant le délai entre :
Étape 220 : "Cargo flight departed" (départ du vol cargo du pays A).
Étape 370 : "Customs Clearance Completed" (fin du dédouanement dans le pays B).
Spécifications détaillées :
Structure de la base de données :
Créer 7 tables principales avec des relations SQL cohérentes :
parcels (colis) : Infos de base sur chaque colis (tracking number, pays de destination, etc.).
customs_lots (lots douaniers) : Groupe de colis ayant pris le même vol cargo.
tracking_steps (étapes de suivi) : Historique horodaté de chaque colis (codes étapes : 220, 370, etc.).
customs_batches (nouvelle entité) : Sessions de dédouanement groupées (quand ≥20 colis marqués 370 en peu de temps).
queue_status (file d'attente) : État de la file d'attente des lots à des moments précis.
holidays (jours fériés) : Liste des jours non ouvrables dans le pays de destination.
action_code_names : description textuelle des action code
Mettre en place des clés étrangères pour lier les tables logiquement.
Ajouter des index optimisés pour accélérer les requêtes fréquentes (ex: timestamp, action_code, lot_id, etc.).
Notion de "Customs Batch" (Batch douanier) :
Un batch est déclenché quand ≥20 colis reçoivent le code 370 ("Customs Clearance Completed") dans un intervalle serré (~quelques minutes).
Caractéristiques à capturer :
start_timestamp : Horodatage du 1er colis marqué 370 du groupe.
end_timestamp : Horodatage du dernier colis marqué 370 du groupe.
batch_size : Nombre total de colis dans ce batch (≥20).
processing_duration : Durée en secondes entre start_timestamp et end_timestamp.
avg_processing_speed : Vitesse moyenne (colis/heure) calculée automatiquement.
Règle métier : Si l'écart entre deux marquages 370 dépasse 15 minutes, c'est un nouveau batch qui commence.
Collecte des données via API :
Les données arriveront par requêtes HTTP/JSON (probablement ~1 à 5 fois par heure).
Chaque requête contiendra :
Un ou plusieurs numéros de tracking avec leurs étapes horodatées (ex: {parcel_id, action_code, timestamp}).
Éventuellement des métadonnées vol (départ, arrivée, code vol) si elles n'existent pas déjà.
Chaque étape reçue doit :
Être insérée dans tracking_steps.
Déclencher la logique de détection de batch si c'est un code 370.
Traitements automatisés :
Détection des customs batches en temps réel (regrouper les 370 par paquets rapprochés).
Mise à jour des customs_lots avec le batch_id correspondant.
Calcul automatique des durées (processing_duration) et vitesses (avg_processing_speed).
Analyses prévues :
Statistiques journalières : Nombre de batches, colis traités, durée moyenne, etc.
Évolution mensuelle de la performance douanière.
Modélisation prédictive (Machine Learning) pour anticiper les durées de dédouanement futures en fonction :
Jour de la semaine / heure de départ.
Taille du lot douanier.
File d'attente estimée.
Présence de jours fériés proches.
**"Conçois une base de données SQLite3 optimisée pour suivre et analyser les durées de dédouanement douanier de colis.
Les données arriveront en temps réel via API JSON.
Réalise les tâches suivantes :
Écris le code Python 3.10 complet pour :
Initialiser la base SQLite (CREATE TABLE, INDEX, TRIGGER si besoin).
Définir 7 tables : parcels, customs_lots, cargo_flights, tracking_steps, customs_batches, queue_status, holidays.
Intégrer la logique de détection automatique des 'customs batches' (≥20 colis marqués 370 en <15 minutes).
Mettre à jour les customs_lots avec le batch_id associé.
Simule l'injection de données via un exemple d'API JSON (colis + étapes de tracking).
Exemple d'entrée :
{
"tracking_number": "MA047420310R",
"steps": [
{"action_code": "220", "timestamp": "2025-01-12 08:30:00"},
{"action_code": "230", "timestamp": "2025-01-13 10:15:00"},
{"action_code": "370", "timestamp": "2025-01-14 09:02:00"}
],
"flight_info": {"departure_date": "2025-01-12 08:30:00", "flight_code": "AF1234"}
}
Fournis des exemples de requêtes SQL pour :
Extraire les KPIs journaliers (nb batches, durée moyenne, etc.).
Analyser l'impact du jour de la semaine sur la vitesse de dédouanement.
Lister les lots encore en attente (pas de 370 reçu depuis >3 jours).
Ébauche un modèle prédictif simplifié (Python sklearn) pour estimer la durée 220 → 370 en fonction des features (jour, taille lot, file d'attente, etc.).
Contraintes techniques :
Utilise SQLite3 (pas de PostgreSQL/MySQL).
Code Python doit être PEP8 (lisible, commenté, black formaté).
Évite les SELECT * dans les requêtes finales (nomme explicitement les colonnes).
Documente chaque table + chaque fonction Python (docstrings).
Livrables attendus :
Un script init_db.py pour créer les tables/index.
Un script insert_data.py simulant l'API + la détection de batches.
Un notebook Jupyter (analysis.ipynb) avec les requêtes SQL + modèle ML de base.
Bonus si :
Tu intègres une vue matérialisée pour les stats journalières.
Tu proposes une alerte automatique (ex: par mail) si un batch dépasse 24h.
Prêt ? Vas-y !"**
# insert_data.py
import sqlite3
import json
from datetime import datetime, timedelta
from dateutil.parser import parse as parse_timestamp # More robust parsing
# Define the database file path
DB_FILE = 'customs_tracking.db'
# Global variable (in a real app, state management would be more sophisticated)
# To keep track of recent unbatched 370 steps for batch detection
# Format: {step_id: datetime_obj, ...}
# We'll store step_id and timestamp, and query the DB for current state
# when a 370 arrives. A global list is fragile for concurrent access,
# but sufficient for this script simulation.
_pending_370_steps = []
BATCH_WINDOW_MINUTES = 15
BATCH_MIN_SIZE = 20
def get_db_connection():
"""Gets a database connection."""
conn = sqlite3.connect(DB_FILE)
# Configure connection for row access by column name
conn.row_factory = sqlite3.Row
return conn
def process_batch_detection(conn, inserted_step_id):
"""
Checks for and creates customs batches based on recent 370 steps.
Triggered after a new 370 step is inserted.
"""
cursor = conn.cursor()
# Get the newly inserted 370 step
cursor.execute("SELECT step_id, timestamp FROM tracking_steps WHERE step_id = ? AND action_code = '370';", (inserted_step_id,))
new_step = cursor.fetchone()
if not new_step:
# This should not happen if called correctly after inserting a 370
return
new_timestamp_str = new_step['timestamp']
new_timestamp = parse_timestamp(new_timestamp_str)
window_start_time = new_timestamp - timedelta(minutes=BATCH_WINDOW_MINUTES)
# Find all unbatched 370 steps within the sliding window (including the new one)
# Order by timestamp to easily find the earliest/latest
cursor.execute("""
SELECT step_id, timestamp
FROM tracking_steps
WHERE action_code = '370'
AND batch_id IS NULL
AND timestamp >= ? -- Window start
ORDER BY timestamp;
""", (window_start_time.strftime('%Y-%m-%d %H:%M:%S'),)) # Use string for DB query
recent_unbatched_steps = cursor.fetchall()
# Convert timestamps to datetime objects for calculations
steps_with_dt = [(step['step_id'], parse_timestamp(step['timestamp'])) for step in recent_unbatched_steps]
# Check for batch condition: >= BATCH_MIN_SIZE steps in the group
if len(steps_with_dt) >= BATCH_MIN_SIZE:
earliest_step_id, earliest_timestamp = steps_with_dt[0]
latest_step_id, latest_timestamp = steps_with_dt[-1]
duration = latest_timestamp - earliest_timestamp
# Check if the time span of these steps is within the window
# (This second check is technically redundant if we query 'timestamp >= window_start_time'
# and the number is >= 20, *unless* steps could arrive significantly out of order.
# Let's keep it simple and rely on the query window and count.
# The prompt says "intervalle serré (~quelques minutes)" and the 15 min rule.
# A simple rule: if the number of UNBATCHED 370s in the last 15 mins >= 20, batch them all.)
# Refined simple rule: If the number of UNBATCHED 370s in the last 15 mins >= 20
# AND the time between the EARLIEST and LATEST of *these specific steps* is <= 15 mins, create the batch.
if duration <= timedelta(minutes=BATCH_WINDOW_MINUTES):
# Create a new batch
batch_size = len(steps_with_dt)
processing_duration_seconds = int(duration.total_seconds())
avg_speed = (batch_size / processing_duration_seconds) * 3600 if processing_duration_seconds > 0 else 0
cursor.execute("""
INSERT INTO customs_batches (start_timestamp, end_timestamp, batch_size, processing_duration_seconds, avg_processing_speed_per_hour)
VALUES (?, ?, ?, ?, ?)
""", (earliest_timestamp.strftime('%Y-%m-%d %H:%M:%S'),
latest_timestamp.strftime('%Y-%m-%d %H:%M:%S'),
batch_size,
processing_duration_seconds,
avg_speed))
batch_id = cursor.lastrowid
# Assign the new batch_id to all included steps
step_ids_to_update = [step[0] for step in steps_with_dt]
cursor.executemany("""
UPDATE tracking_steps
SET batch_id = ?
WHERE step_id = ?;
""", [(batch_id, step_id) for step_id in step_ids_to_update])
conn.commit()
print(f"Created new customs batch {batch_id} with {batch_size} parcels (Duration: {processing_duration_seconds}s)")
# Else: Not enough steps within the _specific_ time window of the fetched group, or group too small.
# The steps remain unbatched for now, waiting for more 370s to arrive.
# Else: Fewer than BATCH_MIN_SIZE unbatched steps in the window. No batch yet.
def process_api_data(data):
"""
Processes a single API data payload (JSON structure).
Inserts data and triggers batch detection if a 370 step is present.
"""
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor()
tracking_number = data.get("tracking_number")
steps_data = data.get("steps", [])
flight_info = data.get("flight_info", {})
destination_country = data.get("destination_country", "Unknown") # Assume destination country is provided
if not tracking_number or not steps_data or not flight_info:
print(f"Skipping invalid data payload: {data}")
return
flight_code = flight_info.get("flight_code")
departure_timestamp_str = flight_info.get("departure_date") # API uses "departure_date"
arrival_timestamp_str = flight_info.get("arrival_date") # API might include arrival
# 1. Handle Flight Info
flight_id = None
if flight_code and departure_timestamp_str:
cursor.execute("SELECT flight_id FROM cargo_flights WHERE flight_code = ? AND departure_timestamp = ?",
(flight_code, departure_timestamp_str))
flight_row = cursor.fetchone()
if flight_row:
flight_id = flight_row['flight_id']
# print(f"Found existing flight {flight_code}")
else:
# Insert new flight
cursor.execute("""
INSERT INTO cargo_flights (flight_code, departure_timestamp, arrival_timestamp, origin_country, destination_country)
VALUES (?, ?, ?, ?, ?)
""", (flight_code, departure_timestamp_str, arrival_timestamp_str, flight_info.get("origin_country"), destination_country)) # Assume origin from API
flight_id = cursor.lastrowid
print(f"Inserted new flight {flight_code} with ID {flight_id}")
conn.commit() # Commit flight insertion
# 2. Handle Parcel and Lot
parcel_id = None
lot_id = None
# Check if parcel exists
cursor.execute("SELECT parcel_id, lot_id FROM parcels WHERE tracking_number = ?", (tracking_number,))
parcel_row = cursor.fetchone()
if parcel_row:
parcel_id = parcel_row['parcel_id']
lot_id = parcel_row['lot_id']
# print(f"Found existing parcel {tracking_number} with ID {parcel_id}")
# If flight info is new/different and parcel was unassigned or on a different flight,
# potentially update lot or create a new one. For simplicity here, if flight_id exists,
# ensure the parcel is linked to a lot for that flight.
if flight_id and (lot_id is None or cursor.execute("SELECT 1 FROM customs_lots WHERE lot_id = ? AND flight_id = ?", (lot_id, flight_id)).fetchone() is None):
# Parcel exists but isn't linked to the correct lot/flight. Create or find suitable lot.
print(f"Updating lot link for parcel {tracking_number}...")
# Find if a lot already exists for this flight
cursor.execute("SELECT lot_id FROM customs_lots WHERE flight_id = ?", (flight_id,))
lot_row = cursor.fetchone()
if lot_row:
lot_id = lot_row['lot_id']
print(f" - Found existing lot {lot_id} for flight {flight_id}. Assigning parcel.")
else:
# Create a new lot for this flight
cursor.execute("INSERT INTO customs_lots (flight_id, destination_country) VALUES (?, ?)", (flight_id, destination_country))
lot_id = cursor.lastrowid
print(f" - Created new lot {lot_id} for flight {flight_id}. Assigning parcel.")
# Update parcel's lot_id
cursor.execute("UPDATE parcels SET lot_id = ? WHERE parcel_id = ?", (lot_id, parcel_id))
conn.commit()
else:
# Parcel is new
print(f"Inserting new parcel {tracking_number}")
# Find or create a lot for this flight
if flight_id:
cursor.execute("SELECT lot_id FROM customs_lots WHERE flight_id = ?", (flight_id,))
lot_row = cursor.fetchone()
if lot_row:
lot_id = lot_row['lot_id']
# print(f" - Found existing lot {lot_id} for flight {flight_id}")
else:
# Create a new lot for this flight
cursor.execute("INSERT INTO customs_lots (flight_id, destination_country) VALUES (?, ?)", (flight_id, destination_country))
lot_id = cursor.lastrowid
print(f" - Created new lot {lot_id} for flight {flight_id}")
# else: parcel arrives without flight info initially? Handle if needed.
cursor.execute("""
INSERT INTO parcels (tracking_number, destination_country, lot_id)
VALUES (?, ?, ?)
""", (tracking_number, destination_country, lot_id))
parcel_id = cursor.lastrowid
conn.commit() # Commit parcel insertion
# Update actual_parcel_count for the lot if a lot was assigned
if lot_id:
cursor.execute("UPDATE customs_lots SET actual_parcel_count = (SELECT COUNT(*) FROM parcels WHERE lot_id = ?) WHERE lot_id = ?", (lot_id, lot_id))
conn.commit()
# 3. Handle Tracking Steps
inserted_step_ids = [] # Keep track of newly inserted steps
for step in steps_data:
action_code = step.get("action_code")
timestamp_str = step.get("timestamp")
location = step.get("location")
if not action_code or not timestamp_str:
print(f"Skipping invalid step data for {tracking_number}: {step}")
continue
# Check if this specific step (parcel_id, action_code, timestamp) already exists
# This helps prevent duplicate inserts from repeated API calls
cursor.execute("""
SELECT step_id FROM tracking_steps
WHERE parcel_id = ? AND action_code = ? AND timestamp = ?
""", (parcel_id, action_code, timestamp_str))
existing_step = cursor.fetchone()
if existing_step:
# print(f"Step {action_code} at {timestamp_str} for {tracking_number} already exists.")
# If the existing step is a 370 and is currently unbatched,
# re-run batch detection with its ID. This handles cases where
# a step was inserted but didn't trigger batching initially,
# but now *does* because new 370s arrived.
if action_code == '370' and existing_step['batch_id'] is None:
inserted_step_ids.append(existing_step['step_id']) # Add existing step ID to list
continue # Skip insertion
# Insert the new step
cursor.execute("""
INSERT INTO tracking_steps (parcel_id, action_code, timestamp, location)
VALUES (?, ?, ?, ?)
""", (parcel_id, action_code, timestamp_str, location))
new_step_id = cursor.lastrowid
conn.commit() # Commit each step insertion (or batch commits for performance)
print(f"Inserted step {action_code} at {timestamp_str} for {tracking_number}")
# If it's a 370 step, trigger batch detection
if action_code == '370':
inserted_step_ids.append(new_step_id) # Add new step ID to list
# 4. Run batch detection for any newly inserted or processed 370 steps
for step_id in inserted_step_ids:
process_batch_detection(conn, step_id)
except sqlite3.Error as e:
print(f"Database error processing data for {tracking_number}: {e}")
if conn:
conn.rollback() # Roll back changes on error
except Exception as e:
print(f"An error occurred processing data for {tracking_number}: {e}")
if conn:
conn.rollback()
finally:
if conn:
conn.close()
# --- Simulation Data ---
# Need data that simulates steps arriving, including >20 steps for batching
# Helper to generate steps with incremental timestamps
def generate_steps(tracking_number, base_timestamp, action_codes, time_increment_seconds, flight_code, flight_departure, destination_country="FR"):
steps = []
current_timestamp = parse_timestamp(base_timestamp)
for code in action_codes:
steps.append({
"action_code": code,
"timestamp": current_timestamp.strftime('%Y-%m-%d %H:%M:%S')
# Add location data if needed
})
current_timestamp += timedelta(seconds=time_increment_seconds)
return {
"tracking_number": tracking_number,
"steps": steps,
"flight_info": {"flight_code": flight_code, "departure_date": flight_departure},
"destination_country": destination_country
}
# Simulate data arriving over time
# Initial data (Flight AF1234, Lot for this flight)
data_payload_1 = generate_steps(
"MA001", "2025-01-12 08:30:00", ["220", "230", "250", "300"], 10000, "AF1234", "2025-01-12 08:30:00"
)
data_payload_2 = generate_steps(
"MA002", "2025-01-12 08:35:00", ["220", "230", "250", "300"], 9800, "AF1234", "2025-01-12 08:30:00"
)
data_payload_3 = generate_steps(
"MA003", "2025-01-12 08:40:00", ["220", "230", "250", "300"], 10200, "AF1234", "2025-01-12 08:30:00"
)
# Simulate first 370s (not enough for batch)
data_payload_4 = generate_steps(
"MA001", "2025-01-14 09:02:00", ["370"], 0, "AF1234", "2025-01-12 08:30:00" # MA001 gets 370
)
data_payload_5 = generate_steps(
"MA002", "2025-01-14 09:03:30", ["370"], 0, "AF1234", "2025-01-12 08:30:00" # MA002 gets 370 ~1.5 min later
)
data_payload_6 = generate_steps(
"MA003", "2025-01-14 09:04:50", ["370"], 0, "AF1234", "2025-01-12 08:30:00" # MA003 gets 370 ~1.3 min later
)
# Simulate a bulk of 370s arriving quickly to trigger a batch
bulk_370_payloads = []
base_batch_time = parse_timestamp("2025-01-14 09:05:00")
# Generate 25 parcels receiving 370 within the next ~5 minutes
for i in range(4, 29): # MA004 to MA028
tn = f"MA{i:03d}"
# Simulate some earlier steps for these parcels
earlier_steps = generate_steps(tn, f"2025-01-12 09:{i:02d}:00", ["220", "230", "250", "300"], 8000 + i*10, "AF1234", "2025-01-12 08:30:00")
bulk_370_payloads.append(earlier_steps)
# Simulate the 370 step arriving within a tight window
batch_timestamp = base_batch_time + timedelta(seconds=i * 10) # 10 seconds apart
bulk_370_payloads.append({
"tracking_number": tn,
"steps": [{"action_code": "370", "timestamp": batch_timestamp.strftime('%Y-%m-%d %H:%M:%S')}],
"flight_info": {"flight_code": "AF1234", "departure_date": "2025-01-12 08:30:00"}, # Include flight info again
"destination_country": "FR"
})
# Simulate more data later
data_payload_late_370 = generate_steps(
"MA001", "2025-01-14 10:00:00", ["400"], 0, "AF1234", "2025-01-12 08:30:00" # MA001 gets 400 (already had 370)
)
data_payload_another_flight = generate_steps(
"MB101", "2025-01-15 10:00:00", ["220", "230", "300"], 5000, "LH5678", "2025-01-15 10:00:00", "DE" # Different flight, different country
)
# Simulate queue status snapshots (manual insertion)
def insert_queue_status_snapshot(conn, timestamp_str):
"""Simulates taking a queue status snapshot."""
cursor = conn.cursor()
# Count parcels with 220 step but no 370 step
cursor.execute("""
SELECT COUNT(DISTINCT p.parcel_id)
FROM parcels p
JOIN tracking_steps t220 ON p.parcel_id = t220.parcel_id AND t220.action_code = '220'
LEFT JOIN tracking_steps t370 ON p.parcel_id = t370.parcel_id AND t370.action_code = '370'
WHERE t370.step_id IS NULL;
""")
parcels_awaiting = cursor.fetchone()[0]
# Count lots where at least one parcel has 220 but no 370
cursor.execute("""
SELECT COUNT(DISTINCT cl.lot_id)
FROM customs_lots cl
JOIN parcels p ON cl.lot_id = p.lot_id
JOIN tracking_steps t220 ON p.parcel_id = t220.parcel_id AND t220.action_code = '220'
LEFT JOIN tracking_steps t370 ON p.parcel_id = t370.parcel_id AND t370.action_code = '370'
WHERE t370.step_id IS NULL;
""") # This counts lots with *any* parcel awaiting clearance.
# A more accurate "lot in queue" might be lots where *all* parcels are awaiting 370,
# but the simple count is easier for simulation. Let's use the count of lots with *at least one* parcel awaiting 370.
lots_awaiting = cursor.fetchone()[0]
cursor.execute("""
INSERT INTO queue_status (timestamp, lots_awaiting_clearance, parcels_awaiting_clearance)
VALUES (?, ?, ?)
""", (timestamp_str, lots_awaiting, parcels_awaiting))
conn.commit()
print(f"Inserted queue status snapshot at {timestamp_str}: {lots_awaiting} lots, {parcels_awaiting} parcels awaiting.")
if __name__ == "__main__":
# Ensure DB is initialized
print("Ensuring database is initialized...")
# You might want to run init_db.py separately first, or include its logic here
# For simplicity, let's assume init_db.py has been run.
# If running this script standalone, uncomment the following:
# import init_db
# init_db.create_tables(get_db_connection())
# init_db.populate_lookup_data(get_db_connection())
# init_db.create_views(get_db_connection())
print("Database is ready.")
# Process simulated data payloads in chronological order of first relevant event
# (Approximation based on how APIs might send data)
print("\n--- Processing initial data ---")
process_api_data(data_payload_1)
process_api_data(data_payload_2)
process_api_data(data_payload_3)
# Simulate queue status after initial data
with get_db_connection() as conn:
insert_queue_status_snapshot(conn, "2025-01-13 12:00:00")
print("\n--- Processing early 370s (should not form a batch) ---")
process_api_data(data_payload_4) # MA001 370
process_api_data(data_payload_5) # MA002 370
process_api_data(data_payload_6) # MA003 370
# Simulate queue status after a few 370s
with get_db_connection() as conn:
insert_queue_status_snapshot(conn, "2025-01-14 09:04:00")
print("\n--- Processing bulk 370s (should trigger a batch) ---")
# Process the earlier steps first for the bulk parcels
for i in range(0, len(bulk_370_payloads), 2):
process_api_data(bulk_370_payloads[i]) # Earlier steps
# Now process the 370 steps for the bulk parcels
for i in range(1, len(bulk_370_payloads), 2):
process_api_data(bulk_370_payloads[i]) # 370 steps
# Simulate queue status after batch clearance
with get_db_connection() as conn:
insert_queue_status_snapshot(conn, "2025-01-14 09:15:00")
print("\n--- Processing more data ---")
process_api_data(data_payload_late_370) # MA001 400 step
process_api_data(data_payload_another_flight) # New flight/lot
print("\n--- Simulation complete ---")
# analysis.ipynb
# To run this notebook, make sure you have pandas, sqlite3, and scikit-learn installed:
# pip install pandas scikit-learn jupyter matplotlib seaborn ipywidgets dateutil
import sqlite3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
import dateutil.parser
# Define the database file path
DB_FILE = 'customs_tracking.db'
# --- Database Connection ---
def get_db_connection():
"""Gets a database connection."""
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row # Access columns by name
return conn
# Test connection
try:
conn = get_db_connection()
print("Successfully connected to the database.")
conn.close()
except Exception as e:
print(f"Error connecting to the database: {e}")
# --- SQL Queries ---
print("\n--- Running SQL Queries ---")
conn = get_db_connection()
cursor = conn.cursor()
# Helper function to run queries and display results
def run_query(query, params=None):
print(f"\n--- Executing Query ---")
print(query)
if params:
print(f"Parameters: {params}")
try:
cursor.execute(query, params or ())
rows = cursor.fetchall()
if rows:
# Convert to pandas DataFrame for better display
df = pd.DataFrame([dict(row) for row in rows])
print(f"Found {len(rows)} rows.")
print(df.to_markdown(index=False)) # Use to_markdown if available, otherwise .to_string()
else:
print("No results found.")
except sqlite3.Error as e:
print(f"SQL Error: {e}")
print("------------------------")
# 1. Extract daily KPIs (Nb batches, parcels processed in batches, avg batch duration)
run_query("""
SELECT
DATE(start_timestamp) AS batch_date,
COUNT(batch_id) AS number_of_batches,
SUM(batch_size) AS total_parcels_in_batches,
AVG(processing_duration_seconds) AS avg_batch_duration_seconds,
AVG(avg_processing_speed_per_hour) AS avg_batch_speed_per_hour
FROM customs_batches
GROUP BY batch_date
ORDER BY batch_date;
""")
# 2. Analyze overall 220 -> 370 clearance duration distribution
# Using the pre-calculated view
run_query("""
SELECT
COUNT(parcel_id) AS total_cleared_parcels,
AVG(duration_seconds) AS avg_clearance_duration_seconds,
MIN(duration_seconds) AS min_clearance_duration_seconds,
MAX(duration_seconds) AS max_clearance_duration_seconds,
SUM(CASE WHEN duration_seconds <= 3600 THEN 1 ELSE 0 END) * 100.0 / COUNT(parcel_id) AS percent_cleared_under_1_hour,
SUM(CASE WHEN duration_seconds <= 24*3600 THEN 1 ELSE 0 END) * 100.0 / COUNT(parcel_id) AS percent_cleared_under_24_hours
FROM parcel_clearance_duration;
""")
# 3. Analyze impact of day of the week on clearance duration (using 220 step day)
# Note: SQLite STRFTIME('%w') is Sunday=0..Saturday=6
run_query("""
SELECT
start_day_of_week, -- 0=Sunday, 1=Monday, ... 6=Saturday
COUNT(parcel_id) AS parcels_cleared_started_this_day,
AVG(duration_seconds) AS avg_clearance_duration_seconds
FROM parcel_clearance_duration
GROUP BY start_day_of_week
ORDER BY start_day_of_week;
""")
# 4. Analyze impact of estimated lot size (if available) on clearance duration
# Join parcel durations with their lot's estimated size
run_query("""
SELECT
cl.estimated_parcel_count,
COUNT(pcd.parcel_id) AS parcels_in_lots_with_this_estimate,
AVG(pcd.duration_seconds) AS avg_clearance_duration_seconds
FROM parcel_clearance_duration pcd
JOIN customs_lots cl ON pcd.lot_id = cl.lot_id
WHERE cl.estimated_parcel_count IS NOT NULL AND cl.estimated_parcel_count > 0
GROUP BY cl.estimated_parcel_count
ORDER BY cl.estimated_parcel_count;
""") # This requires estimated_parcel_count to be populated during data insertion
# Let's use actual parcel count per lot arriving on the flight instead
run_query("""
SELECT
cl.actual_parcel_count,
COUNT(pcd.parcel_id) AS parcels_cleared_from_lot_size,
AVG(pcd.duration_seconds) AS avg_clearance_duration_seconds
FROM parcel_clearance_duration pcd
JOIN customs_lots cl ON pcd.lot_id = cl.lot_id
WHERE cl.actual_parcel_count > 0
GROUP BY cl.actual_parcel_count
ORDER BY cl.actual_parcel_count;
""")
# 5. List lots still awaiting clearance (e.g., no 370 step received for any parcel in the lot)
# Refined query: Lots that have at least one parcel with a 220 step, but NO parcel with a 370 step.
run_query("""
SELECT
cl.lot_id,
cl.lot_number,
cl.flight_id,
cl.actual_parcel_count,
MIN(t220.timestamp) AS first_220_in_lot
FROM customs_lots cl
JOIN parcels p ON cl.lot_id = p.lot_id
JOIN tracking_steps t220 ON p.parcel_id = t220.parcel_id AND t220.action_code = '220'
LEFT JOIN tracking_steps t370 ON p.parcel_id = t370.parcel_id AND t370.action_code = '370'
GROUP BY cl.lot_id, cl.lot_number, cl.flight_id, cl.actual_parcel_count
HAVING COUNT(t220.step_id) > 0 -- Ensure there was at least one 220 in the lot
AND COUNT(t370.step_id) = 0; -- Ensure NO 370 in the lot
""")
# 6. List lots potentially "stuck" (e.g., oldest lots from the previous query)
# Filter the previous query results by the first 220 timestamp
run_query("""
SELECT
cl.lot_id,
cl.lot_number,
cl.flight_id,
cl.actual_parcel_count,
MIN(t220.timestamp) AS first_220_in_lot
FROM customs_lots cl
JOIN parcels p ON cl.lot_id = p.lot_id
JOIN tracking_steps t220 ON p.parcel_id = t220.parcel_id AND t220.action_code = '220'
LEFT JOIN tracking_steps t370 ON p.parcel_id = t370.parcel_id AND t370.action_code = '370'
GROUP BY cl.lot_id, cl.lot_number, cl.flight_id, cl.actual_parcel_count
HAVING COUNT(t220.step_id) > 0
AND COUNT(t370.step_id) = 0
AND MIN(t220.timestamp) < DATE('now', '-3 days'); -- First 220 was more than 3 days ago
""")
conn.close()
# --- Basic Machine Learning Model ---
print("\n--- Training Basic ML Model ---")
conn = get_db_connection()
# Load data from the view into a pandas DataFrame
# Only select columns useful for prediction features and the target
query = """
SELECT
duration_seconds,
start_date,
start_day_of_week,
lot_id,
batch_id -- Include batch_id to see if we can predict *within* a batch (or exclude if predicting before batch)
FROM parcel_clearance_duration
WHERE duration_seconds IS NOT NULL AND duration_seconds > 0;
"""
df = pd.read_sql_query(query, conn)
conn.close()
print(f"Loaded {len(df)} cleared parcels for ML.")
if len(df) < 10: # Need at least some data
print("Not enough data to train the ML model.")
else:
# Feature Engineering
df['start_date'] = pd.to_datetime(df['start_date'])
# Day of week is already 0-6 from SQL, but let's ensure type
df['start_day_of_week'] = df['start_day_of_week'].astype(int)
# Add lot size as a feature (actual count)
conn = get_db_connection()
lot_counts_df = pd.read_sql_query("SELECT lot_id, actual_parcel_count FROM customs_lots;", conn)
conn.close()
df = pd.merge(df, lot_counts_df, on='lot_id', how='left')
df['actual_parcel_count'] = df['actual_parcel_count'].fillna(df['actual_parcel_count'].median()) # Handle potential missing lot counts
# Add holiday proximity feature (e.g., number of holidays in the next 7 days)
conn = get_db_connection()
holidays_df = pd.read_sql_query("SELECT holiday_date FROM holidays WHERE country_code = 'FR';", conn) # Assuming FR for now
conn.close()
holidays = pd.to_datetime(holidays_df['holiday_date']).tolist()
def count_holidays_in_next_n_days(start_date, holidays_list, n_days=7):
count = 0
end_date = start_date + timedelta(days=n_days)
for holiday in holidays_list:
# Check if the holiday is between the start date (exclusive) and end date (inclusive)
if start_date < holiday <= end_date:
count += 1
return count
# This might be slow on large datasets, but fine for simulation
df['holidays_in_next_7_days'] = df['start_date'].apply(lambda x: count_holidays_in_next_n_days(x, holidays))
# Add a feature for whether the parcel was cleared as part of a batch
df['cleared_in_batch'] = df['batch_id'].apply(lambda x: 1 if pd.notna(x) else 0)
# Select Features and Target
features = ['start_day_of_week', 'actual_parcel_count', 'holidays_in_next_7_days', 'cleared_in_batch']
target = 'duration_seconds'
X = df[features]
y = df[target]
# Handle categorical features (Day of Week) - One-Hot Encoding
X = pd.get_dummies(X, columns=['start_day_of_week'], drop_first=True)
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"Training data shape: {X_train.shape}, Target shape: {y_train.shape}")
print(f"Testing data shape: {X_test.shape}, Target shape: {y_test.shape}")
# Model Training (Using RandomForestRegressor as it often performs well and captures non-linearities)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1) # n_jobs=-1 uses all available cores
print("\nTraining RandomForestRegressor model...")
model.fit(X_train, y_train)
print("Model training complete.")
# Model Evaluation
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
rmse = mean_squared_error(y_test, y_pred, squared=False) # RMSE
r2 = r2_score(y_test, y_pred)
print(f"\nModel Evaluation (RandomForestRegressor):")
print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"Root Mean Squared Error (RMSE): {rmse:.2f}")
print(f"R-squared (R2): {r2:.2f}")
# Feature Importance (for Random Forest)
if hasattr(model, 'feature_importances_'):
feature_importances = pd.Series(model.feature_importances_, index=X_train.columns)
sorted_importances = feature_importances.sort_values(ascending=False)
print("\nFeature Importances:")
print(sorted_importances.to_markdown())
# Plot feature importances
plt.figure(figsize=(10, 6))
sns.barplot(x=sorted_importances, y=sorted_importances.index)
plt.title('Feature Importances')
plt.xlabel('Importance')
plt.ylabel('Feature')
plt.tight_layout()
plt.show()
# Example Prediction
# Create a sample data point for prediction
# Example: A parcel arriving on a Monday (day 1), in a lot of size 50,
# with 0 holidays in the next 7 days, and we want to predict its duration assuming it's *not* batched yet
# Need to match the columns after one-hot encoding
sample_data = pd.DataFrame([{
'actual_parcel_count': 50,
'holidays_in_next_7_days': 0,
'cleared_in_batch': 0, # Assume we are predicting *before* it's batched
'start_day_of_week_1': 1, # Monday (assuming Monday is day 1 after dropping day 0)
'start_day_of_week_2': 0,
'start_day_of_week_3': 0,
'start_day_of_week_4': 0,
'start_day_of_week_5': 0,
'start_day_of_week_6': 0,
}])
# Ensure all columns from training data are present, fill missing with 0 (standard for one-hot)
sample_data = sample_data.reindex(columns=X_train.columns, fill_value=0)
predicted_duration = model.predict(sample_data)
print(f"\nExample Prediction:")
print(f"Features: Lot Size=50, Holidays_in_next_7_days=0, Monday start, Not yet batched")
print(f"Predicted Clearance Duration: {predicted_duration[0]:.2f} seconds")
print(f"Predicted Clearance Duration: {predicted_duration[0]/3600:.2f} hours")
# --- Further Analysis Ideas ---
# - Plot average clearance duration by day of week.
# - Plot batch size distribution.
# - Plot average batch processing speed over time.
# - Analyze queue_status table snapshots to understand queue build-up/clearing.
# - Calculate and visualize 220->370 duration distribution using a histogram.
# - Incorporate queue status snapshots into ML features (e.g., queue size at 220 timestamp).
# - Consider external factors not in DB (weather, strikes - would need external data).