rishabh5752 commited on
Commit
73e5422
·
verified ·
1 Parent(s): 26f57b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -96
app.py CHANGED
@@ -1,101 +1,132 @@
1
- import io
2
- import tempfile
3
  import gradio as gr
4
- from transformers import pipeline
5
- from fpdf import FPDF
6
- import matplotlib.pyplot as plt
7
 
8
- # ---- 1. Model (text2text because FLAN-T5 is encoder-decoder) ----
9
- generator = pipeline("text2text-generation", model="google/flan-t5-small", device=-1)
10
-
11
- # ---- 2. Survey-driven report builder ----
12
- def generate_detailed_report(company_name, answers):
13
- # convert answers dict into prompt text
14
- survey_text = "\n".join([f"{k}: {v}" for k, v in answers.items()])
15
- prompt = f"Generate a compliance assessment for {company_name} based on:\n{survey_text}. Mention their responses and the general findings."
16
-
17
- # call model
18
- result = generator(prompt, max_new_tokens=300)
19
- report = result[0]["generated_text"]
20
-
21
- # ---- 3. Simple chart (scores just for demo) ----
22
- # map answers to numeric scores (Yes=1, No=0, Partially=0.5)
23
- label_map = {"Yes": 1, "No": 0, "Partially": 0.5}
24
- labels, values = [], []
25
- for k, v in answers.items():
26
- labels.append(k)
27
- values.append(label_map.get(v, 0.5))
28
-
29
- plt.figure(figsize=(6, 3))
30
- plt.barh(labels, values, color="skyblue")
31
- plt.xlim(0, 1)
32
- plt.tight_layout()
33
-
34
- # Save chart as temporary file
35
- tmp_chart_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
36
- plt.savefig(tmp_chart_file.name)
37
- plt.close()
38
-
39
- # ---- 4. Build PDF ----
40
- pdf = FPDF()
41
- pdf.add_page()
42
- pdf.set_font("Arial", "B", 16)
43
- pdf.cell(0, 10, f"{company_name} Compliance Report", ln=True, align="C")
44
- pdf.ln(10)
45
- pdf.set_font("Arial", "", 12)
46
- pdf.multi_cell(0, 8, report)
47
- pdf.image(tmp_chart_file.name, x=10, y=None, w=180)
48
-
49
- # Save PDF as temporary file for Gradio
50
- tmp_pdf_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
51
- pdf.output(tmp_pdf_file.name)
52
-
53
- return report, tmp_chart_file.name, tmp_pdf_file.name
54
-
55
- # ---- 5. Gradio UI ----
56
- with gr.Blocks() as demo:
57
- gr.Markdown("## 📝 Compliance Survey + Report Generator")
58
-
59
- company_name = gr.Textbox(label="Company / Project Name", placeholder="Acme Corp")
60
-
61
- # survey with a few quick yes/no/partial questions, now with labels
62
- survey = {
63
- "Data Encryption Implemented": gr.Radio(
64
- ["Yes", "No", "Partially"],
65
- label="Data Encryption Implemented",
66
- value="Yes"
67
- ),
68
- "Regular Security Audits": gr.Radio(
69
- ["Yes", "No", "Partially"],
70
- label="Regular Security Audits",
71
- value="No"
72
- ),
73
- "Privacy Policy Updated": gr.Radio(
74
- ["Yes", "No", "Partially"],
75
- label="Privacy Policy Updated",
76
- value="Partially"
77
- ),
78
- "Employee Training Conducted": gr.Radio(
79
- ["Yes", "No", "Partially"],
80
- label="Employee Training Conducted",
81
- value="Yes"
82
- ),
83
  }
84
-
85
- submit = gr.Button("Generate Compliance Report")
86
-
87
- report_out = gr.Textbox(label="Generated Report", lines=8)
88
- chart_out = gr.Image(label="Compliance Chart")
89
- pdf_out = gr.File(label="Download PDF")
90
-
91
- def collect_and_generate(cname, *vals):
92
- answers = {k: v for k, v in zip(survey.keys(), vals)}
93
- return generate_detailed_report(cname, answers)
94
-
95
- submit.click(
96
- collect_and_generate,
97
- inputs=[company_name] + list(survey.values()),
98
- outputs=[report_out, chart_out, pdf_out],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  )
100
 
101
- demo.launch()
 
 
 
 
1
  import gradio as gr
 
 
 
2
 
3
+ # -------------------------
4
+ # Questions Configuration
5
+ # -------------------------
6
+ survey_questions = [
7
+ {
8
+ "label": "Company/Project Name",
9
+ "type": "text",
10
+ "key": "company"
11
+ },
12
+ {
13
+ "label": "1. Is data encryption implemented?",
14
+ "type": "radio",
15
+ "choices": ["Yes", "No", "Partially"],
16
+ "key": "encryption"
17
+ },
18
+ {
19
+ "label": "2. Are regular security audits performed?",
20
+ "type": "radio",
21
+ "choices": ["Yes", "No", "Partially"],
22
+ "key": "audits"
23
+ },
24
+ {
25
+ "label": "3. Is your privacy policy up to date and accessible to users?",
26
+ "type": "radio",
27
+ "choices": ["Yes", "No", "Partially"],
28
+ "key": "privacy"
29
+ },
30
+ {
31
+ "label": "4. Have employees received data governance training?",
32
+ "type": "checkbox",
33
+ "choices": ["Technical Staff", "HR & Admin", "All Employees", "Not Conducted"],
34
+ "key": "training"
35
+ },
36
+ {
37
+ "label": "5. Rate your organization’s data access control maturity:",
38
+ "type": "slider",
39
+ "key": "access_control",
40
+ "min": 1,
41
+ "max": 5
42
+ },
43
+ {
44
+ "label": "6. Are third-party vendors assessed for data compliance?",
45
+ "type": "radio",
46
+ "choices": ["Yes", "No", "Sometimes"],
47
+ "key": "third_party"
48
+ },
49
+ {
50
+ "label": "7. Additional notes or context (optional):",
51
+ "type": "text_area",
52
+ "key": "comments"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
54
+ ]
55
+
56
+ # -------------------------
57
+ # Report Generator
58
+ # -------------------------
59
+ def generate_compliance_report(**responses):
60
+ company = responses.get("company", "[Unknown Company]")
61
+ report = f"# Compliance Report for {company}\n\n"
62
+
63
+ # Score calculation (simplified logic)
64
+ score_map = {"Yes": 1, "Partially": 0.5, "No": 0, "Sometimes": 0.5}
65
+ score = 0
66
+ score += score_map.get(responses.get("encryption"), 0.5)
67
+ score += score_map.get(responses.get("audits"), 0.5)
68
+ score += score_map.get(responses.get("privacy"), 0.5)
69
+ score += score_map.get(responses.get("third_party"), 0.5)
70
+ score += (int(responses.get("access_control", 3)) / 5)
71
+
72
+ training = responses.get("training", [])
73
+ if isinstance(training, list):
74
+ score += 1 if "All Employees" in training else 0.5 if training else 0
75
+
76
+ avg_score = score / 6 # weighted average
77
+
78
+ if avg_score >= 0.8:
79
+ rating = "Excellent"
80
+ elif avg_score >= 0.5:
81
+ rating = "Moderate"
82
+ else:
83
+ rating = "Critical Risk"
84
+
85
+ report += f"**Overall Compliance Rating:** {rating}\n\n"
86
+ report += "## Survey Summary\n"
87
+ for q in survey_questions:
88
+ key = q["key"]
89
+ label = q["label"]
90
+ answer = responses.get(key, "[No Response]")
91
+ if isinstance(answer, list):
92
+ answer = ", ".join(answer) if answer else "None"
93
+ report += f"- **{label}**: {answer}\n"
94
+
95
+ notes = responses.get("comments", "No additional comments.")
96
+ report += f"\n**Additional Notes:**\n{notes}\n\n"
97
+ report += "\n_This report was generated using AI-assisted compliance heuristics._"
98
+ return report
99
+
100
+ # -------------------------
101
+ # Gradio UI
102
+ # -------------------------
103
+ with gr.Blocks(title="AI Compliance Survey") as demo:
104
+ gr.Markdown("""
105
+ # 🛡️ AI-Driven Compliance & Governance Survey
106
+ Answer the following questions to receive an AI-generated personalized compliance assessment report.
107
+ """)
108
+
109
+ inputs = {}
110
+ for q in survey_questions:
111
+ if q["type"] == "text":
112
+ inputs[q["key"]] = gr.Textbox(label=q["label"])
113
+ elif q["type"] == "radio":
114
+ inputs[q["key"]] = gr.Radio(q["choices"], label=q["label"])
115
+ elif q["type"] == "checkbox":
116
+ inputs[q["key"]] = gr.CheckboxGroup(q["choices"], label=q["label"])
117
+ elif q["type"] == "slider":
118
+ inputs[q["key"]] = gr.Slider(minimum=q["min"], maximum=q["max"], step=1, label=q["label"])
119
+ elif q["type"] == "text_area":
120
+ inputs[q["key"]] = gr.Textbox(label=q["label"], lines=4)
121
+
122
+ submit_btn = gr.Button("Generate Report")
123
+ report_output = gr.Textbox(label="Compliance Report", lines=20, interactive=False)
124
+
125
+ submit_btn.click(
126
+ fn=lambda **kwargs: generate_compliance_report(**kwargs),
127
+ inputs=[el for el in inputs.values()],
128
+ outputs=report_output
129
  )
130
 
131
+ if __name__ == "__main__":
132
+ demo.launch()