rishabh5752 commited on
Commit
0481dfa
Β·
verified Β·
1 Parent(s): ee78979

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -70
app.py CHANGED
@@ -1,15 +1,26 @@
1
  """
2
- Governance-GPT Quiz – AI-Maturity Self-Assessment (bucket version)
3
  Author: Rishabh Sharma – 2025-09-14
4
- Single-file Gradio Space: 15-question Likert survey ➜ bucket scores ➜ PDF+summary
5
  """
6
 
7
- import os, tempfile, datetime
8
  import gradio as gr
9
  import pandas as pd
10
- from fpdf import FPDF # pure-python PDF – no external binaries
11
-
12
- # ------------------- Question bank ------------------- #
 
 
 
 
 
 
 
 
 
 
 
13
  QUESTIONS = [
14
  "Governance framework is documented and communicated across the organisation.",
15
  "Roles & responsibilities for AI oversight are clearly assigned.",
@@ -32,7 +43,6 @@ QUESTIONS = [
32
  "Model cards or equivalent documentation exist for each deployed model.",
33
  ]
34
 
35
- # Five buckets, 3 questions each (index positions are 0-based)
36
  BUCKETS = {
37
  "Governance & Strategy": [0, 1, 2],
38
  "Data & Privacy": [3, 4, 5],
@@ -49,25 +59,7 @@ TIERS = {
49
  "Optimized": (4.51, 5.00),
50
  }
51
 
52
- # Generic tier actions (overall)
53
- OVERALL_ACTION = {
54
- "Initial": "kick-off a cross-functional task-force and establish a basic AI policy.",
55
- "Repeatable": "formalise core processes and create mandatory model documentation.",
56
- "Defined": "scale governance with automated monitoring and periodic audits.",
57
- "Managed": "integrate governance KPIs into OKRs and adopt continuous compliance tooling.",
58
- "Optimized": "benchmark externally, publish transparency reports, and champion open governance.",
59
- }
60
-
61
- # Bucket-specific remediation snippets
62
- BUCKET_ACTION = {
63
- "Governance & Strategy": "formalise decision rights and publish an organisation-wide AI charter.",
64
- "Data & Privacy": "implement end-to-end data lineage and privacy impact assessments.",
65
- "Risk & Compliance": "create incident playbooks and third-party risk registers.",
66
- "Security & Infrastructure": "harden model artefact storage and secure inference endpoints.",
67
- "Lifecycle & Oversight": "define human-override mechanisms and retirement criteria for models.",
68
- }
69
-
70
- # ------------------- Helpers ------------------- #
71
  def score_to_tier(avg: float) -> str:
72
  for tier, (low, high) in TIERS.items():
73
  if low <= avg <= high:
@@ -75,120 +67,111 @@ def score_to_tier(avg: float) -> str:
75
  return "Unclassified"
76
 
77
  def latin1(txt: str) -> str:
78
- """Convert to Latin-1 safe string for FPDF."""
79
  return txt.replace("…", "...").encode("latin-1", "replace").decode("latin-1")
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  def build_pdf(product: str, bucket_df: pd.DataFrame, overall_avg: float,
82
  overall_tier: str, file_path: str, summary_text: str):
83
  pdf = FPDF()
84
  pdf.set_auto_page_break(auto=True, margin=15)
85
  pdf.add_page()
86
 
87
- # Title
88
  pdf.set_font("Helvetica", "B", 16)
89
  pdf.cell(0, 10, latin1(f"AI Governance Maturity Report – {product}"), ln=1, align="C")
90
  pdf.set_font("Helvetica", "", 12)
91
  pdf.cell(0, 8, f"Generated on {datetime.date.today().isoformat()}", ln=1, align="C")
92
  pdf.ln(4)
93
 
94
- # Summary
95
  pdf.set_font("Helvetica", "B", 12)
96
  pdf.cell(0, 8, latin1(f"Overall Score: {overall_avg:.2f} | Tier: {overall_tier}"), ln=1)
97
  pdf.set_font("Helvetica", "", 11)
98
  pdf.multi_cell(0, 6, latin1(summary_text))
99
  pdf.ln(4)
100
 
101
- # Bucket table header
102
  pdf.set_font("Helvetica", "B", 11)
103
  pdf.cell(80, 8, "Bucket", 1)
104
  pdf.cell(35, 8, "Avg Score", 1)
105
  pdf.cell(35, 8, "Tier", 1, ln=1)
106
  pdf.set_font("Helvetica", "", 10)
107
 
108
- # Rows
109
  for _, row in bucket_df.iterrows():
110
  pdf.cell(80, 8, latin1(row["Bucket"][:40]), 1)
111
  pdf.cell(35, 8, f'{row["Avg Score"]:.2f}', 1)
112
  pdf.cell(35, 8, row["Tier"], 1, ln=1)
113
 
114
- # Overall row
115
  pdf.cell(80, 8, "Overall", 1)
116
  pdf.cell(35, 8, f"{overall_avg:.2f}", 1)
117
  pdf.cell(35, 8, overall_tier, 1, ln=1)
118
 
119
  pdf.output(file_path)
120
 
121
- def generate_summary(product: str, bucket_avgs: dict, overall_tier: str) -> str:
122
- """Return markdown remediation summary."""
123
- lines = [f"### 🏷️ AI Governance Summary for **{product}**",
124
- f"- **Overall tier:** {overall_tier}"]
125
-
126
- # Bucket-specific feedback
127
- for bucket, avg in bucket_avgs.items():
128
- tier = score_to_tier(avg)
129
- # Only add remediation if below Managed
130
- if tier in ("Initial", "Repeatable", "Defined"):
131
- lines.append(f"- **{bucket}** score is {avg:.2f} β†’ *{tier}*. "
132
- f"{product} should {BUCKET_ACTION[bucket]}")
133
- # If all buckets high, generic kudos
134
- if len(lines) == 2:
135
- lines.append("Great job! All buckets are Managed or Optimized.")
136
-
137
- # Overall action line
138
- lines.append(f"- Next step: {product} should {OVERALL_ACTION[overall_tier]}")
139
- return " \n".join(lines)
140
-
141
- # ------------------- Gradio callback ------------------- #
142
  def generate_report(product_name, *scores):
143
  product = product_name.strip() or "your product"
144
  scores = list(scores)
145
 
146
- # Compute bucket averages
147
- bucket_avgs = {}
148
- for bucket, idxs in BUCKETS.items():
149
- bucket_avgs[bucket] = sum(scores[i] for i in idxs) / len(idxs)
150
-
151
  overall_avg = sum(scores) / len(scores)
152
  overall_tier = score_to_tier(overall_avg)
153
 
154
- # Prepare DF for PDF table
155
  bucket_df = pd.DataFrame({
156
  "Bucket": list(bucket_avgs.keys()),
157
  "Avg Score": list(bucket_avgs.values()),
158
  "Tier": [score_to_tier(v) for v in bucket_avgs.values()],
159
  })
160
 
161
- # Build remediation summary
162
- summary_md = generate_summary(product, bucket_avgs, overall_tier)
163
 
164
- # Generate PDF
165
  tmp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
166
  build_pdf(product, bucket_df, overall_avg, overall_tier, tmp_pdf.name, summary_md)
167
 
168
  return summary_md, tmp_pdf.name
169
 
170
- # ------------------- Gradio UI ------------------- #
171
  with gr.Blocks(title="Governance-GPT Quiz") as demo:
172
  gr.Markdown(
173
  """
174
  # Governance-GPT Quiz
175
  Enter your **product / system name**, rate each statement from **1 (Strongly Disagree)** to **5 (Strongly Agree)**,
176
- and get a bucket-wise governance score with a personalised remediation plan.
177
  """
178
  )
179
 
180
  product_inp = gr.Textbox(label="Product / System Name", placeholder="e.g. AcmeAI Recommendation Engine")
181
-
182
  sliders = [gr.Slider(1, 5, value=3, step=1, label=q) for q in QUESTIONS]
183
 
184
  btn = gr.Button("Generate PDF Report")
185
  summary_out = gr.Markdown()
186
  pdf_out = gr.File(label="⬇️ Download your PDF")
187
 
188
- btn.click(
189
- fn=generate_report,
190
- inputs=[product_inp] + sliders,
191
- outputs=[summary_out, pdf_out],
192
- )
193
 
194
  demo.launch()
 
1
  """
2
+ Governance-GPT Quiz – bucket version (LLM-powered summary)
3
  Author: Rishabh Sharma – 2025-09-14
4
+ Single-file Gradio Space: 15-question Likert survey β†’ bucket scores β†’ LLM summary + PDF
5
  """
6
 
7
+ import os, tempfile, datetime, warnings
8
  import gradio as gr
9
  import pandas as pd
10
+ from fpdf import FPDF # pure-python PDF
11
+ from transformers import pipeline # πŸ”Ή NEW: LLM summariser
12
+
13
+ # ───────────── Initialize LLM once ───────────── #
14
+ # Small, instruction-tuned model that runs comfortably on free CPU Spaces
15
+ warnings.filterwarnings("ignore", category=UserWarning) # tokenizer warnings
16
+ summariser = pipeline(
17
+ task="text2text-generation",
18
+ model="google/flan-t5-base",
19
+ tokenizer="google/flan-t5-base",
20
+ max_new_tokens=220,
21
+ )
22
+
23
+ # ───────────── Question bank ───────────── #
24
  QUESTIONS = [
25
  "Governance framework is documented and communicated across the organisation.",
26
  "Roles & responsibilities for AI oversight are clearly assigned.",
 
43
  "Model cards or equivalent documentation exist for each deployed model.",
44
  ]
45
 
 
46
  BUCKETS = {
47
  "Governance & Strategy": [0, 1, 2],
48
  "Data & Privacy": [3, 4, 5],
 
59
  "Optimized": (4.51, 5.00),
60
  }
61
 
62
+ # ───────────── Helpers ───────────── #
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  def score_to_tier(avg: float) -> str:
64
  for tier, (low, high) in TIERS.items():
65
  if low <= avg <= high:
 
67
  return "Unclassified"
68
 
69
  def latin1(txt: str) -> str:
 
70
  return txt.replace("…", "...").encode("latin-1", "replace").decode("latin-1")
71
 
72
+ def llm_remediation(product: str, bucket_avgs: dict, overall_tier: str) -> str:
73
+ """Call Flan-T5 to get a markdown summary with recommendations."""
74
+ # Craft a concise prompt to stay within max_new_tokens
75
+ bucket_lines = "\n".join(
76
+ f"- {b}: {v:.2f}" for b, v in bucket_avgs.items()
77
+ )
78
+ prompt = (
79
+ "You are an AI governance consultant.\n"
80
+ f"Product: {product}\n"
81
+ f"Overall tier: {overall_tier}\n"
82
+ "Bucket scores (1-5):\n"
83
+ f"{bucket_lines}\n\n"
84
+ "Write a short markdown summary (≀120 words) with:\n"
85
+ "β€’ A one-sentence overall assessment\n"
86
+ "β€’ 3-5 bullet remediation actions, prioritised, referencing bucket names.\n"
87
+ "Do not add any other sections."
88
+ )
89
+ try:
90
+ gen = summariser(prompt)[0]["generated_text"]
91
+ return gen.strip()
92
+ except Exception as e:
93
+ # Fallback in rare failure cases
94
+ return f"LLM summary unavailable – {e}"
95
+
96
  def build_pdf(product: str, bucket_df: pd.DataFrame, overall_avg: float,
97
  overall_tier: str, file_path: str, summary_text: str):
98
  pdf = FPDF()
99
  pdf.set_auto_page_break(auto=True, margin=15)
100
  pdf.add_page()
101
 
 
102
  pdf.set_font("Helvetica", "B", 16)
103
  pdf.cell(0, 10, latin1(f"AI Governance Maturity Report – {product}"), ln=1, align="C")
104
  pdf.set_font("Helvetica", "", 12)
105
  pdf.cell(0, 8, f"Generated on {datetime.date.today().isoformat()}", ln=1, align="C")
106
  pdf.ln(4)
107
 
 
108
  pdf.set_font("Helvetica", "B", 12)
109
  pdf.cell(0, 8, latin1(f"Overall Score: {overall_avg:.2f} | Tier: {overall_tier}"), ln=1)
110
  pdf.set_font("Helvetica", "", 11)
111
  pdf.multi_cell(0, 6, latin1(summary_text))
112
  pdf.ln(4)
113
 
 
114
  pdf.set_font("Helvetica", "B", 11)
115
  pdf.cell(80, 8, "Bucket", 1)
116
  pdf.cell(35, 8, "Avg Score", 1)
117
  pdf.cell(35, 8, "Tier", 1, ln=1)
118
  pdf.set_font("Helvetica", "", 10)
119
 
 
120
  for _, row in bucket_df.iterrows():
121
  pdf.cell(80, 8, latin1(row["Bucket"][:40]), 1)
122
  pdf.cell(35, 8, f'{row["Avg Score"]:.2f}', 1)
123
  pdf.cell(35, 8, row["Tier"], 1, ln=1)
124
 
 
125
  pdf.cell(80, 8, "Overall", 1)
126
  pdf.cell(35, 8, f"{overall_avg:.2f}", 1)
127
  pdf.cell(35, 8, overall_tier, 1, ln=1)
128
 
129
  pdf.output(file_path)
130
 
131
+ # ───────────── Gradio callback ───────────── #
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def generate_report(product_name, *scores):
133
  product = product_name.strip() or "your product"
134
  scores = list(scores)
135
 
136
+ bucket_avgs = {
137
+ bucket: sum(scores[i] for i in idxs) / len(idxs)
138
+ for bucket, idxs in BUCKETS.items()
139
+ }
 
140
  overall_avg = sum(scores) / len(scores)
141
  overall_tier = score_to_tier(overall_avg)
142
 
 
143
  bucket_df = pd.DataFrame({
144
  "Bucket": list(bucket_avgs.keys()),
145
  "Avg Score": list(bucket_avgs.values()),
146
  "Tier": [score_to_tier(v) for v in bucket_avgs.values()],
147
  })
148
 
149
+ summary_md = llm_remediation(product, bucket_avgs, overall_tier)
 
150
 
 
151
  tmp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
152
  build_pdf(product, bucket_df, overall_avg, overall_tier, tmp_pdf.name, summary_md)
153
 
154
  return summary_md, tmp_pdf.name
155
 
156
+ # ───────────── UI ───────────── #
157
  with gr.Blocks(title="Governance-GPT Quiz") as demo:
158
  gr.Markdown(
159
  """
160
  # Governance-GPT Quiz
161
  Enter your **product / system name**, rate each statement from **1 (Strongly Disagree)** to **5 (Strongly Agree)**,
162
+ and receive an LLM-generated remediation plan plus PDF bucket report.
163
  """
164
  )
165
 
166
  product_inp = gr.Textbox(label="Product / System Name", placeholder="e.g. AcmeAI Recommendation Engine")
 
167
  sliders = [gr.Slider(1, 5, value=3, step=1, label=q) for q in QUESTIONS]
168
 
169
  btn = gr.Button("Generate PDF Report")
170
  summary_out = gr.Markdown()
171
  pdf_out = gr.File(label="⬇️ Download your PDF")
172
 
173
+ btn.click(fn=generate_report,
174
+ inputs=[product_inp] + sliders,
175
+ outputs=[summary_out, pdf_out])
 
 
176
 
177
  demo.launch()