rishabh5752 commited on
Commit
af0780a
Β·
verified Β·
1 Parent(s): 1dec41f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -34
app.py CHANGED
@@ -1,26 +1,29 @@
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-small",
19
  tokenizer="google/flan-t5-small",
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.",
@@ -59,7 +62,9 @@ TIERS = {
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,40 +72,48 @@ def score_to_tier(avg: float) -> str:
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)
@@ -128,11 +141,14 @@ def build_pdf(product: str, bucket_df: pd.DataFrame, overall_avg: float,
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()
@@ -153,13 +169,15 @@ def generate_report(product_name, *scores):
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
 
 
1
  """
2
+ Governance-GPT Quiz ─ LLM-powered bucket report
3
+ Author: Rishabh Sharma Β· 2025-09-14
4
+ One-file Gradio Space β†’ 15-Q Likert survey β†’ bucket scores β†’ FLAN-T5 summary β†’ PDF
5
  """
6
 
7
+ import datetime, tempfile, warnings
8
  import gradio as gr
9
  import pandas as pd
10
+ from fpdf import FPDF # pure-Python PDF (core Helvetica font)
11
+ from transformers import pipeline # Hugging Face inference
12
 
13
+ # ───────────────────────────────────────────────────────────
14
+ # 1. Load a lightweight model once (β‰ˆ 80 M params, CPU-friendly)
15
+ # ───────────────────────────────────────────────────────────
16
+ warnings.filterwarnings("ignore", category=UserWarning)
17
  summariser = pipeline(
18
  task="text2text-generation",
19
  model="google/flan-t5-small",
20
  tokenizer="google/flan-t5-small",
21
+ max_new_tokens=150,
22
  )
23
 
24
+ # ───────────────────────────────────────────────────────────
25
+ # 2. Question bank & buckets
26
+ # ───────────────────────────────────────────────────────────
27
  QUESTIONS = [
28
  "Governance framework is documented and communicated across the organisation.",
29
  "Roles & responsibilities for AI oversight are clearly assigned.",
 
62
  "Optimized": (4.51, 5.00),
63
  }
64
 
65
+ # ───────────────────────────────────────────────────────────
66
+ # 3. Helper functions
67
+ # ───────────────────────────────────────────────────────────
68
  def score_to_tier(avg: float) -> str:
69
  for tier, (low, high) in TIERS.items():
70
  if low <= avg <= high:
 
72
  return "Unclassified"
73
 
74
  def latin1(txt: str) -> str:
75
+ """Force text into Latin-1 for the core fonts used by FPDF."""
76
+ return txt.encode("latin-1", "replace").decode("latin-1")
77
 
78
  def llm_remediation(product: str, bucket_avgs: dict, overall_tier: str) -> str:
79
+ """
80
+ Ask FLAN-T5-small to write a short markdown summary.
81
+ Uses only ASCII bullets ('-') so the PDF core font can render them.
82
+ """
83
+ bucket_lines = "\n".join(f"- {b}: {v:.2f}" for b, v in bucket_avgs.items())
84
  prompt = (
85
  "You are an AI governance consultant.\n"
86
  f"Product: {product}\n"
87
  f"Overall tier: {overall_tier}\n"
88
  "Bucket scores (1-5):\n"
89
  f"{bucket_lines}\n\n"
90
+ "Write a concise markdown summary (≀120 words) with:\n"
91
+ "- One overall assessment sentence.\n"
92
+ "- 3-5 bullet remediation actions referencing bucket names.\n"
93
+ "Return only the summary."
94
  )
95
+
96
+ # Generate
97
+ raw = summariser(prompt)[0]["generated_text"].strip()
98
+
99
+ # Some T5 models echo a slice of the prompt. Remove if present.
100
+ if raw.startswith(prompt[:50]):
101
+ raw = raw[len(prompt):].strip()
102
+
103
+ # Replace any unicode bullets with ASCII "- "
104
+ summary = raw.replace("β€’", "- ")
105
+ return summary if summary else "Summary unavailable."
106
+
107
+ def build_pdf(product: str, bucket_df: pd.DataFrame,
108
+ overall_avg: float, overall_tier: str,
109
+ file_path: str, summary_text: str):
110
  pdf = FPDF()
111
  pdf.set_auto_page_break(auto=True, margin=15)
112
  pdf.add_page()
113
 
114
  pdf.set_font("Helvetica", "B", 16)
115
  pdf.cell(0, 10, latin1(f"AI Governance Maturity Report – {product}"), ln=1, align="C")
116
+
117
  pdf.set_font("Helvetica", "", 12)
118
  pdf.cell(0, 8, f"Generated on {datetime.date.today().isoformat()}", ln=1, align="C")
119
  pdf.ln(4)
 
141
 
142
  pdf.output(file_path)
143
 
144
+ # ───────────────────────────────────────────────────────────
145
+ # 4. Gradio callback
146
+ # ───────────────────────────────────────────────────────────
147
  def generate_report(product_name, *scores):
148
  product = product_name.strip() or "your product"
149
  scores = list(scores)
150
 
151
+ # Bucket averages
152
  bucket_avgs = {
153
  bucket: sum(scores[i] for i in idxs) / len(idxs)
154
  for bucket, idxs in BUCKETS.items()
 
169
 
170
  return summary_md, tmp_pdf.name
171
 
172
+ # ───────────────────────────────────────────────────────────
173
+ # 5. Gradio UI
174
+ # ───────────────────────────────────────────────────────────
175
  with gr.Blocks(title="Governance-GPT Quiz") as demo:
176
  gr.Markdown(
177
  """
178
  # Governance-GPT Quiz
179
  Enter your **product / system name**, rate each statement from **1 (Strongly Disagree)** to **5 (Strongly Agree)**,
180
+ and receive an LLM-generated remediation plan plus a PDF bucket report.
181
  """
182
  )
183