-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1657 lines (1485 loc) · 62.8 KB
/
main.py
File metadata and controls
1657 lines (1485 loc) · 62.8 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import math
import os
import re
import sys
import argparse
import logging
from typing import Dict, List, Optional, Tuple
import matplotlib.pyplot as plt
import pandas as pd
class FriendlyArgumentParser(argparse.ArgumentParser):
"""Custom ArgumentParser that prints helpful error messages"""
def error(self, message):
print("\n" + "="*60)
print("ERROR: Invalid command usage")
print("="*60)
print(f"\n{message}\n")
print("USAGE:")
print(" python main.py [OPTIONS] [FORMAT ...]\n")
print("REQUIRED:")
print(" -i FILE Path to data file (.csv, .xls, .xlsx, .ods)")
print(" Default: input/csv/example_table.csv\n")
print("OPTIONAL:")
print(" --client NAME Name of client to highlight (auto-detected if not provided)")
print(" FORMAT ... Output format(s): html, pdf, png, svg, jpg, jpeg, webp, eps")
print(" Default: png")
print(" -h, --help Show full help message\n")
print("EXAMPLES:")
print(" python main.py")
print(" python main.py -i data.csv")
print(" python main.py -i data.xlsx --client 'Company Name'")
print(" python main.py -i data.csv html png svg")
print("="*60 + "\n")
sys.exit(2)
salary = 'salary'
location = 'location'
sal_min = 'salary_min'
sal_max = 'salary_max'
title = 'POSITION TITLE'
# Keywords that indicate a job is paid per-inspection rather than hourly
PER_INSPECTION_INDICATORS = ['per', 'inspection', 'fee', 'paid']
def is_per_inspection(value) -> bool:
"""Return True if a cell value signals per-inspection (not hourly) pay."""
if value is None:
return False
try:
if math.isnan(float(value)):
return False
except (ValueError, TypeError):
pass
s = str(value).strip().lower()
return any(indicator in s for indicator in PER_INSPECTION_INDICATORS)
def format_per_inspection_rate(rates):
"""Format a list of numeric inspection rates into a display string."""
if not rates:
return "Per Inspection"
unique = sorted(set(rates))
if len(unique) == 1:
return f"${unique[0]:,.2f} per inspection"
return f"${min(unique):,.2f} \u2013 ${max(unique):,.2f} per inspection"
def classify_special_status(combined_text: str) -> tuple:
"""
Given a combined string assembled from all non-numeric cell values for a
single (position, employer) pair, determine the special status type.
Returns a 3-tuple ``(status_type, display_text, reference)`` where:
* ``status_type`` – one of ``'district'``, ``'outsourced'``, ``'see'``,
or ``None`` (unrecognised / skip).
* ``display_text`` – human-readable label shown in the badge.
* ``reference`` – for ``'see'`` type, the raw reference string used to
look up a matching position; ``None`` otherwise.
"""
# Normalise whitespace
t = ' '.join(combined_text.split()).strip()
tl = t.lower()
if not tl:
return (None, t, None)
if 'outsourced' in tl:
return ('outsourced', 'Outsourced', None)
# "Cape Cod District" may appear split across two rows as "District" and
# "Cape Cod", so accept any combination that mentions both or either.
if 'cape cod' in tl or 'district' in tl:
return ('district', 'Cape Cod District', None)
if tl.startswith('see'):
ref = t[3:].strip() # everything after "see"
return ('see', ref, ref)
if 'done by' in tl:
ref = re.sub(r'(?i)done\s+by\s*', '', t).strip()
return ('done_by', ref, ref if ref else None)
return (None, t, None)
def find_position_match(reference: str, position_names: List[str]) -> Optional[str]:
"""
Try to find a position name in *position_names* that best matches the
short *reference* string (e.g. ``"Fin Dir"``).
Strategy
--------
1. Direct substring match (reference inside position name).
2. Word-prefix overlap: count how many reference words are a prefix of any
word in the position name. Require ≥ 50 % of reference words to match.
"""
if not reference:
return None
ref_lower = reference.lower()
ref_words = ref_lower.split()
if not ref_words:
return None
# 1. substring match
for pos in position_names:
if ref_lower in pos.lower():
return pos
# 2. word-prefix overlap
best_match = None
best_score = 0
for pos in position_names:
pos_words = pos.lower().replace('/', ' ').replace('&', ' ').split()
score = sum(
1 for rw in ref_words
if any(pw.startswith(rw) or rw.startswith(pw) for pw in pos_words)
)
if score > best_score:
best_score = score
best_match = pos
threshold = max(1, len(ref_words) * 0.5)
return best_match if best_score >= threshold else None
def render_special_status_badge(ss_info: dict, position_summaries: list) -> str:
"""
Return an HTML string (a styled ``<span>`` badge) for the given special
status. For ``'see'`` type, attempt to link to the referenced position.
"""
status_type = ss_info['type']
display = ss_info['display']
reference = ss_info.get('reference')
if status_type == 'district':
return (
'<span class="status-badge badge-district">'
'🏛 Cape Cod District'
'</span>'
)
if status_type == 'outsourced':
return (
'<span class="status-badge badge-outsourced">'
'🔄 Outsourced'
'</span>'
)
if status_type == 'see':
if reference and reference.lower() != 'above':
matched = find_position_match(
reference, [p['name'] for p in position_summaries]
)
if matched:
safe = matched.replace('/', '_')
return (
f'<span class="status-badge badge-see">'
f'🔗 See: <a href="#pos-{safe}">{matched}</a>'
f'</span>'
)
# Fall-through: show plain text (includes "see above")
label = f'See: {display}' if display else 'See above'
return f'<span class="status-badge badge-see">🔗 {label}</span>'
if status_type == 'done_by':
if reference:
matched = find_position_match(
reference, [p['name'] for p in position_summaries]
)
if matched:
safe = matched.replace('/', '_')
return (
f'<span class="status-badge badge-done-by">'
f'👥 Done by: <a href="#pos-{safe}">{matched}</a>'
f'</span>'
)
label = f'Done by: {display}' if display else 'Done by another position'
return f'<span class="status-badge badge-done-by">👥 {label}</span>'
# Unknown / unclassified
return f'<span class="status-badge badge-unknown">ℹ {display}</span>'
def read_data(file_path: str, ext: str, header_row: int = 0) -> pd.DataFrame:
"""Read a compensation data file into a DataFrame."""
converters = {title: str}
if ext == '.csv':
return pd.read_csv(file_path, converters=converters, skiprows=header_row, header=0)
elif ext in ['.xls', '.xlsx']:
return pd.read_excel(file_path, converters=converters, header=header_row)
elif ext == '.ods':
return pd.read_excel(file_path, engine='odf', converters=converters, header=header_row)
else:
raise ValueError(f"Unsupported file format: {ext}")
def remove_summary_columns(df):
bad_columns = [
"Comp Data Points",
"Comp Average",
"Comp Lo-Hi Range",
"Comp Median",
"75th Percent of Market",
"% Melrose Higher Lower than 75th Percentile"
]
for c in bad_columns:
df = df.drop(c, axis=1, errors='ignore')
return df
def combine_lines(df):
newdf = pd.DataFrame()
every_other_idx = df.index // 2
for column in df.columns:
newdf[column] = df.groupby(every_other_idx)[column].apply(list)
newdf[title] = newdf.apply(lambda row: [row[title][0]] * 2, axis=1)
return newdf
def normalize(df):
first = pd.DataFrame()
second = pd.DataFrame()
for c in df.columns:
first[c] = df.apply(lambda row: row[c][0], axis=1)
second[c] = df.apply(lambda row: row[c][1], axis=1)
return pd.concat([first, second])
def make_city_column(df):
melted = df.melt(
id_vars=[title],
value_vars=list(df.columns[1:]),
value_name=salary,
var_name=location
).dropna()
# Detect per-inspection rows BEFORE numeric coercion, then drop them from
# the hourly dataset so they never appear as a numeric bar in the chart.
per_inspection_raw = {} # {position: {employer: [raw_strings]}}
per_inspection_indices = []
for idx, row in melted.iterrows():
if is_per_inspection(row[salary]):
pos = row[title]
emp = row[location]
per_inspection_raw.setdefault(pos, {}).setdefault(emp, []).append(
str(row[salary]).strip()
)
per_inspection_indices.append(idx)
# Remove per-inspection rows from the hourly data entirely
melted = melted.drop(index=per_inspection_indices)
# Build per_inspection dict: extract numeric rates from raw strings.
# Also detect "fee paid" entries (cells containing "fee"/"paid" but not
# "per"/"inspection") so they can be labelled differently in the output.
per_inspection = {}
for pos, employers in per_inspection_raw.items():
per_inspection[pos] = {}
for emp, raw_values in employers.items():
rates = []
for v in raw_values:
nums = re.findall(r'\d+\.?\d*', v)
rates.extend(float(n) for n in nums)
combined_raw = ' '.join(raw_values).lower()
has_per_or_inspection = 'per' in combined_raw or 'inspection' in combined_raw
has_fee_or_paid = 'fee' in combined_raw or 'paid' in combined_raw
is_fee_paid = has_fee_or_paid and not has_per_or_inspection
per_inspection[pos][emp] = {
'rates': sorted(set(rates)),
'fee_paid': is_fee_paid,
}
# ------------------------------------------------------------------ #
# Detect other special statuses: Cape Cod District, outsourced, #
# "see <position>" references, etc. #
# These are non-numeric cell values that are NOT per-inspection. #
# They are collected here and removed before the numeric conversion #
# so they never produce NaN bars in the chart. #
# ------------------------------------------------------------------ #
per_insp_idx_set = set(per_inspection_indices)
special_raw: Dict[str, Dict[str, List[str]]] = {} # {pos: {emp: [values]}}
special_status_indices = []
for idx, row in melted.iterrows():
if idx in per_insp_idx_set:
continue # already handled
val = str(row[salary]).strip()
if not val:
continue
# Skip values that are purely numeric (with optional $, commas, etc.)
try:
float(val.replace(',', '').replace('$', ''))
continue # numeric — leave for the normal conversion
except (ValueError, TypeError):
pass
# Also skip values that look numeric via the extraction regex
if re.fullmatch(r'\$?\s*[\d,]+\.?\d*', val):
continue
pos = row[title]
emp = row[location]
special_raw.setdefault(pos, {}).setdefault(emp, []).append(val)
special_status_indices.append(idx)
# Drop special-status rows so they don't end up as NaN after coercion
melted = melted.drop(index=special_status_indices)
# Classify the combined text for each (position, employer) pair
special_statuses: Dict[str, Dict[str, dict]] = {}
for pos, employers in special_raw.items():
for emp, values in employers.items():
combined = ' '.join(values)
status_type, display_text, reference = classify_special_status(combined)
if status_type is not None:
special_statuses.setdefault(pos, {})[emp] = {
'type': status_type,
'display': display_text,
'reference': reference,
}
# Convert salary to numeric
melted[salary] = pd.to_numeric(
melted[salary].astype(str).str.extract(r'(\d+\.?\d*)', expand=False),
errors='coerce'
)
melted = melted.dropna(subset=[salary])
# Filter out empty titles
melted = melted[melted[title].str.len() > 0]
return melted, per_inspection, special_statuses
def combine_high_low(df, location_name):
groups = df.groupby([location, title])
def helper(group):
minimum = group[salary].min()
maximum = group[salary].max()
# if minimum == maximum:
# minimum = minimum * .99
# maximum = maximum
client_color = '#e8f4fd'#'#AAA'
default_color = '#FFF'
if location_name in group[location].iloc[0]:
color = client_color
else:
color = default_color
return pd.Series(
data={
location: group[location].iloc[0],
title: group[title].iloc[0],
sal_min: minimum,
sal_max: maximum,
'color': color
},
index=[location, title, sal_min, sal_max, 'color']
)
return pd.concat([helper(group) for name, group in groups], axis=1).transpose()
def generate_text_summary(df: pd.DataFrame) -> str:
"""Generate a text summary of compensation statistics for all positions."""
from datetime import datetime
lines = [
"=" * 60,
"COMPENSATION ANALYSIS SUMMARY REPORT",
"=" * 60,
f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"",
]
position_count = df[title].nunique()
employer_count = df[location].nunique()
lines.append(f"Positions analyzed: {position_count}")
lines.append(f"Employers compared: {employer_count}")
lines.append("-" * 60)
lines.append("")
for pos_name, group in df.groupby(title):
all_salaries = pd.concat([group[sal_min], group[sal_max]])
lines.extend([
f"Position: {pos_name}",
f" Employers: {len(group)}",
f" Min salary: ${group[sal_min].min():,.2f}",
f" Max salary: ${group[sal_max].max():,.2f}",
f" Median: ${all_salaries.median():,.2f}",
f" Mean: ${all_salaries.mean():,.2f}",
"",
])
lines.append("=" * 60)
return "\n".join(lines)
def graph(df, output, client_name: str = '', show_labels: bool = False, show_grid: bool = True):
for name, group in df.groupby(title):
# Sanitize name for filename by replacing slashes with underscores
safe_name = name.replace('/', '_')
group = group.sort_values(by=sal_max, ascending=True)
fig, ax = plt.subplots(figsize=(10, 8))
heights = group[sal_max] - group[sal_min]
# Calculate y-axis range to determine appropriate thickness for zero-height bars
all_salaries = pd.concat([group[sal_min], group[sal_max]])
y_range = all_salaries.max() - all_salaries.min()
# Use a fixed percentage of the y-axis range for consistent thickness
ZERO_BAR_THICKNESS_RATIO = 0.02 # 2% of y-axis range
zero_bar_height = y_range * ZERO_BAR_THICKNESS_RATIO if y_range > 0 else 1.0
# Adjust heights for zero-height bars
adjusted_heights = []
for h in heights:
if h == 0:
adjusted_heights.append(zero_bar_height)
else:
adjusted_heights.append(h)
linewidths = [3 if h == 0 else 1 for h in heights]
bars = ax.bar(group[location], adjusted_heights, bottom=group[sal_min], color=group['color'], edgecolor='black', linewidth=linewidths, zorder=3)
if show_labels:
for bar, (_, row) in zip(bars, group.iterrows()):
ax.annotate(
f'${row[sal_max]:,.0f}',
xy=(bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()),
xytext=(0, 3), textcoords='offset points',
ha='center', va='bottom', fontsize=7,
)
ax.set_ylabel("Hourly Pay")
ax.set_xlabel("Location")
# ax.set_title(name)
if show_grid:
ax.grid(True, color="#AAA", zorder=0)
ax.tick_params(axis="x", labelrotation=45, labelsize=8)
plt.setp(ax.get_xticklabels(), ha="right")
if client_name:
fig.canvas.draw()
for label in ax.get_xticklabels():
if client_name in label.get_text():
label.set_color('#1565C0')
label.set_fontweight('bold')
plt.tight_layout()
output_configs = {
'pdf': ('output/pdf', 'pdf'),
'png': ('output/png', 'png'),
'svg': ('output/svg', 'svg'),
'jpg': ('output/jpg', 'jpg'),
'jpeg': ('output/jpeg', 'jpeg'),
'webp': ('output/webp', 'webp'),
'eps': ('output/eps', 'eps'),
}
for fmt in output:
if fmt in output_configs:
dir_path, ext = output_configs[fmt]
os.makedirs(dir_path, exist_ok=True)
fig.savefig(f"{dir_path}/{safe_name}.{fmt}", bbox_inches="tight")
plt.close(fig)
def chart_to_svg(group: pd.DataFrame, name: str, client_name: str = '', show_labels: bool = False, show_grid: bool = True) -> str:
"""Generate a bar chart for a position group and return it as an inline SVG string."""
group = group.sort_values(by=sal_max, ascending=True)
fig, ax = plt.subplots(figsize=(10, 8))
heights = group[sal_max] - group[sal_min]
# Calculate y-axis range to determine appropriate thickness for zero-height bars
all_salaries = pd.concat([group[sal_min], group[sal_max]])
y_range = all_salaries.max() - all_salaries.min()
# Use a fixed percentage of the y-axis range for consistent thickness
ZERO_BAR_THICKNESS_RATIO = 0.02 # 2% of y-axis range
zero_bar_height = y_range * ZERO_BAR_THICKNESS_RATIO if y_range > 0 else 1.0
# Adjust heights for zero-height bars
adjusted_heights = []
for h in heights:
if h == 0:
adjusted_heights.append(zero_bar_height)
else:
adjusted_heights.append(h)
linewidths = [3 if h == 0 else 1 for h in heights]
bars = ax.bar(group[location], adjusted_heights, bottom=group[sal_min], color=group['color'],
edgecolor='black', linewidth=linewidths, zorder=3)
if show_labels:
for bar, (_, row) in zip(bars, group.iterrows()):
ax.annotate(
f'${row[sal_max]:,.0f}',
xy=(bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()),
xytext=(0, 3), textcoords='offset points',
ha='center', va='bottom', fontsize=7,
)
ax.set_ylabel("Hourly Pay")
ax.set_xlabel("Location")
#ax.set_title(name)
if show_grid:
ax.grid(True, color="#AAA", zorder=0)
plt.xticks(rotation=60, ha='right', fontsize=8)
if client_name:
fig.canvas.draw()
for label in ax.get_xticklabels():
if client_name in label.get_text():
label.set_color('#1565C0')
label.set_fontweight('bold')
plt.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format='svg', bbox_inches='tight')
plt.close(fig)
buf.seek(0)
svg_string = buf.read().decode('utf-8')
# Strip XML declaration, keep just the <svg>...</svg> element
svg_content = svg_string[svg_string.find('<svg'):]
return svg_content
def graph_with_html(df, output_formats, client_name, input_file, per_inspection=None,
special_statuses=None,
show_labels: bool = False, show_grid: bool = True):
"""Generate graphs with optional HTML output"""
# Generate image formats (non-HTML)
image_formats = [fmt for fmt in output_formats if fmt != "html"]
if image_formats:
graph(df, image_formats, client_name=client_name, show_labels=show_labels, show_grid=show_grid)
# Generate HTML if requested
if 'html' in output_formats:
generate_html_report(df, client_name, input_file,
per_inspection or {},
special_statuses or {},
show_labels=show_labels, show_grid=show_grid)
def generate_html_report(df, client_name, input_file, per_inspection=None,
special_statuses=None,
show_labels: bool = False, show_grid: bool = True):
"""Generate a self-contained HTML report with interactive Chart.js charts and filterable tables."""
import json
from datetime import datetime
if per_inspection is None:
per_inspection = {}
if special_statuses is None:
special_statuses = {}
# Group data by position for HTML generation
position_summaries = []
for position_name, group in df.groupby(title):
safe_name = position_name.replace('/', '_')
# Escape single quotes for JavaScript string literals
safe_name_js = safe_name.replace("'", "\\'")
# Store both versions in the position data
position_data = {
'name': position_name,
'safe_name': safe_name,
}
# Continue with the rest of the data gathering
# Sort by salary range
sorted_group = group.sort_values(by=sal_max, ascending=True)
# Create position summary (hourly employers) — these drive the chart
chart_data = [] # only numeric/hourly rows go in the chart
employers_data = []
for _, row in sorted_group.iterrows():
is_client = client_name in row[location]
chart_data.append({
'employer': row[location],
'min': float(row[sal_min]),
'max': float(row[sal_max]),
'color': '#e8f4fd' if is_client else '#ffffff',
'borderColor': '#1565C0' if is_client else '#333333',
'is_client': is_client,
})
employers_data.append({
'employer': row[location],
'min_salary': row[sal_min],
'max_salary': row[sal_max],
'is_client': is_client,
'per_inspection': False,
})
# Append per-inspection / fee-paid employers for this position (sorted by name)
for pi_employer, pi_data in sorted(per_inspection.get(position_name, {}).items()):
employers_data.append({
'employer': pi_employer,
'is_client': client_name in pi_employer,
'per_inspection': True,
'rates': pi_data['rates'],
'fee_paid': pi_data.get('fee_paid', False),
})
# Append special-status employers (Cape Cod District, outsourced, see X)
for ss_employer, ss_info in sorted(special_statuses.get(position_name, {}).items()):
employers_data.append({
'employer': ss_employer,
'is_client': client_name in ss_employer,
'per_inspection': False,
'special_status': ss_info,
})
position_summaries.append({
'name': position_name,
'safe_name': safe_name,
'safe_name_js': safe_name_js,
'employers': employers_data,
'chart_data': chart_data,
})
# Serialise per-position chart data to JSON for embedding in HTML
all_chart_data_json = json.dumps(
{p['safe_name']: p['chart_data'] for p in position_summaries},
ensure_ascii=False
)
# Generate HTML
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
input_stem = os.path.splitext(os.path.basename(input_file))[0]
html_content = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Compensation Analysis Report - {client_name}</title>
<!-- Chart.js for interactive bar charts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<style>
body {{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}}
.header {{
background: linear-gradient(135deg, #667eea 0%, #aeceaf 100%);
color: white;
padding: 30px;
border-radius: 10px;
margin-bottom: 30px;
text-align: center;
}}
/* ── Legend / Table of Contents ── */
.legend {{
background: white;
border-radius: 8px;
padding: 20px 24px;
margin-bottom: 30px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}}
.legend h2 {{
margin: 0 0 12px 0;
font-size: 1.1em;
color: #2c3e50;
}}
.search-bar {{
width: 100%;
box-sizing: border-box;
padding: 8px 12px;
font-size: 0.95em;
border: 1px solid #ccc;
border-radius: 6px;
margin-bottom: 14px;
outline: none;
transition: border-color 0.2s;
}}
.search-bar:focus {{
border-color: #3498db;
}}
.legend-list {{
display: flex;
flex-wrap: wrap;
gap: 6px 10px;
list-style: none;
margin: 0;
padding: 0;
max-height: 220px;
overflow-y: auto;
}}
.legend-list li {{
flex: 0 0 auto;
}}
.legend-list a {{
display: inline-block;
padding: 3px 10px;
background: #eaf4fb;
border: 1px solid #b6d9f0;
border-radius: 20px;
color: #2471a3;
text-decoration: none;
font-size: 0.85em;
transition: background 0.15s, color 0.15s;
white-space: nowrap;
}}
.legend-list a:hover {{
background: #3498db;
color: white;
border-color: #2980b9;
}}
.legend-toggle {{
float: right;
background: none;
border: 1px solid #aaa;
border-radius: 4px;
width: 22px;
height: 22px;
line-height: 18px;
text-align: center;
font-size: 1.1em;
color: #555;
cursor: pointer;
padding: 0;
margin-top: 1px;
transition: background 0.15s, color 0.15s;
}}
.legend-toggle:hover {{
background: #3498db;
color: white;
border-color: #2980b9;
}}
.legend-item-hidden {{
display: none !important;
}}
.no-results {{
color: #999;
font-style: italic;
font-size: 0.9em;
padding: 4px 0;
}}
/* ── Position Cards ── */
.position-card {{
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
scroll-margin-top: 20px;
}}
.position-card.card-hidden {{
display: none;
}}
.position-title {{
font-size: 1.5em;
font-weight: bold;
color: #2c3e50;
margin-bottom: 15px;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}}
.chart-container {{
position: relative;
margin: 20px 0;
width: 100%;
/* Use min-height instead of fixed height for better responsiveness */
min-height: 400px;
height: auto;
aspect-ratio: 16 / 9; /* Maintains a professional look */
border: 1px solid #eee; /* Optional: adds definition */
overflow: hidden; /* Prevents internal graph elements from leaking out */
}}
.chart-container img, .chart-container canvas {{
width: 100%;
height: 100%;
object-fit: contain; /* Ensures the graph isn't distorted */
}}
/* ── Table ── */
.salary-table {{
width: 100%;
border-collapse: collapse;
margin-top: 15px;
}}
.salary-table th, .salary-table td {{
border: 1px solid #ddd;
padding: 8px 12px;
text-align: left;
}}
.salary-table th {{
background-color: #f8f9fa;
font-weight: bold;
}}
/* ── Sortable column headers ── */
.sortable {{
cursor: pointer;
user-select: none;
white-space: nowrap;
}}
.sortable:hover {{
background-color: #e9ecef;
}}
.sort-icon {{
display: inline-block;
margin-left: 4px;
color: #aaa;
font-size: 0.85em;
vertical-align: middle;
}}
.sortable.sort-asc .sort-icon,
.sortable.sort-desc .sort-icon {{
color: #3498db;
}}
.client-row {{
background-color: #e8f4fd;
font-weight: bold;
}}
.salary-range {{
font-family: 'Courier New', monospace;
font-weight: bold;
}}
.per-inspection-row td {{
color: #888;
font-style: italic;
}}
.per-inspection-badge {{
display: inline-block;
background: #fff3cd;
border: 1px solid #ffc107;
color: #856404;
border-radius: 4px;
padding: 1px 7px;
font-size: 0.82em;
font-style: normal;
white-space: nowrap;
}}
/* ── Special-status badges ── */
.special-status-row td {{
color: #555;
font-style: italic;
}}
.status-badge {{
display: inline-block;
border-radius: 4px;
padding: 1px 7px;
font-size: 0.82em;
font-style: normal;
white-space: nowrap;
}}
.badge-district {{
background: #cce5ff;
border: 1px solid #004085;
color: #004085;
}}
.badge-outsourced {{
background: #fde8d8;
border: 1px solid #c0392b;
color: #c0392b;
}}
.badge-see {{
background: #e8f5e9;
border: 1px solid #2e7d32;
color: #2e7d32;
}}
.badge-see a {{
color: #1a5e20;
text-decoration: underline;
}}
.badge-unknown {{
background: #f5f5f5;
border: 1px solid #888;
color: #555;
}}
.fee-paid-badge {{
display: inline-block;
background: #e8f5e9;
border: 1px solid #2e7d32;
color: #2e7d32;
border-radius: 4px;
padding: 1px 7px;
font-size: 0.82em;
font-style: normal;
white-space: nowrap;
}}
.badge-done-by {{
background: #f3e5f5;
border: 1px solid #7b1fa2;
color: #7b1fa2;
}}
.badge-done-by a {{
color: #4a0072;
text-decoration: underline;
}}
.summary {{
background: #ecf0f1;
padding: 20px;
border-radius: 8px;
margin-top: 30px;
}}
.stats {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-top: 15px;
}}
.stat-box {{
background: white;
padding: 15px;
border-radius: 5px;
text-align: center;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}}
.stat-value {{
font-size: 1.5em;
font-weight: bold;
color: #3498db;
}}
.stat-label {{
color: #7f8c8d;
font-size: 0.9em;
}}
/* ── Row hover highlight (from table or from chart bar) ── */
.salary-table tbody tr {{
transition: background-color 0.1s;
}}
.salary-table tbody tr.row-hover,
.salary-table tbody tr.bar-hover {{
background-color: #aeceaf !important;
cursor: default;
}}
/* ── Back-to-top button ── */
#backToTop {{
display: none;
position: fixed;
bottom: 28px;
right: 28px;
z-index: 999;
background: #3498db;
color: white;
border: none;
border-radius: 50px;
padding: 10px 16px;
font-size: 0.9em;
font-weight: bold;
cursor: pointer;
box-shadow: 0 3px 10px rgba(0,0,0,0.25);
transition: background 0.2s, opacity 0.2s;
opacity: 0.85;
}}
#backToTop:hover {{
background: #2980b9;
opacity: 1;
}}
</style>
</head>
<body>
<div class="header">
<h1>{input_stem}</h1>
<h2>{client_name}, MA</h2>
<h3>FY-26 Market Data</h3>
</div>
<!-- Legend / Table of Contents -->
<div class="legend" id="legend">
<h2>🔍 Search<button class="legend-toggle" id="legendToggle" title="Show/hide">−</button></h2>
<div id="legendBody">
<input
class="search-bar"
id="positionSearch"
type="search"
placeholder="Search"
autocomplete="off"
/>