2 Dashboard - VforVitorio/F1_Strat_Manager GitHub Wiki

📊 Streamlit Dashboard

Interactive web interface for F1 strategy analysis and visualization

# Strategy Recommendations View

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Strategy Recommendations View

Relevant source files

Purpose and Scope

The Strategy Recommendations View is the primary interface component within the Streamlit Dashboard for displaying and analyzing AI-generated F1 strategic recommendations. This component transforms raw recommendation data from the Expert System into an interactive visualization and analysis environment that enables race strategists to evaluate, compare, and understand optimal race strategies.

This document covers the visual interface and recommendation processing capabilities. For information about the underlying recommendation generation logic, see Expert System. For details about the broader dashboard architecture, see Streamlit Dashboard.

System Overview

The Strategy Recommendations View operates as a multi-layered system that processes recommendation data through filtering, visualization, and comparative analysis stages. The component integrates several specialized modules to provide comprehensive strategy analysis capabilities.

Component Architecture

Strategy Comparison

Strategy Generation

Core Functions

Helper Modules

Main Entry Point

render_recommendations_view()

recommendations_helpers.py

optimal_strategy_generator.py

strategy_comparator.py

render_stat_card()

filter_and_sort_recommendations()

plot_recommendation_timeline()

plot_priority_distribution()

plot_confidence_distribution()

render_recommendation_card()

generate_optimal_strategy()

plot_optimal_strategy_step_chart()

plot_optimal_strategy_swimlane()

render_optimal_strategy_summary_table()

render_strategy_comparison()

generate_aggressive_strategy()

generate_conservative_strategy()

extract_strategy_features()

render_comparison_table()

Sources: scripts/app/components/recommendations_view.py 1-190

scripts/app/components/recommendations_module/recommendations_helpers.py 1-184

scripts/app/components/recommendations_module/optimal_strategy_generator.py 1-198

scripts/app/components/recommendations_module/strategy_comparator.py 1-347

Data Processing Pipeline

Output Interface

Visualization Layer

Processing Layer

Input Data

recommendations DataFrame

selected_driver

get_processed_race_data()

filter_and_sort_recommendations()

generate_optimal_strategy()

generate_aggressive_strategy()

generate_conservative_strategy()

Stat Cards

Timeline Plots

Distribution Charts

Recommendation Cards

Strategy Charts

Comparison Tables

Streamlit UI Components

Sources: scripts/app/components/recommendations_view.py 27-41

scripts/app/components/recommendations_view.py 104-111

scripts/app/components/recommendations_view.py 157-169

Core Interface Components

Statistical Overview Cards

The interface begins with four statistical overview cards that provide immediate insight into the recommendation dataset. These cards are rendered using the render_stat_card() function and display:

Metric Description Source Column

Total Recommendations Count of all recommendations len(recommendations) Types of Actions Unique action types recommendations['action'].nunique() Average Confidence Mean confidence score recommendations['confidence'].mean() Maximum Priority Highest priority value recommendations['priority'].max()

Sources: scripts/app/components/recommendations_view.py 42-57

scripts/app/components/recommendations_module/recommendations_helpers.py 34-43

Interactive Filtering System

The filtering system provides granular control over recommendation display through multiple filter dimensions:

Confidence Threshold Filtering: Users can set a minimum confidence level using a slider that adapts to the data range scripts/app/components/recommendations_view.py 63-75

Priority Level Selection: Multi-select dropdown for filtering by priority levels, with dynamic population based on available data scripts/app/components/recommendations_view.py 77-86

Race Phase Filtering: Optional filtering by race phases when 'RacePhase' column is present in the data scripts/app/components/recommendations_view.py 93-101

Sorting Options: Four sorting modes implemented in filter_and_sort_recommendations():

Lap (Ascending/Descending)

Confidence (High to Low) Priority (High to Low)

Sources: scripts/app/components/recommendations_view.py 59-111

scripts/app/components/recommendations_module/recommendations_helpers.py 46-64

Visualization Capabilities

The component provides multiple visualization modes for analyzing recommendation patterns and distributions.

Timeline Visualization

The plot_recommendation_timeline() function creates an interactive scatter plot where:

X-axis represents lap numbers

Y-axis shows action types

Marker size corresponds to confidence levels

Color coding differentiates action types using ACTION_COLORS mapping

ACTION_COLORS Mapping

pit_stop → #FF5733

extend_stint → #33FF57

prepare_pit → #5733FF

perform_undercut → #33FFEC

defensive_pit → #FF33EB

prepare_rain_tires → #3385FF

perform_overcut → #BD33FF

consider_pit → #FF8833

Sources: scripts/app/components/recommendations_view.py 112-116

scripts/app/components/recommendations_module/recommendations_helpers.py 67-99

scripts/app/components/recommendations_module/recommendations_helpers.py 16-31

Distribution Analysis

Two complementary distribution charts provide statistical insights:

Priority Distribution: Pie chart showing recommendation count by priority level using plot_priority_distribution() scripts/app/components/recommendations_module/recommendations_helpers.py 102-119

Confidence Distribution: Histogram displaying confidence value distribution using plot_confidence_distribution() scripts/app/components/recommendations_module/recommendations_helpers.py 122-132

Sources: scripts/app/components/recommendations_view.py 120-126

Detailed Recommendation Cards

Individual recommendations are displayed using render_recommendation_card() which creates formatted cards containing:

Header: Lap number and action type with color-coded border

Content: Explanation text and key metrics (confidence, priority, rule fired)

Expandable Section: Additional information including tire compound and race phase

Simulation Feature: Mock what-if analysis showing potential time savings and position gains

The component supports two viewing modes:

Group by Action Type: Organizes cards in tabs by action type

Chronological View: Displays cards in lap number order

Sources: scripts/app/components/recommendations_view.py 128-152

scripts/app/components/recommendations_module/recommendations_helpers.py 135-183

Optimal Strategy Generation

The strategy generation system processes raw recommendations to create coherent, conflict-free strategy plans through the generate_optimal_strategy() function.

Conflict Resolution Algorithm

The algorithm implements a sophisticated conflict resolution system:

Selection Criteria

Conflict Detection

Incompatible Actions

pit_stop

extend_stint

perform_undercut

perform_overcut

defensive_pit

consider_pit

Check lap proximity (±2 laps)

Check incompatible_actions mapping

Reject conflicting recommendations

Sort by: LapNumber, priority, confidence

One action per lap maximum

Mandatory pit stop guarantee

Sources: scripts/app/components/recommendations_module/optimal_strategy_generator.py 7-59

scripts/app/components/recommendations_module/optimal_strategy_generator.py 24-31

Strategy Visualization Types

Step Chart: Line chart with horizontal-vertical steps showing action progression over laps using plot_optimal_strategy_step_chart() scripts/app/components/recommendations_module/optimal_strategy_generator.py 100-134

Swimlane Chart: Horizontal bar chart where each action type occupies a separate lane using plot_optimal_strategy_swimlane() scripts/app/components/recommendations_module/optimal_strategy_generator.py 137-171

Summary Table: Tabular display of strategy decisions with key metrics using render_optimal_strategy_summary_table() scripts/app/components/recommendations_module/optimal_strategy_generator.py 174-197

Sources: scripts/app/components/recommendations_view.py 172-184

Strategy Comparison System

The comparison system enables side-by-side analysis of different strategic approaches through the render_strategy_comparison() function.

Strategy Generation Variants

Three strategy variants are generated automatically:

Strategy Type Selection Logic Priority Sorting

Optimal Balanced priority and confidence ["LapNumber", "priority", "confidence"] desc

Aggressive Highest priority actions first ["priority", "LapNumber", "confidence"] desc

Conservative Lowest priority actions preferred ["priority", "LapNumber", "confidence"] asc

Sources: scripts/app/components/recommendations_module/strategy_comparator.py 185-264

scripts/app/components/recommendations_module/strategy_comparator.py 267-346

Feature Extraction and Comparison

The extract_strategy_features() function analyzes strategies across multiple dimensions:

Timing Metrics:

First pit stop lap

Number of pit stops Stint length analysis (shortest/longest)

Action Analysis:

Action type distribution

Chronological action sequence Total number of strategic actions

Comparison Visualization:

Action timeline overlay using plot_strategy_action_timeline()

Side-by-side metrics table using render_comparison_table()

Sources: scripts/app/components/recommendations_module/strategy_comparator.py 35-83

scripts/app/components/recommendations_module/strategy_comparator.py 128-157

scripts/app/components/recommendations_module/strategy_comparator.py 86-125

Integration Points

The Strategy Recommendations View integrates with several system components:

Data Source: Receives processed recommendation data from the Expert System via the main Streamlit application scripts/app/components/recommendations_view.py 33

Race Data Integration: Utilizes get_processed_race_data() from utils.processing for additional context scripts/app/components/recommendations_view.py 24

scripts/app/components/recommendations_view.py 189

UI Framework: Built entirely on Streamlit components with extensive use of columns, expanders, tabs, and interactive widgets for responsive user interface design.

Sources: scripts/app/components/recommendations_view.py 1-190


# Gap Analysis View

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Gap Analysis View

Relevant source files

Purpose and Scope

The Gap Analysis View is an interactive visualization component within the Streamlit Dashboard that displays time gaps between F1 cars and identifies strategic opportunities for undercuts and overcuts. This view processes real-time gap data to highlight tactical windows where pit stop timing can gain or defend track position.

For overall dashboard architecture, see Streamlit Dashboard. For lap time predictions and competitive analysis, see Time Predictions View. For AI-generated strategy recommendations, see Strategy Recommendations View.

System Integration

The Gap Analysis View integrates multiple system components to transform raw telemetry data into actionable strategic insights:

Strategic Rules

FastF1 API

calculate_all_gaps()

Gap DataFrame

calculate_gap_consistency()

GapFact Objects

F1GapRules Engine

Strategy Recommendations

Visualization Functions

render_gap_analysis()

undercut_opportunity()

defensive_pit_stop()

strategic_overcut()

traffic_management()

Sources: scripts/app/components/gap_analysis_view.py 1-140

scripts/IS_agent/utils/N05_gap_rules.py 47-191

scripts/IS_agent/N05_gap_rules.ipynb 323-471

Data Processing Pipeline

Gap Calculation Engine

The system calculates precise time gaps between cars at lap completion points using FastF1 telemetry data:

Strategic Flags

Gap Metrics

FastF1 Lap Data

For Each Driver

get_gap_at_lap_completion()

Calculate Gap to Leader

Calculate Relative Gaps

Gap to Car Ahead

Gap to Car Behind

Gap to Leader

Race Position

InUndercutWindow (<2.5s)

InDRSWindow (<1.0s)

The calculate_all_gaps() function processes lap data to generate comprehensive gap metrics. It handles both driver abbreviations and driver numbers, calculates gaps using completion times, and generates strategic flags for undercut and DRS windows.

Sources: scripts/IS_agent/utils/N05_gap_rules.py 47-191

scripts/IS_agent/N05_gap_rules.ipynb 264-297

Gap Consistency Analysis

Gap consistency metrics track how stable gaps remain over multiple consecutive laps, crucial for strategic decision-making:

Consistency Metrics

Gap DataFrame

calculate_gap_consistency()

Sliding Window Analysis

consistent_gap_ahead_laps

consistent_gap_behind_laps

±0.5s threshold

transform_gap_data_with_consistency()

GapFact Objects

Sources: scripts/IS_agent/utils/N01_agent_setup.py

scripts/IS_agent/N05_gap_rules.ipynb 139-149

Strategic Analysis Engine

Rule-Based Decision System

The F1GapRules class implements four core strategic rules using the Experta framework:

Strategic Windows

Strategic Actions

Rule Conditions

GapFact

Rule Evaluation

TelemetryFact

RaceStatusFact

gap_ahead < 2.0s AND consistent ≥ 3 laps

gap_behind < 2.0s AND consistent ≥ 3 laps

2.0s < gap_ahead < 3.5s AND consistent ≥ 4 laps

position > 10 AND gap_to_leader > 30.0s

perform_undercut (85% confidence)

defensive_pit (80% confidence)

perform_overcut (80% confidence)

adjust_pit_window (70% confidence)

Laps 6-26

Laps 27-48

Each rule includes specific conditions:

Undercut Opportunity: Triggers when consistently within 2.0s of car ahead for ≥3 laps during strategic windows Defensive Pit Stop: Activates when car behind maintains <2.0s gap for ≥3 consecutive laps Strategic Overcut: Recommends staying out when gap ahead remains 2.0-3.5s for ≥4 laps Traffic Management: Suggests pit window adjustment for cars >10th position with >30s gap to leader

Sources: scripts/IS_agent/utils/N05_gap_rules.py 193-301

scripts/IS_agent/N05_gap_rules.ipynb 806-880

Visualization Components

Interactive Chart Types

The Gap Analysis View provides four specialized visualizations through tabbed interface:

Tab Function Purpose

Gap Evolution st_plot_gap_evolution() Time series of gaps to cars ahead/behind

Undercut Opportunities st_plot_undercut_opportunities() Strategic zones with color-coded windows

Gap Consistency st_plot_gap_consistency() Bar chart of consistent lap counts Strategic Insights Metrics and tables Summary of opportunity statistics

Chart Features

Visualization Functions

Gap Data

render_gap_analysis()

Streamlit Tabs

st_plot_gap_evolution()

st_plot_undercut_opportunities()

st_plot_gap_consistency()

calculate_strategic_windows()

Line plots with markers

Fill areas for strategic zones

Reference lines (2.0s, 1.0s)

Grouped bars for consistency

Strategic Zone Visualization

The undercut opportunities chart uses color-coded zones:

Green zone (0-2.0s): Undercut window Orange zone (2.0-3.5s): Overcut window Red zone (>3.5s): No strategy zone

Reference lines mark DRS window (1.0s) and undercut threshold (2.0s) for tactical analysis.

Sources: scripts/app/utils/visualization.py 260-362

scripts/app/components/gap_analysis_view.py 15-140

User Interface Implementation

Component Structure

The render_gap_analysis() function orchestrates the complete gap analysis interface:

Error Handling

Tab Implementations

render_gap_analysis()

Data Validation

Filter to MAX_LAPS (66)

calculate_strategic_windows()

st.tabs() Creation

Gap Evolution Tab

Undercut Opportunities Tab

Gap Consistency Tab

Strategic Insights Tab

try/except blocks

st.error() messages

st.info() fallbacks

Strategic Insights Dashboard

The Strategic Insights tab provides quantitative analysis through metrics and data tables:

Opportunity counting from strategic_data

undercut_count = strategic_data['undercut_opportunity'].sum() overcut_count = strategic_data['overcut_opportunity'].sum() defensive_count = strategic_data['defensive_needed'].sum()

Column layout for metrics display

col1, col2, col3 = st.columns(3) with col1: st.metric("Undercut Windows", f"{int(undercut_count)} laps")

The interface includes expandable detailed tables showing lap-by-lap opportunity data with gap values, consistency metrics, and strategic flags.

Sources: scripts/app/components/gap_analysis_view.py 15-140

scripts/app/utils/processing.py

Integration with Expert System

The Gap Analysis View connects directly to the F1 Strategy Engine through fact transformation:

Fact Attributes

Gap DataFrame

transform_gap_data_with_consistency()

GapFact Instance

driver_number

gap_ahead

gap_behind

consistent_gap_ahead_laps

consistent_gap_behind_laps

in_undercut_window

F1CompleteStrategyEngine

StrategyRecommendation Objects

The transformation process converts tabular gap data into structured facts that the expert system rules can evaluate, enabling automated strategic decision-making based on gap analysis.

Sources: scripts/IS_agent/utils/N01_agent_setup.py

scripts/IS_agent/utils/N05_gap_rules.py 303-398


# Radio Analysis View

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Radio Analysis View Relevant source files

The Radio Analysis View provides an interface for uploading and analyzing F1 team radio communications using advanced Natural Language Processing models. This component processes audio files through a multi-stage pipeline that extracts sentiment, intent, and named entities from radio messages, converting unstructured communications into structured data for strategic decision-making.

For information about the underlying NLP pipeline components, see 4. For details about how the extracted radio data integrates with strategic recommendations, see 5.4.

System Architecture

The Radio Analysis View implements a complete audio-to-insights pipeline through four main processing stages:

Output Generation

NLP Analysis Pipeline

Audio Processing

User Interface Layer

file_uploader()

NamedTemporaryFile

st.audio()

transcribe_audio()

Transcribed Text

load_sentiment_model()

load_intent_model()

load_bert_ner_model()

predict_sentiment()

predict_intent()

analyze_f1_radio()

Structured JSON

radio_analysis_timestamp.json

Sources: scripts/app/components/radio_analysis_view.py 12-60

scripts/NLP_radio_processing/N06_model_merging.ipynb 604-669

Audio Transcription

The system uses OpenAI's Whisper model for audio-to-text conversion of team radio communications:

MP3 File Upload

outputs/temp/

whisper.load_model('turbo')

model.transcribe(audio_path)

result['text']

The transcribe_audio() function handles the complete transcription workflow, loading the Whisper turbo model and processing uploaded audio files. Temporary files are stored in outputs/temp/ directory and cleaned up after processing.

Sources: scripts/NLP_radio_processing/N06_model_merging.ipynb 678-700

scripts/app/components/radio_analysis_view.py 24-39

Multi-Model NLP Analysis

Model Loading Architecture

The system loads three specialized transformer models for comprehensive text analysis:

Model Component Base Architecture Purpose Output Classes load_sentiment_model() RoBERTa-base Emotional tone analysis positive, negative, neutral load_intent_model() RoBERTa-large Communication purpose INFORMATION, PROBLEM, ORDER, WARNING, QUESTION load_bert_ner_model() BERT-large-cased Entity extraction ACTION, SITUATION, INCIDENT, etc.

Model Loading

Model Initialization

Tokenizers

AutoTokenizer.from_pretrained('roberta-base')

AutoTokenizer.from_pretrained('roberta-large')

BertTokenizer.from_pretrained('dbmdz/bert-large-cased-finetuned-conll03-english')

../../outputs/week4/models/best_roberta_sentiment_model.pt

../../outputs/week4/models/best_roberta_large_intent_model.pt

../../outputs/week4/models/best_focused_bert_model.pt

RobertaForSequenceClassification(num_labels=3)

RobertaForSequenceClassification(num_labels=5)

BertForTokenClassification(num_labels=19)

Sources: scripts/NLP_radio_processing/N06_model_merging.ipynb 161-304

scripts/app/app_modules/nlp_radio_processing/N04_radio_info.py 100-415

Intent Classification System

The intent classification model categorizes radio messages into strategic communication types:

Intent Categories

INFORMATION: Factual updates

PROBLEM: Driver-reported issues

ORDER: Direct instructions

WARNING: Alerts about issues

QUESTION: Queries requiring input

Radio Message Text

tokenizer(text, max_length=128)

model(input_ids, attention_mask)

torch.nn.functional.softmax(logits)

intent_labels[pred_class]

The intent model achieved 76% accuracy with strong performance across all categories, particularly excelling in QUESTION (F1=0.94) and PROBLEM (F1=0.82) classification.

Sources: scripts/NLP_radio_processing/N04_radio_info.ipynb 463-510

scripts/NLP_radio_processing/N06_model_merging.ipynb 463-510

Named Entity Recognition

The NER system extracts F1-specific entities using BIO (Beginning-Inside-Outside) tagging:

Processing Pipeline

Tokenized Text

BertForTokenClassification

19-class predictions

entity_mapping dict

BIO Tagging

B-ENTITY: Beginning token

I-ENTITY: Inside token

O: Outside entity

Entity Categories

ACTION: Direct commands

SITUATION: Racing context

INCIDENT: On-track events

STRATEGY_INSTRUCTION: Strategic directives

POSITION_CHANGE: Overtakes/positions

PIT_CALL: Pit stop calls

TRACK_CONDITION: Track state

TECHNICAL_ISSUE: Car problems

WEATHER: Weather conditions

The NER model processes tokenized text through BERT and maps predictions to structured entity categories using a 19-class BIO tagging scheme.

Sources: scripts/NLP_radio_processing/N05_ner_models.ipynb 418-460

scripts/NLP_radio_processing/N06_model_merging.ipynb 281-304

Integrated Analysis Pipeline

The analyze_radio_message() function orchestrates the complete NLP pipeline:

JSON Structure Generation

Pipeline Orchestration

Response Format

message: original text

analysis.sentiment

analysis.intent

analysis.entities

Radio Message Input

Load All Three Models

Parallel Model Inference

sentiment_prediction

intent_prediction

ner_entities

Structured Response

radio_analysis_YYYYMMDD_HHMMSS.json

The pipeline generates structured JSON output with timestamp-based filenames for integration with the expert system.

Sources: scripts/NLP_radio_processing/N06_model_merging.ipynb 604-669

scripts/app/components/radio_analysis_view.py 41-53

Streamlit Interface Implementation

User Interface Components

The render_radio_analysis_view() function provides the complete user interface:

Error Handling

st.error('Transcription failed')

st.error('Analysis failed')

File Management

os.makedirs('outputs/temp')

tempfile.NamedTemporaryFile(suffix='.mp3')

os.remove(temp_audio_path)

Streamlit Components

st.header('Analyze a Team Radio Audio File')

st.file_uploader('Upload MP3 file', type=['mp3'])

st.audio(temp_audio_path)

st.spinner('Transcribing audio...')

st.spinner('Analyzing radio message...')

st.code(transcribed_text)

st.json(analysis)

The interface handles file uploads, displays progress indicators during processing, and presents results in both code and JSON formats with comprehensive error handling.

Sources: scripts/app/components/radio_analysis_view.py 12-60

Processing Workflow "JSON File Output" "analyze_radio_message()" "transcribe_audio()" "Temporary Storage" "render_radio_analysis_view()" User "JSON File Output" "analyze_radio_message()" "transcribe_audio()" "Temporary Storage" "render_radio_analysis_view()"

User

Upload MP3 file

Save to outputs/temp/

Display audio player

Process audio file

Return transcribed text

Display transcription

Analyze transcribed text

Generate timestamped JSON

Return file path

Display analysis results

Clean up temporary files

The processing workflow ensures proper resource management and provides user feedback at each stage of the analysis pipeline.

Sources: scripts/app/components/radio_analysis_view.py 23-59

Configuration and Model Artifacts

Model Configuration

The system uses a centralized configuration approach for model paths and label mappings:

Configuration Key Value Purpose sentiment_model_path best_roberta_sentiment_model.pt Sentiment analysis weights intent_model_path best_roberta_large_intent_model.pt Intent classification weights ner_model_path best_focused_bert_model.pt NER model weights whisper_model_size turbo Audio transcription model

Output Structure

Standardized JSON format for expert system integration

Label Mappings

['positive', 'negative', 'neutral']

['INFORMATION', 'PROBLEM', 'ORDER', 'WARNING', 'QUESTION']

19 BIO-tagged entity classes

Model Artifacts

best_roberta_sentiment_model.pt

best_roberta_large_intent_model.pt

best_focused_bert_model.pt

Sources: scripts/NLP_radio_processing/N06_model_merging.ipynb 99-138

Integration with Expert System

The Radio Analysis View generates structured output that integrates with the F1 strategy expert system:

Expert System Integration

Radio Analysis Output

radio_analysis_timestamp.json

message: original text

analysis.sentiment

analysis.intent

analysis.entities

RadioFact(sentiment, intent, entities)

F1RadioRules engine

Strategic recommendations

The structured JSON format enables the expert system to process radio communications as facts for rule-based strategic decision making.

Sources: scripts/NLP_radio_processing/N06_model_merging.ipynb 647-668

scripts/app/utils/processing.py 1-475


# Time Predictions View

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Time Predictions View Relevant source files

The Time Predictions View is a component of the F1 Strategy Manager that visualizes the comparison between predicted and actual lap times for selected drivers. This documentation explains how the view is implemented, its visual components, and its integration with the underlying prediction models.

For information about the lap time prediction model implementation, see Lap Time Prediction.

Purpose

This component allows race strategists to:

Visualize predicted vs. actual lap times for any driver

Evaluate prediction accuracy through error metrics

Identify laps with significant prediction errors

Understand performance trends to inform strategy decisions

Component Architecture

The Time Predictions View processes prediction data through a single main rendering function that produces multiple visualization components for the Streamlit dashboard.

Output Components

render_time_predictions_view Function Flow

predictions_df + selected_driver

Filter data for selected driver lines 17-18

Check for empty data lines 20-22

Calculate MAE lines 25-29

Generate top 5 error table lines 34-41

Create Plotly figure lines 44-77

Return fig object line 80

st.metric MAE display

st.table top errors

st.plotly_chart comparison

Sources: scripts/app/components/time_predictions_view.py 6-80

Core Implementation

The component is implemented through the render_time_predictions_view function, which processes predictions data and generates three main visualization elements:

Streamlit Components

render_time_predictions_view

df = predictions_df[predictions_df['DriverNumber'].astype(int) == int(selected_driver)]

valid['AbsError'] = (valid['LapTime'] - valid['PredictedLapTime']).abs()

top_errors = valid.sort_values('AbsError', ascending=False).head(5)

go.Figure() with two traces

st.metric MAE display

st.table error breakdown

st.plotly_chart comparison

Sources: scripts/app/components/time_predictions_view.py 6-80

Visualization Components

The Time Predictions View generates three main visual elements:

  1. Mean Absolute Error (MAE) Metric

A single numeric value that quantifies the overall prediction accuracy. Lower values indicate better prediction performance.

valid['AbsError'] = (valid['LapTime'] - valid['PredictedLapTime']).abs() mae = valid['AbsError'].mean() st.metric("Mean Absolute Error (MAE)", f"{mae:.3f} s")

Sources: scripts/app/components/time_predictions_view.py 25-31

  1. Top Errors Table

A tabular display showing the 5 laps with the largest prediction errors, generated by sorting the AbsError column in descending order and taking the first 5 rows.

The table displays renamed columns for clarity:

LapNumber → Lap

LapTime → Real Lap Time

PredictedLapTime → Predicted Lap Time

AbsError → Absolute Error

Code implementation

top_errors = valid.sort_values('AbsError', ascending=False).head(5) st.table(top_errors'LapNumber', 'LapTime', 'PredictedLapTime', 'AbsError'.rename( columns={'LapNumber': 'Lap', 'LapTime': 'Real Lap Time', 'PredictedLapTime': 'Predicted Lap Time', 'AbsError': 'Absolute Error'}))

Sources: scripts/app/components/time_predictions_view.py 39-41

  1. Comparison Chart

An interactive Plotly line chart created with go.Figure() that displays two traces for visual comparison of real versus predicted lap times.

go.Figure Construction

fig = go.Figure()

fig.add_trace for LapTime color='deepskyblue', solid line

fig.add_trace for PredictedLapTime color='orange', dashed line

fig.update_layout with plotly_dark theme

st.plotly_chart with use_container_width=True

Chart specifications:

Real Lap Time trace: color='deepskyblue', width=2, solid line, 4px markers

Predicted Lap Time trace: color='orange', width=2, dashed line, 4px markers

Layout: plotly_dark template, 400px height, horizontal legend positioned above chart

Axes: X-axis shows Lap Number, Y-axis shows Lap Time (s)

Sources: scripts/app/components/time_predictions_view.py 44-78

Data Requirements

For proper functioning, the Time Predictions View requires a DataFrame with the following columns:

Column Description Type

DriverNumber Car number of the driver integer

LapNumber Sequential lap number integer

LapTime Actual recorded lap time float (seconds) PredictedLapTime Model-predicted lap time float (seconds)

The view automatically calculates the AbsError column as the absolute difference between actual and predicted lap times.

Sources: scripts/app/components/time_predictions_view.py 8-9

scripts/app/components/time_predictions_view.py 25-28

Data Input Requirements

The Time Predictions View expects a pre-processed DataFrame containing prediction results. The view operates as a pure visualization component that does not perform predictions itself.

Required DataFrame Columns

Input Data Flow

External ML Pipeline

predictions_df DataFrame

render_time_predictions_view

DriverNumber: int

LapNumber: int

LapTime: float

PredictedLapTime: float

The function performs data validation by filtering for the selected driver and dropping rows with missing values in the required columns before processing.

Sources: scripts/app/components/time_predictions_view.py 8-9

scripts/app/components/time_predictions_view.py 17-19

scripts/app/components/time_predictions_view.py 25-26

Integration with Report Export

The Time Predictions View integrates with the report generation system through the render_report_export_ui function, which can include prediction charts in exported HTML reports.

Report Sections

Report Export Integration

render_time_predictions_view

Returned fig object

collect_report_data

prediction_charts parameter

build_html_report

predictions section

lap_time_charts

degradation_charts

The report export system includes prediction visualizations in multiple sections:

Predictions section: Main lap time prediction charts via prediction_charts parameter

Lap time charts: Additional lap time analysis via lap_time_charts parameter Export logic: Charts converted to base64 images for HTML embedding

Sources: scripts/app/components/report_export.py 222-223

scripts/app/components/report_export.py 317-322

scripts/app/components/report_export.py 508-516

Practical Usage

When using the Time Predictions View:

Select a driver from the dashboard

The view automatically filters prediction data for that driver

Review the MAE to assess overall prediction quality

Examine the top errors table to identify specific problematic laps

Analyze the comparison chart to detect patterns or trends in performance

Use these insights to inform race strategy decisions

The view is particularly valuable for:

Validating the prediction model's reliability

Understanding how different race conditions affect performance

Identifying unexpected performance changes that may require strategy adjustments

Providing data-driven support for strategic decisions

Sources: scripts/app/components/time_predictions_view.py 6-80


# Strategy Chat Interface

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Strategy Chat Interface Relevant source files

The Strategy Chat Interface is an LLM-powered conversational component of the F1 Strategy Manager that enables users to interact with the system through natural language. It provides a ChatGPT-style interface where users can ask questions, seek explanations about race strategy, and analyze F1-related data including uploaded images such as charts and graphs.

This interface serves as a complementary tool to the other specialized data visualization views in the system (see Strategy Recommendations View, Gap Analysis View, Radio Analysis View, and Time Predictions View). While those components provide structured visualizations of specific data types, the Strategy Chat Interface offers a more flexible, conversational way to explore F1 strategy concepts.

  1. Architecture Overview

The Strategy Chat Interface is built as a Streamlit component that integrates with a locally-hosted LLM service (Ollama) to provide F1-specific strategic insights and explanations.

Component Architecture

Session State

LLM Service

Strategy Chat Interface

handle_user_input_streaming()

stream_llm_response()

User

render_strategy_chat()

Chat History Display

Message Input Area

Chat Management Sidebar

Model Parameters

Ollama API (localhost:11434)

F1 Strategy Models (llama3.2-vision, etc.)

strategy_chat_history

strategy_saved_chats

current_chat_name

Sources: scripts/app/components/strategy_chat.py 8-81

scripts/app/components/strategy_chat.py 310-348

Data Flow "Ollama LLM Service" "Input Handler" "Session State" "Streamlit UI" User "Ollama LLM Service" "Input Handler" "Session State" "Streamlit UI"

User

Enter message or upload image

Click "Send" button

Call handle_user_input_streaming()

Add user message to chat history

Stream request with messages and system prompt

Stream response chunks

Update display with each chunk

Add complete assistant response to history

Update saved chats if necessary Display complete conversation

Sources: scripts/app/components/strategy_chat.py 248-308

scripts/app/components/strategy_chat.py 226-246

  1. Key Components 2.1 Chat Interface Components

The Streamlit-based interface is divided into three main areas:

Chat History Display: Shows the conversation history with user and assistant messages

Message Input Area: Allows users to enter text messages and upload images Sidebar Management Panel: Provides chat session management and model configuration options

StrategyChat

+render_strategy_chat(section_title, context)

+initialize_chat_state()

+get_chat_history()

ChatManagement

+create_new_chat(context)

+load_chat(chat_name)

+delete_current_chat()

+generate_chat_name(context, user_message)

MessageHandling

+add_message(role, msg_type, content)

+handle_user_input_streaming(text, image, model, temperature)

+stream_llm_response(messages, model, temperature)

+send_message_to_llm(messages, model, temperature)

ImageSupport

+open_chat_with_image(image, description, new_chat, context)

ModelManagement

+get_available_models()

Sources: scripts/app/components/strategy_chat.py 8-130

scripts/app/components/strategy_chat.py 146-186

scripts/app/components/strategy_chat.py 188-224

2.2 Message Structure

The system handles multiple message types (text and images) and maintains them in a standardized format within the session state.

Field Description Example role Message author "user" or "assistant" type Content type "text" or "image" content Message content Text string or image data

Sources: scripts/app/components/strategy_chat.py 226-246

  1. Functionality 3.1 Formula 1 Strategic Assistant

The chat interface is specialized for Formula 1 strategy assistance through a carefully crafted system prompt that defines its scope and capabilities:

Race strategy analysis and recommendations

Interpretation of F1 data visualizations (charts, tables, etc.)

Historical race data, driver information, and technical context

Analysis of uploaded images including lap time charts, tire degradation graphs, and race statistics

The system prompt directs the model to focus exclusively on F1-related topics and to use appropriate F1 terminology.

Sources: scripts/app/components/strategy_chat.py 260-273

3.2 Image Analysis Capabilities

The interface supports multimodal interaction through image uploads, allowing users to:

Upload charts, graphs, or other F1-related images

Ask specific questions about the visuals Receive detailed analysis from the F1 strategy assistant

This feature is particularly useful for analyzing complex race data visualizations and getting expert interpretations.

Sources: scripts/app/components/strategy_chat.py 68-72

scripts/app/components/strategy_chat.py 276-292

3.3 Chat Session Management

Users can manage multiple chat sessions through the sidebar interface:

Create new chats with the "New chat" button

Browse and load saved chat sessions

Delete the current chat session

Automatically name chat sessions based on context or initial message

This allows users to maintain separate conversations about different aspects of F1 strategy or different races.

Sources: scripts/app/components/strategy_chat.py 16-40

scripts/app/components/strategy_chat.py 146-224

  1. Implementation Details 4.1 Streaming Responses

Rather than waiting for the complete LLM response, the interface streams the response in chunks, providing a more interactive experience:

User input is sent to the LLM via handle_user_input_streaming()

Response chunks are streamed back through stream_llm_response()

The UI is updated in real-time as new chunks arrive

The complete response is added to chat history when streaming completes

Sources: scripts/app/components/strategy_chat.py 248-308

scripts/app/components/strategy_chat.py 310-348

4.2 Model Configuration

Users can customize their interaction through model parameters:

Select from available Ollama models (with llama3.2-vision as default) Adjust temperature (creativity) from 0.0 to 1.0 (default 0.2)

The system retrieves available models dynamically from the Ollama service.

Sources: scripts/app/components/strategy_chat.py 42-48

scripts/app/components/strategy_chat.py 488-503

4.3 External Integration

The open_chat_with_image() function allows other components of the F1 Strategy Manager to programmatically open the chat interface with a specific image (such as a chart) for analysis:

open_chat_with_image(image, description="Please analyze this tire degradation chart", new_chat=True, context="TireDeg")

This enables seamless integration between the data visualization components and the conversational interface.

Sources: scripts/app/components/strategy_chat.py 472-485

  1. UI Design

The chat interface follows a modern chat application design with:

Right-aligned user messages with navy blue background

Left-aligned assistant messages with gray background

Support for both text and image content

Custom CSS styling for readability Racing-themed icons (🏎️ for user, 🏁 for assistant)

Sources: scripts/app/components/strategy_chat.py 84-129

  1. Technical Requirements

The Strategy Chat Interface requires:

A locally running Ollama service on port 11434

Compatible LLM models with multimodal support (for image analysis) Streamlit for the web interface components

If the Ollama service is unavailable, the interface will display appropriate error messages and fallback gracefully.

Sources: scripts/app/components/strategy_chat.py 323-347

scripts/app/components/strategy_chat.py 488-503


# Streamlit Dashboard

DeepWiki

VforVitorio/F1_Strat_Manager

Get free private DeepWikis with

Devin

Share

Last indexed: 13 June 2025 (0638ba)

Overview

System Architecture

Installation and Setup

Documentation Workflow

Streamlit Dashboard

Strategy Recommendations View

Gap Analysis View

Radio Analysis View

Time Predictions View

Strategy Chat Interface

Machine Learning Models

Lap Time Prediction

Tire Degradation Modeling

Vision-based Gap Calculation

NLP Pipeline

Radio Transcription

Sentiment and Intent Analysis

Named Entity Recognition

Integrated NLP Pipeline

Expert System

Facts and Data Transformation

Degradation Rules

Gap Analysis Rules

Radio Message Rules

Integrated Rule Engine

Developer Guide

Data Processing Utilities

Model Artifacts and Deployment

Development Environment

Streamlit Dashboard Relevant source files

The Streamlit Dashboard serves as the primary user interface for the F1 Strategy Manager system. It provides an interactive environment where race engineers can analyze data, visualize insights, and receive strategic recommendations. This central hub integrates output from various subsystems including tire degradation models, gap analysis, lap time predictions, and team radio analysis.

For information about the expert system generating recommendations, see Expert System, and for details on the machine learning models powering the predictions, see Machine Learning Models.

Dashboard Architecture

The dashboard is built with Streamlit, a Python framework for creating data applications. It follows a modular design with separate components for each analysis view, connected through a central navigation system.

Data Processing Layer

Core Views

Main Application

app.py Main Dashboard Entry Point

Session State

Data Caching

Navigation Sidebar

Data Selection

  • Driver
  • Race

render_overview() Race Performance Summary

render_degradation_view() Tire Performance Analysis

render_gap_analysis() Position Gap Tracking

render_time_predictions_view() Lap Time Forecast

render_radio_analysis() Team Communication Analysis

render_recommendations_view() AI Strategy Suggestions

render_strategy_chat() LLM-based Interactive Chat

Data Loading Functions load_race_data() load_recommendation_data()

Data Processing Functions get_processed_race_data() get_processed_gap_data()

Visualization Functions st_plot_degradation_rate() st_plot_gap_evolution()

Sources: scripts/app/app.py 46-92

scripts/app/app.py 126-156

Navigation and User Interface

The dashboard provides a consistent navigation structure through a sidebar that allows users to switch between different analysis views. The main application file handles the routing logic and maintains the application state.

Main Navigation Structure

The navigation is implemented as a sidebar with radio buttons for different views:

  • Overview
  • Tire Analysis
  • Gap Analysis
  • Lap Time Predictions
  • Team Radio Analysis
  • Strategy Recommendations
  • Competitive Analysis
  • Vision Gap Extraction
  • Strategy Chat
  • Export Strategy Report

Sources: scripts/app/app.py 67-87

Data Selection

The sidebar also contains controls for data selection, allowing users to:

View race information (currently fixed to "Spain 2023")

Select a driver to analyze (from available drivers in the dataset)

When a new driver is selected, the relevant data is reloaded and processed for the selected driver.

Sources: scripts/app/app.py 94-124

Data Flow

The dashboard implements a data flow pattern that loads, processes, and visualizes race data and strategic recommendations. Data is cached in the Streamlit session state to improve performance when navigating between views.

Visualization Layer

View Controllers

Processing Pipeline

Data Sources

Race Telemetry Data (CSV Files)

Strategy Recommendations (Generated by Expert System)

Gap Analysis Data (Generated by Vision System)

data_loader.py Data Loading Functions

processing.py Data Processing Functions

Session State

Data Caching

degradation_view.py Tire Analysis

gap_analysis_view.py Gap Analysis

time_predictions_view.py Lap Predictions

radio_analysis_view.py Team Radio

recommendations_view.py Strategy Recommendations

st_plot_degradation_rate() st_plot_regular_vs_adjusted_degradation()

st_plot_gap_evolution() st_plot_undercut_opportunities()

st_plot_fuel_adjusted_degradation()

Sources: scripts/app/app.py 126-156

scripts/app/utils/processing.py 114-156

Main View Components

The dashboard consists of several key view components, each focusing on a specific aspect of race strategy analysis.

Overview View

The Overview view provides a high-level summary of the race performance for the selected driver. It includes:

Key metrics (average degradation, pit stops, final position)

Lap time evolution chart with tire compound visualization Multi-driver lap time comparison

Sources: scripts/app/components/overview_view.py 9-253

Tire Analysis View

The Tire Analysis view focuses on tire performance and degradation throughout the race. It uses a tabbed interface to organize different analyses:

Degradation Rate Analysis: Shows how quickly tire performance degrades over time

Fuel-Adjusted Analysis: Compares raw vs. fuel-adjusted tire degradation Speed Comparison: Analyzes how sector speeds evolve as tires age

The view uses specialized visualization functions such as st_plot_degradation_rate(), st_plot_regular_vs_adjusted_degradation(), and st_plot_speed_vs_tire_age().

Sources: scripts/app/components/degradation_view.py 12-87

scripts/app/utils/visualization.py 31-158

Gap Analysis View

The Gap Analysis view examines the gaps between cars throughout the race. It includes:

Gap Evolution: Shows how gaps to cars ahead and behind evolved during the race

Undercut Opportunities: Visualizes windows where undercut or overcut strategies were possible

Gap Consistency: Displays how consistently gaps were maintained over multiple laps

Strategic Insights: Summarizes strategic opportunities identified from gap analysis

This view helps race engineers identify strategic opportunities based on car position.

Sources: scripts/app/components/gap_analysis_view.py 15-139

scripts/app/utils/visualization.py 260-399

Lap Time Predictions View

This view displays predictions for future lap times based on machine learning models, helping teams anticipate performance changes. It provides:

Visualization of predicted lap times

Comparison between actual and predicted performance Fuel-adjusted lap time analysis

The predictions are generated using XGBoost models trained on historical race data.

Sources: scripts/app/app.py 192-201

scripts/app/utils/processing.py 152-159

Team Radio Analysis View

This view analyzes team radio communications for strategic insights, including:

Radio-based strategic recommendations

Radio message sentiment analysis Key communications that might impact race strategy

The system identifies radio messages that could indicate important events (weather changes, strategic decisions by competitors, etc.).

Sources: scripts/app/components/team_radio_view.py 7-42

Strategy Recommendations View

This central view displays AI-generated strategy recommendations from the expert system. Engineers can review and filter recommendations based on:

Confidence levels

Action types Strategic urgency

Sources: scripts/app/app.py 211-216

Strategy Chat Interface

A unique feature allowing engineers to ask natural language questions about race strategy. This LLM-powered interface:

Provides conversational access to strategy insights

Explains reasoning behind recommendations Allows exploration of alternative strategies

Sources: scripts/app/app.py 228-229

Data Visualization

The dashboard heavily uses interactive visualizations to present complex race data in an intuitive format. These visualizations are implemented using Plotly and are rendered through specialized functions in the visualization.py file.

Key Visualization Functions

Function Purpose Source st_plot_degradation_rate() Visualizes tire degradation rates visualization.py 227-257

st_plot_regular_vs_adjusted_degradation() Compares raw vs. fuel-adjusted degradation visualization.py 76-158

st_plot_gap_evolution() Shows gap evolution over time visualization.py 260-310

st_plot_undercut_opportunities() Highlights strategic windows visualization.py 313-362

st_plot_gap_consistency() Visualizes gap consistency metrics visualization.py 365-399

st_plot_fuel_adjusted_degradation() Shows fuel-adjusted degradation data visualization.py 161-191

Each visualization function takes processed data and creates interactive Plotly charts that engineers can explore within the dashboard.

Integration with Other Subsystems

The dashboard integrates with multiple subsystems to provide a comprehensive strategy management platform:

Expert System

Prediction Systems

Data Processing Layer

User Interface Layer

Streamlit Dashboard app.py

Processing Utilities processing.py

Visualization Functions visualization.py

Data Loading Functions data_loader.py

XGBoost Lap Time Prediction get_lap_time_predictions()

TCN Tire Degradation Model predict_tire_degradation()

YOLOv8 Gap Calculation

Vision-based Gap Detection

F1StrategyEngine

Rule-based Expert System

Strategy Recommendations recommendations.csv

Sources: scripts/app/utils/processing.py 30-64

scripts/app/app.py 8-21

Performance Considerations

The dashboard implements several performance optimizations:

Session State Caching: Data is loaded once and cached in session state to avoid redundant processing

Selective Data Loading: Only data for the selected driver is processed when possible Error Handling: Robust error handling prevents dashboard crashes when data is missing or models fail

Sources: scripts/app/app.py 34-46

scripts/app/app.py 126-156

Key Files and Functions

The dashboard is implemented across several key files:

File Purpose app.py Main application entry point and routing logic utils/processing.py Data processing functions utils/visualization.py Visualization functions utils/data_loader.py Data loading functions components/*.py Individual view components

The modular structure allows for easy maintenance and extension of dashboard functionality.

Conclusion

The Streamlit Dashboard provides a comprehensive interface for the F1 Strategy Manager system, integrating data from various sources and presenting it through intuitive visualizations. The dashboard connects ML models, the expert system, and raw data to deliver actionable insights for race engineers.

Future enhancements may include additional views, more advanced visualizations, and deeper integration with live data sources during races.


📝 This documentation is automatically generated using browser automation.
🕒 Last updated: $(date '+%Y-%m-%d %H:%M:%S UTC') 📊 Auto-organized from 6 content files