Wajahat698 commited on
Commit
29833ea
·
verified ·
1 Parent(s): 6887816

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -0
app.py CHANGED
@@ -74,6 +74,120 @@ df_builder_pivot_str = ""
74
 
75
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  def plot_model_results(results_df, average_value, title, model_type):
78
  """
79
  Plot model results with specific orders and colors for Trust and NPS models.
@@ -663,6 +777,7 @@ def analyze_excel_single(file_path):
663
  average_value_nps = results_df_nps["Importance_percent"].mean()
664
  img_nps = plot_model_results(
665
  results_df_nps,
 
666
  f"NPS Drivers: {file_name}",
667
  "NPS",
668
  )
@@ -1039,6 +1154,18 @@ def variable_outputs(file_inputs):
1039
  "<span style='font-size:20px; font-weight:bold;'>3) Trust and KPI Drivers</span>",
1040
  visible=True,
1041
  ),
 
 
 
 
 
 
 
 
 
 
 
 
1042
 
1043
  gr.Image(
1044
  value=img_trust,
 
74
 
75
 
76
 
77
+
78
+
79
+
80
+ def plot_model_results(results_df, average_value, title, model_type):
81
+ """
82
+ Plot model results with specific orders and colors for Trust and NPS models.
83
+ Args:
84
+ results_df (DataFrame): DataFrame containing predictor names and their importance.
85
+ average_value (float): Average importance value.
86
+ title (str): Title of the plot.
87
+ model_type (str): Type of model (either "Trust" or "NPS").
88
+ Returns:
89
+ Image: Image object containing the plot.
90
+ """
91
+
92
+ logger.info(
93
+ "Plotting model results for %s model with title '%s'.", model_type, title
94
+ )
95
+ try:
96
+ import math
97
+
98
+ # Color mapping
99
+ color_map = {
100
+ "Stability": "#375570",
101
+ "Development": "#E3B05B",
102
+ "Relationship": "#C63F48",
103
+ "Benefit": "#418387",
104
+ "Vision": "#DF8859",
105
+ "Competence": "#6D93AB",
106
+ "Trust": "#f5918a",
107
+ }
108
+
109
+ # Load Trust Core Image
110
+ image_path = "./images/image.png"
111
+ try:
112
+ trust_core_img = Image.open(image_path)
113
+ except FileNotFoundError:
114
+ raise FileNotFoundError(f"❌ Error: Trust Core image '{image_path}' not found!")
115
+
116
+ # 🟠 NORMAL BAR PLOT
117
+ # 🟢 BUBBLE PLOT for NPS (copied exactly from your plot_trust_driver_bubbles)
118
+ order = ["Trust", "Stability", "Development", "Relationship", "Benefit", "Vision", "Competence"]
119
+
120
+ results_df["Predictor"] = pd.Categorical(
121
+ results_df["Predictor"], categories=order, ordered=True
122
+ )
123
+ results_df.sort_values("Predictor", ascending=False, inplace=True)
124
+
125
+ # Extract values
126
+ values_dict = results_df.set_index("Predictor")["Importance_percent"].to_dict()
127
+ percentages = [values_dict.get(pred, 0) for pred in order]
128
+
129
+ # Bubble sizes
130
+ min_radius = 0.15
131
+ base_percentage = min(percentages) if min(percentages) > 0 else 1
132
+ bubble_radii = [min_radius * (p / base_percentage) ** 0.75 for p in percentages]
133
+
134
+ # Central core
135
+ central_radius = 0.8
136
+
137
+ # Bubble positions
138
+ default_positions = {
139
+ "Trust": (0.0, 1.3),
140
+ "Stability": (-1.05, 0.0),
141
+ "Development": (1.05, 0.0),
142
+ "Relationship": (-0.6, 0.85),
143
+ "Benefit": (0.6, -0.85),
144
+ "Vision": (0.6, 0.85),
145
+ "Competence": (-0.6, -0.85)
146
+ }
147
+
148
+ # Adjust bubble positions slightly to touch core
149
+ for i, predictor in enumerate(order):
150
+ x, y = default_positions[predictor]
151
+ r = bubble_radii[i]
152
+ distance = np.sqrt(x**2 + y**2)
153
+ scale_factor = (central_radius + r - 0.2) / distance
154
+ default_positions[predictor] = (x * scale_factor, y * scale_factor)
155
+
156
+ fig, ax = plt.subplots(figsize=(10, 10), dpi=300)
157
+ ax.set_xlim(-2, 2)
158
+ ax.set_ylim(-2, 2)
159
+ ax.set_aspect('equal')
160
+ ax.axis("off")
161
+
162
+ # Draw Trust Core
163
+ extent = [-central_radius, central_radius, -central_radius, central_radius]
164
+ ax.imshow(trust_core_img, extent=extent, alpha=1.0)
165
+
166
+ # Draw Bubbles
167
+ for i, predictor in enumerate(order):
168
+ x, y = default_positions[predictor]
169
+ r = bubble_radii[i]
170
+ color = color_map.get(predictor, "#cccccc")
171
+ circle = patches.Circle((x, y), r, facecolor=color, alpha=1.0, lw=1.5)
172
+ ax.add_patch(circle)
173
+ ax.text(x, y, f"{percentages[i]:.1f}%", fontsize=10, fontweight="bold", ha="center", va="center", color="white")
174
+
175
+ plt.title(title, fontsize=12)
176
+
177
+ # Save and return image
178
+ img_data = io.BytesIO()
179
+ plt.savefig(img_data, format="png", bbox_inches="tight", facecolor=fig.get_facecolor())
180
+ img_data.seek(0)
181
+ img = Image.open(img_data)
182
+ plt.close(fig)
183
+
184
+ return img
185
+
186
+ except Exception as e:
187
+ logger.error("Error plotting model results: %s", e)
188
+ raise
189
+
190
+
191
  def plot_model_results(results_df, average_value, title, model_type):
192
  """
193
  Plot model results with specific orders and colors for Trust and NPS models.
 
777
  average_value_nps = results_df_nps["Importance_percent"].mean()
778
  img_nps = plot_model_results(
779
  results_df_nps,
780
+ average_value_nps,
781
  f"NPS Drivers: {file_name}",
782
  "NPS",
783
  )
 
1154
  "<span style='font-size:20px; font-weight:bold;'>3) Trust and KPI Drivers</span>",
1155
  visible=True,
1156
  ),
1157
+ gr.Markdown(
1158
+ """
1159
+ <div style='font-size:16px;'>
1160
+ This analysis highlights which Trust Buckets® are most effective in improving NPS and building trust.
1161
+ <br><br>
1162
+ The baseline impact for each driver is <b>16.7%</b> (100% divided across 6 Trust Buckets®). Any percentage above this average indicates higher significance,
1163
+ meaning these Trust Buckets® require more attention. To maximise their potential, focus on “filling” them with the right attributes and tailored messaging.
1164
+ </div>
1165
+ """,
1166
+ visible=True,
1167
+ ),
1168
+
1169
 
1170
  gr.Image(
1171
  value=img_trust,