Spaces:
Sleeping

GitHub Actions commited on
Commit
d1a14fd
Β·
0 Parent(s):

Deploy from GitHub 2e77da18dfbfb7cba94e60bcc53b33d28dcbfe06

Browse files
Files changed (7) hide show
  1. README.md +11 -0
  2. app.py +359 -0
  3. assets/skoda_logo.png +0 -0
  4. excel_export.py +81 -0
  5. requirements.txt +7 -0
  6. scoring.py +80 -0
  7. storage.py +207 -0
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Gurudev Motors BDIT Score
3
+ emoji: πŸš—
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: false
9
+ ---
10
+
11
+ Gurudev Motors β€” Best Dealer in Town sales KPI score calculator.
app.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gurudev Motors β€” Best Dealer In Town Sales Score Calculator (Gradio web edition)."""
2
+
3
+ import base64
4
+ import datetime
5
+ import os
6
+
7
+ import gradio as gr
8
+ import pandas as pd
9
+
10
+ try:
11
+ import spaces # Hugging Face's ZeroGPU helper β€” a no-op outside that runtime
12
+ except ImportError:
13
+ spaces = None
14
+
15
+ from scoring import KPIS, TOTAL_WT, MONTHS, QUARTERS, SLAB_COLOR, compute_slab
16
+ from storage import load_db, save_entry
17
+ from excel_export import build_workbook
18
+
19
+ if spaces is not None:
20
+ @spaces.GPU
21
+ def _zerogpu_startup_check():
22
+ """This app never uses a GPU, but Spaces on ZeroGPU hardware require at
23
+ least one @spaces.GPU-decorated function to exist or the Space fails
24
+ to start. Never called."""
25
+ return True
26
+
27
+ ASSET_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
28
+ LOGO_PATH = os.path.join(ASSET_DIR, "skoda_logo.png")
29
+
30
+ with open(LOGO_PATH, "rb") as f:
31
+ _LOGO_DATA_URI = "data:image/png;base64," + base64.b64encode(f.read()).decode()
32
+
33
+ MONTH_ORDER = {m: i for i, m in enumerate(MONTHS)}
34
+ TODAY = datetime.date.today()
35
+
36
+ CUSTOM_CSS = """
37
+ .app-header {
38
+ display: flex; align-items: center; gap: 16px;
39
+ padding: 14px 22px; margin-bottom: 1rem;
40
+ background: linear-gradient(135deg, #0f3460, #16213e);
41
+ border-bottom: 3px solid #4caf50; border-radius: 8px;
42
+ }
43
+ .app-header img { height: 48px; width: 48px; }
44
+ .app-header .titles { display: flex; flex-direction: column; justify-content: center; }
45
+ .app-header .main-title { font-size: 1.4rem; font-weight: 700; color: #f2f2f2; line-height: 1.2; }
46
+ .app-header .sub-title { font-size: 0.9rem; font-weight: 600; color: #4caf50; line-height: 1.3; }
47
+
48
+ .kpi-name { font-size: 1rem; font-weight: 600; margin-bottom: 2px; }
49
+ .kpi-hint { font-size: 0.78rem; color: #b8c2d6; margin-bottom: 6px; }
50
+ .slab-badge {
51
+ display: inline-block; padding: 6px 12px; border-radius: 6px;
52
+ font-weight: 600; font-size: 0.9rem;
53
+ }
54
+ .total-score { text-align: right; }
55
+ """
56
+
57
+ HEADER_HTML = f"""
58
+ <div class="app-header">
59
+ <img src="{_LOGO_DATA_URI}" />
60
+ <div class="titles">
61
+ <span class="main-title">Gurudev Motors Pvt. Ltd</span>
62
+ <span class="sub-title">Best Dealer in Town β€” Sales Score Calculator</span>
63
+ </div>
64
+ </div>
65
+ """
66
+
67
+
68
+ def _badge(kpi, val):
69
+ if val is None:
70
+ return "β€”"
71
+ pct, lbl, score = compute_slab(kpi, val)
72
+ color = SLAB_COLOR[pct]
73
+ return (f"<span class='slab-badge' style='background:{color}20;color:{color};'>"
74
+ f"{lbl} Β· {score} pts</span>")
75
+
76
+
77
+ def _recompute(*vals):
78
+ badges = [_badge(kpi, v) for kpi, v in zip(KPIS, vals)]
79
+ if any(v is None for v in vals):
80
+ total_md = "### Total Score: β€”"
81
+ else:
82
+ total = sum(compute_slab(kpi, v)[2] for kpi, v in zip(KPIS, vals))
83
+ total_md = f"### Total Score: {total} / {TOTAL_WT} ({total / TOTAL_WT * 100:.1f}%)"
84
+ return badges + [total_md]
85
+
86
+
87
+ def _on_submit(username, month, year, *vals):
88
+ if not username or not username.strip():
89
+ return "❌ Please enter a user name."
90
+ if any(v is None for v in vals):
91
+ return "❌ Please enter a value for every KPI."
92
+ scores = {}
93
+ for kpi, v in zip(KPIS, vals):
94
+ pct, lbl, score = compute_slab(kpi, v)
95
+ scores[kpi["name"]] = {"value": v, "pct": pct, "label": lbl, "score": score}
96
+ save_entry(username.strip(), int(year), month, scores)
97
+ total = sum(s["score"] for s in scores.values())
98
+ return f"βœ… Saved {username.strip()} β€” {month} {int(year)}: {total} / {TOTAL_WT}"
99
+
100
+
101
+ def _refresh_hist_users():
102
+ db = load_db()
103
+ users = sorted(db.keys())
104
+ return gr.update(choices=users, value=users[0] if users else None)
105
+
106
+
107
+ def _refresh_hist_years(user):
108
+ db = load_db()
109
+ years = sorted(db.get(user, {}).keys()) if user else []
110
+ return gr.update(choices=years, value=years[-1] if years else None)
111
+
112
+
113
+ def _show_history(user, year):
114
+ db = load_db()
115
+ if not user or not year or user not in db or year not in db.get(user, {}):
116
+ return pd.DataFrame(), "No entries for this year yet."
117
+
118
+ yd = db[user][year]
119
+ entered_months = sorted(yd.keys(), key=lambda m: MONTH_ORDER.get(m, 99))
120
+
121
+ rows = []
122
+ for m in entered_months:
123
+ row = {"Month": m}
124
+ tot = 0
125
+ for kpi in KPIS:
126
+ d = yd[m].get(kpi["name"], {})
127
+ row[kpi["name"]] = d.get("score", "")
128
+ tot += d.get("score", 0) or 0
129
+ row["Total"] = tot
130
+ rows.append(row)
131
+ df = pd.DataFrame(rows)
132
+
133
+ quarter_lines = []
134
+ for qk, qinfo in QUARTERS.items():
135
+ counted_present = [m for m in qinfo["counted"] if m in yd]
136
+ if len(counted_present) >= 2:
137
+ avg = {}
138
+ for kpi in KPIS:
139
+ vals = [yd[m][kpi["name"]]["score"] for m in counted_present
140
+ if kpi["name"] in yd.get(m, {})]
141
+ avg[kpi["name"]] = sum(vals) / len(vals) if vals else 0.0
142
+ avg_line = " Β· ".join(f"{k}: {v:.1f}" for k, v in avg.items())
143
+ quarter_lines.append(
144
+ f"**{qinfo['label']}** β€” {avg_line} \n"
145
+ f"Quarterly Avg Total: **{sum(avg.values()):.1f} / {TOTAL_WT}**"
146
+ )
147
+ return df, ("\n\n".join(quarter_lines) if quarter_lines else "")
148
+
149
+
150
+ def _refresh_team_years():
151
+ db = load_db()
152
+ years = sorted({y for u in db.values() for y in u.keys()})
153
+ return gr.update(choices=years, value=years[-1] if years else None)
154
+
155
+
156
+ def _show_leaderboard(month, year):
157
+ db = load_db()
158
+ leaderboard = []
159
+ for user, years in db.items():
160
+ yd = years.get(str(year), {})
161
+ md = yd.get(month)
162
+ if md:
163
+ tot = sum(v.get("score", 0) or 0 for v in md.values())
164
+ leaderboard.append({"User": user, "Total Score": tot,
165
+ "%": round(tot / TOTAL_WT * 100, 1)})
166
+ if not leaderboard:
167
+ return pd.DataFrame(columns=["User", "Total Score", "%"])
168
+ return pd.DataFrame(leaderboard).sort_values("Total Score", ascending=False)
169
+
170
+
171
+ def _export_excel():
172
+ db = load_db()
173
+ xlsx_bytes = build_workbook(db)
174
+ path = os.path.join("/tmp", "skoda_scores.xlsx")
175
+ with open(path, "wb") as f:
176
+ f.write(xlsx_bytes)
177
+ return path
178
+
179
+
180
+ # Dark palette matching the original desktop app. Every token is set for
181
+ # BOTH its light and _dark variant to the same value, so the UI stays dark
182
+ # regardless of the visitor's browser/OS color-scheme preference.
183
+ _BG = "#1a1a2e" # page background
184
+ _PANEL = "#16213e" # block/card background
185
+ _INPUT = "#0d2137" # input fields, table stripes
186
+ _BORDER = "#2a3a5c"
187
+ _TEXT = "#f2f2f2" # primary text β€” high contrast on dark
188
+ _DIM = "#b8c2d6" # secondary text β€” still readable, not washed out
189
+ _ACCENT = "#4caf50"
190
+ _ACCENT_HOVER = "#5fc563"
191
+ _RED = "#e94560"
192
+
193
+ theme = gr.themes.Default(primary_hue="green", neutral_hue="slate").set(
194
+ body_background_fill=_BG, body_background_fill_dark=_BG,
195
+ body_text_color=_TEXT, body_text_color_dark=_TEXT,
196
+ body_text_color_subdued=_DIM, body_text_color_subdued_dark=_DIM,
197
+
198
+ background_fill_primary=_PANEL, background_fill_primary_dark=_PANEL,
199
+ background_fill_secondary=_INPUT, background_fill_secondary_dark=_INPUT,
200
+
201
+ border_color_primary=_BORDER, border_color_primary_dark=_BORDER,
202
+ border_color_accent=_ACCENT, border_color_accent_dark=_ACCENT,
203
+ border_color_accent_subdued=_ACCENT, border_color_accent_subdued_dark=_ACCENT,
204
+
205
+ link_text_color=_ACCENT, link_text_color_dark=_ACCENT,
206
+ link_text_color_hover=_ACCENT_HOVER, link_text_color_hover_dark=_ACCENT_HOVER,
207
+ link_text_color_active=_ACCENT, link_text_color_active_dark=_ACCENT,
208
+ link_text_color_visited=_ACCENT, link_text_color_visited_dark=_ACCENT,
209
+
210
+ code_background_fill=_INPUT, code_background_fill_dark=_INPUT,
211
+
212
+ block_background_fill=_PANEL, block_background_fill_dark=_PANEL,
213
+ block_border_color=_BORDER, block_border_color_dark=_BORDER,
214
+ block_info_text_color=_DIM, block_info_text_color_dark=_DIM,
215
+ block_label_background_fill=_PANEL, block_label_background_fill_dark=_PANEL,
216
+ block_label_border_color=_BORDER, block_label_border_color_dark=_BORDER,
217
+ block_label_text_color=_TEXT, block_label_text_color_dark=_TEXT,
218
+ block_title_background_fill=_PANEL, block_title_background_fill_dark=_PANEL,
219
+ block_title_border_color=_BORDER, block_title_border_color_dark=_BORDER,
220
+ block_title_text_color=_TEXT, block_title_text_color_dark=_TEXT,
221
+
222
+ panel_background_fill=_PANEL, panel_background_fill_dark=_PANEL,
223
+ panel_border_color=_BORDER, panel_border_color_dark=_BORDER,
224
+
225
+ accordion_text_color=_TEXT, accordion_text_color_dark=_TEXT,
226
+
227
+ table_text_color=_TEXT, table_text_color_dark=_TEXT,
228
+ table_border_color=_BORDER, table_border_color_dark=_BORDER,
229
+ table_even_background_fill=_PANEL, table_even_background_fill_dark=_PANEL,
230
+ table_odd_background_fill=_INPUT, table_odd_background_fill_dark=_INPUT,
231
+
232
+ checkbox_background_color=_INPUT, checkbox_background_color_dark=_INPUT,
233
+ checkbox_background_color_selected=_ACCENT, checkbox_background_color_selected_dark=_ACCENT,
234
+ checkbox_border_color=_BORDER, checkbox_border_color_dark=_BORDER,
235
+ checkbox_border_color_selected=_ACCENT, checkbox_border_color_selected_dark=_ACCENT,
236
+ checkbox_label_background_fill=_PANEL, checkbox_label_background_fill_dark=_PANEL,
237
+ checkbox_label_background_fill_selected=_ACCENT, checkbox_label_background_fill_selected_dark=_ACCENT,
238
+ checkbox_label_border_color=_BORDER, checkbox_label_border_color_dark=_BORDER,
239
+ checkbox_label_text_color=_TEXT, checkbox_label_text_color_dark=_TEXT,
240
+ checkbox_label_text_color_selected="#ffffff", checkbox_label_text_color_selected_dark="#ffffff",
241
+
242
+ error_background_fill="#3a1620", error_background_fill_dark="#3a1620",
243
+ error_border_color=_RED, error_border_color_dark=_RED,
244
+ error_text_color="#ff93a6", error_text_color_dark="#ff93a6",
245
+
246
+ input_background_fill=_INPUT, input_background_fill_dark=_INPUT,
247
+ input_background_fill_focus=_INPUT, input_background_fill_focus_dark=_INPUT,
248
+ input_background_fill_hover=_INPUT, input_background_fill_hover_dark=_INPUT,
249
+ input_border_color=_BORDER, input_border_color_dark=_BORDER,
250
+ input_border_color_focus=_ACCENT, input_border_color_focus_dark=_ACCENT,
251
+ input_border_color_hover=_ACCENT, input_border_color_hover_dark=_ACCENT,
252
+
253
+ stat_background_fill=_INPUT, stat_background_fill_dark=_INPUT,
254
+
255
+ button_primary_background_fill=_ACCENT, button_primary_background_fill_dark=_ACCENT,
256
+ button_primary_background_fill_hover=_ACCENT_HOVER, button_primary_background_fill_hover_dark=_ACCENT_HOVER,
257
+ button_primary_border_color=_ACCENT, button_primary_border_color_dark=_ACCENT,
258
+ button_primary_text_color="#ffffff", button_primary_text_color_dark="#ffffff",
259
+ button_primary_text_color_hover="#ffffff", button_primary_text_color_hover_dark="#ffffff",
260
+
261
+ button_secondary_background_fill=_INPUT, button_secondary_background_fill_dark=_INPUT,
262
+ button_secondary_background_fill_hover=_PANEL, button_secondary_background_fill_hover_dark=_PANEL,
263
+ button_secondary_border_color=_BORDER, button_secondary_border_color_dark=_BORDER,
264
+ button_secondary_text_color=_TEXT, button_secondary_text_color_dark=_TEXT,
265
+ button_secondary_text_color_hover=_TEXT, button_secondary_text_color_hover_dark=_TEXT,
266
+
267
+ button_cancel_background_fill=_RED, button_cancel_background_fill_dark=_RED,
268
+ button_cancel_background_fill_hover="#ff6b85", button_cancel_background_fill_hover_dark="#ff6b85",
269
+ button_cancel_border_color=_RED, button_cancel_border_color_dark=_RED,
270
+ button_cancel_text_color="#ffffff", button_cancel_text_color_dark="#ffffff",
271
+ )
272
+
273
+ with gr.Blocks(title="BDIT Sales Score") as demo:
274
+ gr.HTML(HEADER_HTML)
275
+
276
+ with gr.Tabs():
277
+ # ── Enter Score ───────────────────────────────────────────────────
278
+ with gr.Tab("✍️ Enter Score"):
279
+ with gr.Row():
280
+ username_in = gr.Textbox(label="User Name")
281
+ month_in = gr.Dropdown(MONTHS, value=MONTHS[TODAY.month - 1], label="Month")
282
+ year_in = gr.Number(label="Year", value=TODAY.year, precision=0)
283
+
284
+ kpi_components = {} # kpi name -> (number input, badge HTML)
285
+ with gr.Row():
286
+ for col_idx in range(2):
287
+ with gr.Column():
288
+ for kpi in KPIS[col_idx::2]:
289
+ with gr.Group():
290
+ gr.Markdown(f"<div class='kpi-name'>{kpi['name']}</div>"
291
+ f"<div class='kpi-hint'>{kpi['hint']}</div>")
292
+ with gr.Row():
293
+ num = gr.Number(show_label=False, value=None, scale=1)
294
+ badge = gr.HTML("β€”", scale=1)
295
+ kpi_components[kpi["name"]] = (num, badge)
296
+
297
+ kpi_inputs = [kpi_components[kpi["name"]][0] for kpi in KPIS]
298
+ kpi_badges = [kpi_components[kpi["name"]][1] for kpi in KPIS]
299
+
300
+ total_display = gr.Markdown("### Total Score: β€”", elem_classes="total-score")
301
+ submit_btn = gr.Button("Submit", variant="primary")
302
+ submit_status = gr.Markdown()
303
+
304
+ for inp in kpi_inputs:
305
+ inp.change(_recompute, inputs=kpi_inputs, outputs=kpi_badges + [total_display])
306
+
307
+ submit_btn.click(
308
+ _on_submit,
309
+ inputs=[username_in, month_in, year_in] + kpi_inputs,
310
+ outputs=submit_status,
311
+ )
312
+
313
+ # ── My History ───────────────────────────────────────────────────
314
+ with gr.Tab("πŸ“ˆ My History"):
315
+ hist_refresh_btn = gr.Button("πŸ”„ Refresh")
316
+ with gr.Row():
317
+ hist_user = gr.Dropdown(choices=[], label="User Name")
318
+ hist_year = gr.Dropdown(choices=[], label="Year")
319
+ hist_table = gr.Dataframe(label="Monthly Scores")
320
+ hist_quarter_md = gr.Markdown()
321
+
322
+ hist_refresh_btn.click(_refresh_hist_users, outputs=hist_user).then(
323
+ _refresh_hist_years, inputs=hist_user, outputs=hist_year
324
+ ).then(_show_history, inputs=[hist_user, hist_year],
325
+ outputs=[hist_table, hist_quarter_md])
326
+ hist_user.change(_refresh_hist_years, inputs=hist_user, outputs=hist_year).then(
327
+ _show_history, inputs=[hist_user, hist_year], outputs=[hist_table, hist_quarter_md]
328
+ )
329
+ hist_year.change(_show_history, inputs=[hist_user, hist_year],
330
+ outputs=[hist_table, hist_quarter_md])
331
+
332
+ # ── Team Overview ────────────────────────────────────────────────
333
+ with gr.Tab("πŸ† Team Overview"):
334
+ with gr.Row():
335
+ team_month = gr.Dropdown(MONTHS, value=MONTHS[TODAY.month - 1], label="Month")
336
+ team_year = gr.Dropdown(choices=[], label="Year")
337
+ team_refresh_btn = gr.Button("πŸ”„ Refresh")
338
+ leaderboard_table = gr.Dataframe(label="Leaderboard")
339
+ download_btn = gr.DownloadButton("⬇️ Download full Excel export")
340
+
341
+ team_refresh_btn.click(_refresh_team_years, outputs=team_year).then(
342
+ _show_leaderboard, inputs=[team_month, team_year], outputs=leaderboard_table
343
+ )
344
+ team_month.change(_show_leaderboard, inputs=[team_month, team_year],
345
+ outputs=leaderboard_table)
346
+ team_year.change(_show_leaderboard, inputs=[team_month, team_year],
347
+ outputs=leaderboard_table)
348
+ download_btn.click(_export_excel, outputs=download_btn)
349
+
350
+ demo.load(_refresh_hist_users, outputs=hist_user).then(
351
+ _refresh_hist_years, inputs=hist_user, outputs=hist_year
352
+ ).then(_show_history, inputs=[hist_user, hist_year], outputs=[hist_table, hist_quarter_md])
353
+
354
+ demo.load(_refresh_team_years, outputs=team_year).then(
355
+ _show_leaderboard, inputs=[team_month, team_year], outputs=leaderboard_table
356
+ )
357
+
358
+ if __name__ == "__main__":
359
+ demo.launch(theme=theme, css=CUSTOM_CSS, favicon_path=LOGO_PATH)
assets/skoda_logo.png ADDED
excel_export.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the same formatted Excel workbook the desktop app produces, in-memory."""
2
+
3
+ import io
4
+ import openpyxl
5
+ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
6
+
7
+ from scoring import KPIS, MONTHS
8
+
9
+ MONTH_ORDER = {m: i for i, m in enumerate(MONTHS)}
10
+
11
+
12
+ def build_workbook(db) -> bytes:
13
+ wb = openpyxl.Workbook()
14
+ ws = wb.active
15
+ ws.title = "BDIT Scores"
16
+
17
+ hdr_fill = PatternFill("solid", fgColor="0F3460")
18
+ hdr_font = Font(bold=True, color="FFFFFF", size=10)
19
+ hdr_aln = Alignment(horizontal="center", vertical="center", wrap_text=True)
20
+ val_aln = Alignment(horizontal="center", vertical="center")
21
+ thin = Side(style="thin", color="2A3A5C")
22
+ border = Border(left=thin, right=thin, top=thin, bottom=thin)
23
+
24
+ slab_fill = {
25
+ 1.0: PatternFill("solid", fgColor="1B5E20"),
26
+ 0.8: PatternFill("solid", fgColor="7B5E00"),
27
+ 0.0: PatternFill("solid", fgColor="7B1A2C"),
28
+ }
29
+
30
+ headers = ["User Name", "Year", "Month"]
31
+ for kpi in KPIS:
32
+ n = kpi["name"]
33
+ headers += [f"{n}\nValue", f"{n}\nSlab", f"{n}\nScore"]
34
+ headers.append("Total\nScore")
35
+ ws.append(headers)
36
+
37
+ for cell in ws[1]:
38
+ cell.font = hdr_font
39
+ cell.fill = hdr_fill
40
+ cell.alignment = hdr_aln
41
+ cell.border = border
42
+ ws.row_dimensions[1].height = 42
43
+
44
+ for user in sorted(db):
45
+ for year in sorted(db[user]):
46
+ month_data = db[user][year]
47
+ for month in sorted(month_data, key=lambda m: MONTH_ORDER.get(m, 99)):
48
+ kpis = month_data[month]
49
+ row = [user, int(year), month]
50
+ total = 0
51
+ pcts = []
52
+ for kpi in KPIS:
53
+ d = kpis.get(kpi["name"], {})
54
+ row += [d.get("value", ""), d.get("label", ""), d.get("score", "")]
55
+ total += d.get("score", 0) or 0
56
+ pcts.append(d.get("pct", None))
57
+ row.append(total)
58
+ ws.append(row)
59
+
60
+ r = ws.max_row
61
+ for col_i, pct in enumerate(pcts):
62
+ if pct is not None and pct in slab_fill:
63
+ score_col = 4 + col_i * 3
64
+ ws.cell(r, score_col).fill = slab_fill[pct]
65
+ for cell in ws[r]:
66
+ cell.alignment = val_aln
67
+ cell.border = border
68
+
69
+ ws.column_dimensions["A"].width = 18
70
+ ws.column_dimensions["B"].width = 6
71
+ ws.column_dimensions["C"].width = 11
72
+ col_letters = [chr(c) for c in range(ord("D"), ord("D") + len(KPIS) * 3 + 1)]
73
+ for i, ltr in enumerate(col_letters):
74
+ ws.column_dimensions[ltr].width = 8 if (i % 3 == 2) else 10
75
+ last = openpyxl.utils.get_column_letter(4 + len(KPIS) * 3)
76
+ ws.column_dimensions[last].width = 8
77
+ ws.freeze_panes = "A2"
78
+
79
+ buf = io.BytesIO()
80
+ wb.save(buf)
81
+ return buf.getvalue()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ spaces>=0.30.0
3
+ gspread>=6.0.0
4
+ google-auth>=2.29.0
5
+ openpyxl>=3.0.0
6
+ pandas>=2.0.0
7
+ python-dotenv>=1.0.0
scoring.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared KPI/scoring rules β€” ported from sales_score_calculator.py (no Tkinter)."""
2
+
3
+ ACCENT = "#1b8a3a" # Slab 1 β€” green
4
+ GOLD = "#b8860b" # Slab 2 β€” amber
5
+ RED = "#c0392b" # Slab 3 β€” red
6
+ SLAB_COLOR = {1.0: ACCENT, 0.8: GOLD, 0.0: RED}
7
+ SLAB_LBL = {1.0: "Slab 1 β€” 100%", 0.8: "Slab 2 β€” 80%", 0.0: "Slab 3 β€” 0%"}
8
+
9
+ KPIS = [
10
+ {"name": "Sales Certified Manpower", "weight": 100, "unit": "%",
11
+ "hint": "β‰₯80% full Β· 55–79% partial Β· <55% none",
12
+ "slabs": [(1.0, lambda v: v >= 80, "β‰₯ 80%"),
13
+ (0.8, lambda v: 55 <= v <= 79, "55% – 79%"),
14
+ (0.0, lambda v: v < 55, "< 55%")]},
15
+
16
+ {"name": "Central Web-In Lead to Retail Ratio", "weight": 100, "unit": "%",
17
+ "hint": "β‰₯2.25% full Β· 1.40–2.24% partial Β· <1.40% none",
18
+ "slabs": [(1.0, lambda v: v >= 2.25, "β‰₯ 2.25%"),
19
+ (0.8, lambda v: 1.40 <= v < 2.25, "1.40% – 2.24%"),
20
+ (0.0, lambda v: v < 1.40, "< 1.40%")]},
21
+
22
+ {"name": "Mystery Shopping", "weight": 50, "unit": "%",
23
+ "hint": "β‰₯80% full Β· 60–79% partial Β· <60% none",
24
+ "slabs": [(1.0, lambda v: v >= 80, "β‰₯ 80%"),
25
+ (0.8, lambda v: 60 <= v < 80, "60% – 79%"),
26
+ (0.0, lambda v: v < 60, "< 60%")]},
27
+
28
+ {"name": "Escalation Index Sales", "weight": 50, "unit": "",
29
+ "hint": "≀0.20 full Β· 0.21–0.94 partial Β· >0.94 none",
30
+ "slabs": [(1.0, lambda v: v <= 0.20, "≀ 0.20"),
31
+ (0.8, lambda v: 0.21 <= v <= 0.94, "0.21 – 0.94"),
32
+ (0.0, lambda v: v > 0.94, "> 0.94")]},
33
+
34
+ {"name": "PSI Sales", "weight": 100, "unit": "",
35
+ "hint": "β‰₯4.85 full Β· 4.60–4.84 partial Β· <4.60 none",
36
+ "slabs": [(1.0, lambda v: v >= 4.85, "β‰₯ 4.85"),
37
+ (0.8, lambda v: 4.60 <= v < 4.85, "4.60 – 4.84"),
38
+ (0.0, lambda v: v < 4.60, "< 4.60")]},
39
+
40
+ {"name": "CX Sales", "weight": 100, "unit": "",
41
+ "hint": "β‰₯4.85 full Β· 4.60–4.84 partial Β· <4.60 none",
42
+ "slabs": [(1.0, lambda v: v >= 4.85, "β‰₯ 4.85"),
43
+ (0.8, lambda v: 4.60 <= v < 4.85, "4.60 – 4.84"),
44
+ (0.0, lambda v: v < 4.60, "< 4.60")]},
45
+ ]
46
+
47
+ TOTAL_WT = sum(k["weight"] for k in KPIS) # 500
48
+
49
+ MONTHS = ["January", "February", "March", "April", "May", "June",
50
+ "July", "August", "September", "October", "November", "December"]
51
+
52
+ # Q2 business rule: April excluded β€” only May & Jun count toward Q2 average
53
+ QUARTERS = {
54
+ "Q1": {"months": ["January", "February", "March"],
55
+ "counted": ["January", "February", "March"],
56
+ "label": "Q1 Average (Jan – Mar)"},
57
+ "Q2": {"months": ["April", "May", "June"],
58
+ "counted": ["May", "June"],
59
+ "label": "Q2 Average (May – Jun)"},
60
+ "Q3": {"months": ["July", "August", "September"],
61
+ "counted": ["July", "August", "September"],
62
+ "label": "Q3 Average (Jul – Sep)"},
63
+ "Q4": {"months": ["October", "November", "December"],
64
+ "counted": ["October", "November", "December"],
65
+ "label": "Q4 Average (Oct – Dec)"},
66
+ }
67
+
68
+
69
+ def get_quarter(month):
70
+ for qk, qv in QUARTERS.items():
71
+ if month in qv["months"]:
72
+ return qk, qv
73
+ return None, None
74
+
75
+
76
+ def compute_slab(kpi, value):
77
+ for pct, cond, lbl in kpi["slabs"]:
78
+ if cond(value):
79
+ return pct, SLAB_LBL[pct], int(round(pct * kpi["weight"]))
80
+ return 0.0, SLAB_LBL[0.0], 0
storage.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Storage for shared BDIT scores.
2
+
3
+ Normally backed by a Google Sheet (shared across the whole team). Needs two
4
+ credentials, read from environment variables (works both locally via a
5
+ .env file, loaded with python-dotenv, and on Hugging Face Spaces, where
6
+ Space secrets are injected as plain env vars regardless of SDK):
7
+
8
+ - SHEET_URL the Google Sheet URL, shared with the service
9
+ account's email as an Editor
10
+ - GCP_SERVICE_ACCOUNT_JSON the ENTIRE downloaded service-account JSON key
11
+ file, as one string
12
+
13
+ If neither is configured (e.g. local preview before Google Cloud setup is
14
+ done), falls back to a local JSON file β€” same persistence model as the
15
+ original desktop app β€” so the app is still fully click-through-able.
16
+ """
17
+
18
+ import json
19
+ import os
20
+ import time
21
+
22
+ from dotenv import load_dotenv
23
+
24
+ from scoring import KPIS, MONTHS
25
+
26
+ load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
27
+
28
+ SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
29
+ SHEET_TAB = "BDIT Scores"
30
+ _CACHE_TTL_SECONDS = 20
31
+
32
+ HEADER = ["User Name", "Year", "Month"]
33
+ for _kpi in KPIS:
34
+ HEADER += [f"{_kpi['name']} Value", f"{_kpi['name']} Slab", f"{_kpi['name']} Score"]
35
+ HEADER.append("Total Score")
36
+
37
+ MONTH_ORDER = {m: i for i, m in enumerate(MONTHS)}
38
+
39
+ _LOCAL_DATA_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
40
+ ".local_data", "skoda_scores.json")
41
+
42
+
43
+ def _get_sheet_url():
44
+ return os.environ.get("SHEET_URL") or os.environ.get("sheet_url")
45
+
46
+
47
+ def _get_service_account_info():
48
+ raw = os.environ.get("GCP_SERVICE_ACCOUNT_JSON") or os.environ.get("gcp_service_account_json")
49
+ if not raw:
50
+ return None
51
+ try:
52
+ return json.loads(raw)
53
+ except json.JSONDecodeError:
54
+ return None
55
+
56
+
57
+ def _using_google_sheets():
58
+ return _get_sheet_url() is not None and _get_service_account_info() is not None
59
+
60
+
61
+ def load_db():
62
+ """Return {user: {year: {month: {kpi_name: {value, pct, label, score}}}}}."""
63
+ if _using_google_sheets():
64
+ return _load_db_sheets()
65
+ return _load_db_local()
66
+
67
+
68
+ def save_entry(username, year, month, scores):
69
+ """Upsert one (user, year, month) entry."""
70
+ if _using_google_sheets():
71
+ _save_entry_sheets(username, year, month, scores)
72
+ else:
73
+ _save_entry_local(username, year, month, scores)
74
+
75
+
76
+ # ── Local JSON fallback (preview / no Google Cloud setup yet) ────────────────
77
+
78
+ def _load_db_local():
79
+ if os.path.exists(_LOCAL_DATA_FILE):
80
+ try:
81
+ with open(_LOCAL_DATA_FILE) as f:
82
+ return json.load(f)
83
+ except Exception:
84
+ return {}
85
+ return {}
86
+
87
+
88
+ def _save_entry_local(username, year, month, scores):
89
+ db = _load_db_local()
90
+ db.setdefault(username, {}).setdefault(str(year), {})[month] = scores
91
+ os.makedirs(os.path.dirname(_LOCAL_DATA_FILE), exist_ok=True)
92
+ with open(_LOCAL_DATA_FILE, "w") as f:
93
+ json.dump(db, f, indent=2)
94
+
95
+
96
+ # ── Google Sheets backend (shared, production) ────────────────────────────────
97
+ # Gradio has no built-in resource/data caching like Streamlit, so it's done
98
+ # by hand here: the worksheet handle is resolved once per process, and
99
+ # load_db() results are cached for a short TTL. Without this, every page
100
+ # interaction would re-spend several Sheets API reads and can blow through
101
+ # Google's free read-quota (60 reads/minute) almost immediately.
102
+
103
+ _client_cache = None
104
+ _worksheet_cache = None
105
+ _load_cache = {"data": None, "ts": 0.0}
106
+
107
+
108
+ def _client():
109
+ global _client_cache
110
+ if _client_cache is None:
111
+ import gspread
112
+ from google.oauth2.service_account import Credentials
113
+
114
+ creds = Credentials.from_service_account_info(
115
+ _get_service_account_info(), scopes=SCOPES
116
+ )
117
+ _client_cache = gspread.authorize(creds)
118
+ return _client_cache
119
+
120
+
121
+ def _worksheet():
122
+ global _worksheet_cache
123
+ if _worksheet_cache is not None:
124
+ return _worksheet_cache
125
+
126
+ import gspread
127
+
128
+ sh = _client().open_by_url(_get_sheet_url())
129
+ try:
130
+ ws = sh.worksheet(SHEET_TAB)
131
+ except gspread.WorksheetNotFound:
132
+ ws = sh.add_worksheet(title=SHEET_TAB, rows=1000, cols=len(HEADER))
133
+ ws.append_row(HEADER)
134
+ _worksheet_cache = ws
135
+ return ws
136
+ if ws.row_values(1) != HEADER:
137
+ ws.update("A1", [HEADER])
138
+ _worksheet_cache = ws
139
+ return ws
140
+
141
+
142
+ def _invalidate_cache():
143
+ _load_cache["data"] = None
144
+ _load_cache["ts"] = 0.0
145
+
146
+
147
+ def _load_db_sheets():
148
+ now = time.time()
149
+ if _load_cache["data"] is not None and (now - _load_cache["ts"]) < _CACHE_TTL_SECONDS:
150
+ return _load_cache["data"]
151
+
152
+ rows = _worksheet().get_all_records()
153
+ db = {}
154
+ for row in rows:
155
+ user = str(row.get("User Name", "")).strip()
156
+ year = str(row.get("Year", "")).strip()
157
+ month = str(row.get("Month", "")).strip()
158
+ if not user or not year or not month:
159
+ continue
160
+ scores = {}
161
+ for kpi in KPIS:
162
+ n = kpi["name"]
163
+ scores[n] = {
164
+ "value": row.get(f"{n} Value", ""),
165
+ "label": row.get(f"{n} Slab", ""),
166
+ "score": row.get(f"{n} Score", 0) or 0,
167
+ "pct": _pct_from_label(row.get(f"{n} Slab", "")),
168
+ }
169
+ db.setdefault(user, {}).setdefault(year, {})[month] = scores
170
+
171
+ _load_cache["data"] = db
172
+ _load_cache["ts"] = now
173
+ return db
174
+
175
+
176
+ def _pct_from_label(label):
177
+ if label == "Slab 1 β€” 100%":
178
+ return 1.0
179
+ if label == "Slab 2 β€” 80%":
180
+ return 0.8
181
+ return 0.0
182
+
183
+
184
+ def _save_entry_sheets(username, year, month, scores):
185
+ ws = _worksheet()
186
+ all_values = ws.get_all_values()
187
+
188
+ row_data = [username, str(year), month]
189
+ total = 0
190
+ for kpi in KPIS:
191
+ d = scores[kpi["name"]]
192
+ row_data += [d["value"], d["label"], d["score"]]
193
+ total += d["score"]
194
+ row_data.append(total)
195
+
196
+ target_row = None
197
+ for i, r in enumerate(all_values[1:], start=2):
198
+ if len(r) >= 3 and r[0] == username and r[1] == str(year) and r[2] == month:
199
+ target_row = i
200
+ break
201
+
202
+ if target_row:
203
+ ws.update(f"A{target_row}", [row_data])
204
+ else:
205
+ ws.append_row(row_data)
206
+
207
+ _invalidate_cache()