-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_wizard.py
More file actions
589 lines (474 loc) · 18.5 KB
/
setup_wizard.py
File metadata and controls
589 lines (474 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
#!/usr/bin/env python3
"""
Setup wizard for configuring club mappings and column mappings.
This creates a user-specific configuration file by parsing Garmin data.
"""
import json
from pathlib import Path
import pandas as pd
from InquirerPy import inquirer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from ui_helpers import TABLE_HEADER_STYLE, create_item_table, print_app_header
console = Console()
def load_existing_config() -> dict | None:
"""
Load existing configuration if it exists.
Returns:
Optional[Dict]: Configuration dictionary if found, None otherwise
"""
config_file = Path("config.json")
if config_file.exists():
try:
with open(config_file) as f:
config = json.load(f)
console.print("[green]✓[/green] Found existing configuration")
return config
except Exception as e:
console.print(f"[yellow]Warning: Could not load existing config: {e}[/yellow]")
return None
def configure_units(existing_config: dict | None = None) -> dict[str, str]:
"""
Configure distance and deviation units.
Args:
existing_config: Optional existing configuration to use as defaults
Returns:
Dict[str, str]: Dictionary with 'distance' and 'deviation' unit settings
"""
console.print()
console.print(Panel.fit(
"[bold cyan]Garmin2ShotPattern - Setup Wizard[/bold cyan]\n"
"Configure club mappings and column settings",
border_style="cyan"
))
console.print()
console.print("[bold]Step 1: Configure Units[/bold]")
console.print("Select the units for distances and deviations (for display purposes).")
# Get defaults from existing config
default_distance = "meters"
default_deviation = "meters"
if existing_config and "units" in existing_config:
default_distance = existing_config["units"].get("distance", "meters")
default_deviation = existing_config["units"].get("deviation", "meters")
console.print(f"[dim]Current: {default_distance} (distance), {default_deviation} (deviation)[/dim]")
console.print()
# Distance unit
distance_unit = inquirer.select(
message="Distance unit:",
choices=[
{"name": "Meters", "value": "meters"},
{"name": "Yards", "value": "yards"}
],
default=default_distance
).execute()
console.print()
# Deviation unit
deviation_unit = inquirer.select(
message="Deviation unit:",
choices=[
{"name": "Meters", "value": "meters"},
{"name": "Feet", "value": "feet"},
{"name": "Yards", "value": "yards"}
],
default=default_deviation
).execute()
console.print()
console.print(f"[green]✓[/green] Units configured: {distance_unit} (distance), {deviation_unit} (deviation)")
return {
"distance": distance_unit,
"deviation": deviation_unit
}
def get_garmin_files() -> list[Path]:
"""
Get all Garmin CSV files from data/garmin directory.
Returns:
list[Path]: List of Path objects for CSV files found
"""
garmin_path = Path("data/garmin")
if not garmin_path.exists():
console.print("[red]Error: data/garmin directory not found![/red]")
console.print("[yellow]Please create the directory and add some Garmin CSV files.[/yellow]")
return []
files = sorted(garmin_path.glob("*.csv"))
return files
def select_sample_file(step_number: int = 2) -> Path | None:
"""
Select a sample Garmin file for configuration.
Args:
step_number: The step number to display (default: 2)
Returns:
Optional[Path]: Selected file path, or None if no files available
"""
files = get_garmin_files()
if not files:
console.print("[yellow]No Garmin CSV files found in data/garmin/[/yellow]")
console.print("[yellow]Please add at least one Garmin CSV file to continue.[/yellow]")
return None
console.print()
console.print(f"[bold]Step {step_number}: Select a sample Garmin file[/bold]")
console.print("This file will be used to detect your clubs and columns.")
console.print()
# Create choices for InquirerPy
choices = []
for file in files:
size = file.stat().st_size
size_str = f"{size / 1024:.1f} KB" if size > 1024 else f"{size} B"
choices.append({
"name": f"{file.name} ({size_str})",
"value": file
})
selected_file = inquirer.select(
message="Select a sample file:",
choices=choices,
default=files[0]
).execute()
return selected_file
def detect_columns(file_path: Path) -> list[str]:
"""
Detect all columns in the Garmin CSV file.
Args:
file_path: Path to the CSV file
Returns:
list[str]: List of column names found in the file
"""
try:
df = pd.read_csv(file_path, skiprows=[1], nrows=5)
return list(df.columns)
except Exception as e:
console.print(f"[red]Error reading file: {e}[/red]")
return []
def select_column_mapping(
columns: list[str],
template_col: str,
description: str,
existing_value: str | None,
fallback_index: int
) -> str:
"""
Helper to select a column mapping with defaults.
Args:
columns: List of available column names
template_col: Template column name being mapped
description: Human-readable description of the column
existing_value: Previously configured value (if any)
fallback_index: Index to use as default if existing_value not found
Returns:
str: Selected column name
"""
choices = [{"name": col, "value": col} for col in columns]
# Determine default value
if existing_value in columns:
default = existing_value
elif len(columns) > fallback_index:
default = columns[fallback_index]
else:
default = None
console.print(f"[bold yellow]Select the column containing {description}:[/bold yellow]")
selected = inquirer.select(
message=f"{template_col} column:",
choices=choices,
default=default
).execute()
console.print()
return selected
def configure_columns(
existing_config: dict | None = None,
step_number: int = 3
) -> tuple[Path | None, dict[str, str] | None]:
"""
Configure which Garmin columns map to template columns.
Args:
existing_config: Optional existing configuration to use as defaults
step_number: The step number to display (default: 3)
Returns:
tuple[Optional[Path], Optional[Dict[str, str]]]:
- File path used for detection
- Dictionary mapping template columns to Garmin columns
Returns (None, None) if configuration fails
"""
console.print()
console.print(Panel.fit(
f"[bold cyan]Step {step_number}: Column Mapping[/bold cyan]\n"
"Map Garmin columns to ShotPattern template columns",
border_style="cyan"
))
console.print()
file_path = select_sample_file(step_number)
if not file_path:
return None, None
console.print()
console.print(f"[cyan]Analyzing file:[/cyan] {file_path.name}")
columns = detect_columns(file_path)
if not columns:
return None, None
console.print(f"[green]✓[/green] Found {len(columns)} columns")
console.print()
# Display detected columns
console.print(create_item_table("📋 Detected Columns", columns, "Column Name"))
console.print()
# Get defaults from existing config
existing_columns = {}
if existing_config and "column_mapping" in existing_config:
existing_columns = existing_config["column_mapping"]
console.print("[dim]Using existing column mappings as defaults[/dim]")
console.print()
# Map required columns using helper function
column_mapping = {
"Club": select_column_mapping(columns, "Club", "club names", existing_columns.get("Club"), 0),
"Total": select_column_mapping(columns, "Total", "total distance", existing_columns.get("Total"), 1),
"Side": select_column_mapping(columns, "Side", "side deviation", existing_columns.get("Side"), 2)
}
console.print("[green]✓[/green] Column mapping configured")
console.print()
return file_path, column_mapping
def detect_clubs(file_path: Path, club_column: str) -> list[str]:
"""
Detect all unique clubs in the Garmin file.
Args:
file_path: Path to the CSV file
club_column: Name of the column containing club names
Returns:
list[str]: Sorted list of unique club names
"""
try:
df = pd.read_csv(file_path, skiprows=[1])
if club_column not in df.columns:
console.print(f"[red]Error: Column '{club_column}' not found![/red]")
return []
clubs = df[club_column].dropna().unique().tolist()
return sorted(clubs)
except Exception as e:
console.print(f"[red]Error reading clubs: {e}[/red]")
return []
def get_shotpattern_clubs() -> list[dict[str, str]]:
"""
Get list of available ShotPattern club identifiers.
Returns:
list[Dict[str, str]]: List of dictionaries with 'name' and 'value' keys
"""
from enums import ShotPatternClub
clubs = []
for club in ShotPatternClub:
clubs.append({
"name": f"{club.name}",
"value": club.value
})
return clubs
def configure_club_mappings(
file_path: Path,
club_column: str,
units: dict[str, str],
existing_config: dict | None = None,
step_number: int = 4
) -> tuple[dict[str, str], dict[str, int]]:
"""
Configure which Garmin clubs map to ShotPattern clubs.
Args:
file_path: Path to the CSV file with club data
club_column: Name of the column containing club names
units: Dictionary with distance and deviation units
existing_config: Optional existing configuration to use as defaults
step_number: The step number to display (default: 4)
Returns:
tuple[Dict[str, str], Dict[str, int]]:
- Dictionary mapping Garmin club names to ShotPattern identifiers
- Dictionary mapping ShotPattern identifiers to target distances
"""
console.print()
console.print(Panel.fit(
f"[bold cyan]Step {step_number}: Club Mapping[/bold cyan]\n"
"Map your Garmin clubs to ShotPattern identifiers",
border_style="cyan"
))
console.print()
console.print(f"[cyan]Detecting clubs in:[/cyan] {file_path.name}")
garmin_clubs = detect_clubs(file_path, club_column)
if not garmin_clubs:
return {}, {}
console.print(f"[green]✓[/green] Found {len(garmin_clubs)} unique clubs")
console.print()
# Display detected clubs
console.print(create_item_table("⛳ Detected Clubs", garmin_clubs, "Garmin Club Name"))
console.print()
# Get existing mappings
existing_club_mappings = {}
existing_target_distances = {}
if existing_config:
existing_club_mappings = existing_config.get("club_mappings", {})
existing_target_distances = existing_config.get("target_distances", {})
if existing_club_mappings:
console.print("[dim]Using existing club mappings as defaults[/dim]")
console.print()
# Get available ShotPattern clubs
shotpattern_clubs = get_shotpattern_clubs()
# Map each club
club_mappings = {}
target_distances = {}
console.print("[bold]Map each Garmin club to a ShotPattern identifier:[/bold]")
console.print("[dim]You can skip clubs that you don't want to include in the analysis.[/dim]")
console.print()
for garmin_club in garmin_clubs:
console.print(f"[bold cyan]{garmin_club}[/bold cyan]")
# Check if already mapped
already_mapped = garmin_club in existing_club_mappings
default_include = already_mapped # If previously mapped, default to True
# Ask if user wants to map this club
should_map = inquirer.confirm(
message=f"Include '{garmin_club}' in analysis?",
default=default_include
).execute()
if not should_map:
console.print("[dim]Skipped[/dim]")
console.print()
continue
# Get default values from existing config
default_shotpattern = existing_club_mappings.get(garmin_club, None)
default_distance = 150
if default_shotpattern and default_shotpattern in existing_target_distances:
default_distance = int(existing_target_distances[default_shotpattern])
# Select ShotPattern club
shotpattern_club = inquirer.select(
message="Map to ShotPattern club:",
choices=shotpattern_clubs,
default=default_shotpattern
).execute()
# Ask for target distance with unit display
distance_unit_label = units["distance"]
target_distance = inquirer.number(
message=f"Default target distance ({distance_unit_label}):",
default=int(default_distance),
min_allowed=0,
max_allowed=500,
float_allowed=False
).execute()
club_mappings[garmin_club] = shotpattern_club
target_distances[shotpattern_club] = target_distance
console.print(f"[green]✓[/green] Mapped to {shotpattern_club} (target: {target_distance} {distance_unit_label})")
console.print()
return club_mappings, target_distances
def save_configuration(
units: dict[str, str],
column_mapping: dict[str, str],
club_mappings: dict[str, str],
target_distances: dict[str, int]
) -> Path:
"""
Save the configuration to a JSON file.
Args:
units: Dictionary with distance and deviation units
column_mapping: Dictionary mapping template columns to Garmin columns
club_mappings: Dictionary mapping Garmin clubs to ShotPattern identifiers
target_distances: Dictionary mapping ShotPattern clubs to target distances
Returns:
Path: Path to the saved configuration file
"""
config = {
"units": units,
"column_mapping": column_mapping,
"club_mappings": club_mappings,
"target_distances": target_distances
}
config_file = Path("config.json")
with open(config_file, 'w') as f:
json.dump(config, f, indent=2)
console.print()
console.print("[green]✅ Configuration saved successfully![/green]")
console.print(f"[cyan]Configuration file:[/cyan] {config_file}")
console.print()
return config_file
def display_summary(
units: dict[str, str],
column_mapping: dict[str, str],
club_mappings: dict[str, str],
target_distances: dict[str, int]
) -> None:
"""
Display a summary of the configuration.
Args:
units: Dictionary with distance and deviation units
column_mapping: Dictionary mapping template columns to Garmin columns
club_mappings: Dictionary mapping Garmin clubs to ShotPattern identifiers
target_distances: Dictionary mapping ShotPattern clubs to target distances
"""
console.print()
console.print(Panel.fit(
"[bold cyan]Configuration Summary[/bold cyan]",
border_style="cyan"
))
console.print()
# Units summary
console.print("[bold]Units:[/bold]")
units_table = Table(show_header=True, header_style=TABLE_HEADER_STYLE)
units_table.add_column("Measurement", style="yellow")
units_table.add_column("Unit", style="cyan")
units_table.add_row("Distance", units["distance"])
units_table.add_row("Deviation", units["deviation"])
console.print(units_table)
console.print()
# Column mapping summary
console.print("[bold]Column Mappings:[/bold]")
col_table = Table(show_header=True, header_style=TABLE_HEADER_STYLE)
col_table.add_column("Template Column", style="yellow")
col_table.add_column("→", style="dim")
col_table.add_column("Garmin Column", style="cyan")
for key, value in column_mapping.items():
col_table.add_row(key, "→", value)
console.print(col_table)
console.print()
# Club mapping summary
distance_unit_label = units["distance"]
console.print("[bold]Club Mappings:[/bold]")
club_table = Table(show_header=True, header_style=TABLE_HEADER_STYLE)
club_table.add_column("Garmin Club", style="cyan")
club_table.add_column("→", style="dim")
club_table.add_column("ShotPattern Club", style="yellow")
club_table.add_column("Target Distance", style="green", justify="right")
for garmin_club, shotpattern_club in club_mappings.items():
target = target_distances.get(shotpattern_club, 0)
club_table.add_row(garmin_club, "→", shotpattern_club, f"{target} {distance_unit_label}")
console.print(club_table)
console.print()
def main() -> None:
"""Run the setup wizard."""
try:
# Display application header
print_app_header(console, "Setup Configuration Wizard")
# Load existing configuration if available
existing_config = load_existing_config()
# Step 1: Configure units
units = configure_units(existing_config)
# Step 2 & 3: Configure columns
file_path, column_mapping = configure_columns(existing_config, step_number=3)
if not file_path or not column_mapping:
console.print("[red]Setup cancelled - could not configure columns[/red]")
return
# Step 4: Configure club mappings
club_mappings, target_distances = configure_club_mappings(
file_path,
column_mapping["Club"],
units,
existing_config,
step_number=4
)
if not club_mappings:
console.print("[yellow]No clubs mapped - setup incomplete[/yellow]")
return
# Display summary
display_summary(units, column_mapping, club_mappings, target_distances)
# Save configuration
save_configuration(units, column_mapping, club_mappings, target_distances)
console.print("[bold green]✅ Setup complete![/bold green]")
console.print()
console.print("[cyan]Next steps:[/cyan]")
console.print(" 1. Review config.json to verify your settings")
console.print(" 2. Run the transformer: make run")
console.print()
except KeyboardInterrupt:
console.print()
console.print("[yellow]Setup cancelled by user[/yellow]")
except Exception as e:
console.print()
console.print(f"[red]Error during setup: {e}[/red]")
if __name__ == "__main__":
main()