Benny-Tang commited on
Commit
8f066a6
Β·
verified Β·
1 Parent(s): 6042106

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +720 -4
app.py CHANGED
@@ -1,7 +1,723 @@
1
  import gradio as gr
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import numpy as np
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ from datetime import datetime, timedelta
6
+ import json
7
 
8
+ # ============================================================================
9
+ # PAK System Configuration and Constants
10
+ # ============================================================================
11
 
12
+ PAK_EFFICACY = 0.92 # 92% infestation reduction
13
+ CURRENT_IPM_EFFICACY = 0.70 # 70% average for Triple IPM
14
+ PAK_COST_PER_HA = 95 # S$ per hectare
15
+ CURRENT_IPM_COST_PER_HA = 150 # S$ per hectare
16
+ PAK_LABOR_HOURS_PER_HA = 8 # hours per hectare
17
+ CURRENT_IPM_LABOR_HOURS_PER_HA = 16 # hours per hectare
18
+ LABOR_COST_PER_HOUR = 5 # S$ per hour
19
+
20
+ BASELINE_INFESTATION_RATE = 0.41 # 41% baseline infestation
21
+ YIELD_PER_HA_BASELINE = 1200 # kg per hectare
22
+ COFFEE_PRICE_PER_KG = 2.50 # S$ per kg
23
+
24
+ # ============================================================================
25
+ # Core Calculation Functions
26
+ # ============================================================================
27
+
28
+ def calculate_infestation_rate(baseline_rate, efficacy):
29
+ """Calculate resulting infestation rate after treatment."""
30
+ return baseline_rate * (1 - efficacy)
31
+
32
+ def calculate_yield_impact(baseline_yield, infestation_reduction):
33
+ """
34
+ Calculate yield improvement based on infestation reduction.
35
+ Assumes 2% yield loss per 1% infestation rate.
36
+ """
37
+ yield_loss_per_infestation = 0.02
38
+ yield_improvement = baseline_yield * infestation_reduction * yield_loss_per_infestation
39
+ return baseline_yield + yield_improvement
40
+
41
+ def calculate_costs(farm_size_ha, use_pak=True):
42
+ """Calculate total costs for pest management."""
43
+ if use_pak:
44
+ material_cost = farm_size_ha * PAK_COST_PER_HA
45
+ labor_cost = farm_size_ha * PAK_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR
46
+ else:
47
+ material_cost = farm_size_ha * CURRENT_IPM_COST_PER_HA
48
+ labor_cost = farm_size_ha * CURRENT_IPM_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR
49
+
50
+ total_cost = material_cost + labor_cost
51
+ return {
52
+ 'material_cost': material_cost,
53
+ 'labor_cost': labor_cost,
54
+ 'total_cost': total_cost
55
+ }
56
+
57
+ def calculate_roi(farm_size_ha, years=1):
58
+ """Calculate Return on Investment for PAK System vs Current IPM."""
59
+
60
+ # Current IPM scenario
61
+ current_infestation = calculate_infestation_rate(BASELINE_INFESTATION_RATE, CURRENT_IPM_EFFICACY)
62
+ current_yield = calculate_yield_impact(YIELD_PER_HA_BASELINE,
63
+ CURRENT_IPM_EFFICACY * BASELINE_INFESTATION_RATE)
64
+ current_revenue = farm_size_ha * current_yield * COFFEE_PRICE_PER_KG
65
+ current_costs = calculate_costs(farm_size_ha, use_pak=False)['total_cost']
66
+ current_profit = current_revenue - current_costs
67
+
68
+ # PAK System scenario
69
+ pak_infestation = calculate_infestation_rate(BASELINE_INFESTATION_RATE, PAK_EFFICACY)
70
+ pak_yield = calculate_yield_impact(YIELD_PER_HA_BASELINE,
71
+ PAK_EFFICACY * BASELINE_INFESTATION_RATE)
72
+ pak_revenue = farm_size_ha * pak_yield * COFFEE_PRICE_PER_KG
73
+ pak_costs = calculate_costs(farm_size_ha, use_pak=True)['total_cost']
74
+ pak_profit = pak_revenue - pak_costs
75
+
76
+ # ROI Calculation
77
+ profit_improvement = pak_profit - current_profit
78
+ cost_savings = current_costs['total_cost'] - pak_costs['total_cost']
79
+ roi_percentage = (profit_improvement / current_costs['total_cost']) * 100
80
+
81
+ return {
82
+ 'current_infestation': current_infestation,
83
+ 'pak_infestation': pak_infestation,
84
+ 'current_yield': current_yield,
85
+ 'pak_yield': pak_yield,
86
+ 'current_revenue': current_revenue,
87
+ 'pak_revenue': pak_revenue,
88
+ 'current_costs': current_costs['total_cost'],
89
+ 'pak_costs': pak_costs['total_cost'],
90
+ 'current_profit': current_profit,
91
+ 'pak_profit': pak_profit,
92
+ 'profit_improvement': profit_improvement,
93
+ 'cost_savings': cost_savings,
94
+ 'roi_percentage': roi_percentage,
95
+ 'payback_period_months': (pak_costs['total_cost'] / (profit_improvement / 12)) if profit_improvement > 0 else float('inf')
96
+ }
97
+
98
+ def generate_comparison_chart(farm_size_ha):
99
+ """Generate comparison charts for PAK vs Current IPM."""
100
+ roi_data = calculate_roi(farm_size_ha)
101
+
102
+ fig, axes = plt.subplots(2, 2, figsize=(14, 10))
103
+ fig.suptitle(f'PAK System vs Current IPM - {farm_size_ha} hectares', fontsize=16, fontweight='bold')
104
+
105
+ # Infestation Rate Comparison
106
+ ax1 = axes[0, 0]
107
+ methods = ['Current IPM', 'PAK System']
108
+ infestation_rates = [roi_data['current_infestation'] * 100, roi_data['pak_infestation'] * 100]
109
+ colors = ['#C85A3C', '#7A9E3F']
110
+ bars1 = ax1.bar(methods, infestation_rates, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
111
+ ax1.set_ylabel('Infestation Rate (%)', fontweight='bold')
112
+ ax1.set_title('Infestation Rate Comparison', fontweight='bold')
113
+ ax1.set_ylim(0, 50)
114
+ for bar, rate in zip(bars1, infestation_rates):
115
+ height = bar.get_height()
116
+ ax1.text(bar.get_x() + bar.get_width()/2., height,
117
+ f'{rate:.1f}%', ha='center', va='bottom', fontweight='bold')
118
+
119
+ # Yield Comparison
120
+ ax2 = axes[0, 1]
121
+ yields = [roi_data['current_yield'], roi_data['pak_yield']]
122
+ bars2 = ax2.bar(methods, yields, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
123
+ ax2.set_ylabel('Yield (kg/ha)', fontweight='bold')
124
+ ax2.set_title('Yield Comparison', fontweight='bold')
125
+ ax2.set_ylim(0, max(yields) * 1.2)
126
+ for bar, yield_val in zip(bars2, yields):
127
+ height = bar.get_height()
128
+ ax2.text(bar.get_x() + bar.get_width()/2., height,
129
+ f'{yield_val:.0f}', ha='center', va='bottom', fontweight='bold')
130
+
131
+ # Cost Comparison
132
+ ax3 = axes[1, 0]
133
+ costs = [roi_data['current_costs'], roi_data['pak_costs']]
134
+ bars3 = ax3.bar(methods, costs, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
135
+ ax3.set_ylabel('Total Cost (S$)', fontweight='bold')
136
+ ax3.set_title('Annual Cost Comparison', fontweight='bold')
137
+ ax3.set_ylim(0, max(costs) * 1.2)
138
+ for bar, cost in zip(bars3, costs):
139
+ height = bar.get_height()
140
+ ax3.text(bar.get_x() + bar.get_width()/2., height,
141
+ f'S${cost:.0f}', ha='center', va='bottom', fontweight='bold')
142
+
143
+ # Profit Comparison
144
+ ax4 = axes[1, 1]
145
+ profits = [roi_data['current_profit'], roi_data['pak_profit']]
146
+ bars4 = ax4.bar(methods, profits, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
147
+ ax4.set_ylabel('Annual Profit (S$)', fontweight='bold')
148
+ ax4.set_title('Annual Profit Comparison', fontweight='bold')
149
+ ax4.set_ylim(0, max(profits) * 1.2)
150
+ for bar, profit in zip(bars4, profits):
151
+ height = bar.get_height()
152
+ ax4.text(bar.get_x() + bar.get_width()/2., height,
153
+ f'S${profit:.0f}', ha='center', va='bottom', fontweight='bold')
154
+
155
+ plt.tight_layout()
156
+ return fig
157
+
158
+ def generate_timeline_projection(farm_size_ha, years=5):
159
+ """Generate 5-year financial projection."""
160
+ years_range = np.arange(0, years + 1)
161
+ current_profits = []
162
+ pak_profits = []
163
+
164
+ for year in years_range:
165
+ roi = calculate_roi(farm_size_ha)
166
+ current_profits.append(roi['current_profit'] * year)
167
+ pak_profits.append(roi['pak_profit'] * year)
168
+
169
+ fig, ax = plt.subplots(figsize=(12, 6))
170
+ ax.plot(years_range, current_profits, marker='o', linewidth=2.5, markersize=8,
171
+ label='Current IPM', color='#C85A3C')
172
+ ax.plot(years_range, pak_profits, marker='s', linewidth=2.5, markersize=8,
173
+ label='PAK System', color='#7A9E3F')
174
+
175
+ ax.set_xlabel('Years', fontweight='bold', fontsize=12)
176
+ ax.set_ylabel('Cumulative Profit (S$)', fontweight='bold', fontsize=12)
177
+ ax.set_title(f'5-Year Financial Projection - {farm_size_ha} hectares', fontweight='bold', fontsize=14)
178
+ ax.legend(fontsize=11, loc='upper left')
179
+ ax.grid(True, alpha=0.3)
180
+
181
+ # Format y-axis as currency
182
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'S${x/1000:.0f}K'))
183
+
184
+ plt.tight_layout()
185
+ return fig
186
+
187
+ # ============================================================================
188
+ # Gradio Interface Functions
189
+ # ============================================================================
190
+
191
+ def analyze_farm(farm_size_ha, baseline_infestation=41):
192
+ """Main analysis function for farm-level ROI calculation."""
193
+
194
+ if farm_size_ha <= 0:
195
+ return "Error: Farm size must be greater than 0", None, None
196
+
197
+ roi_data = calculate_roi(farm_size_ha)
198
+
199
+ # Generate summary report
200
+ summary = f"""
201
+ ╔════════════════════════════════════════════════════════════════╗
202
+ β•‘ PAK SYSTEM ROI ANALYSIS - {farm_size_ha} HECTARES
203
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
204
+
205
+ INFESTATION CONTROL
206
+ ──────────────────────────────────────────────────────────────────
207
+ Current IPM Infestation Rate: {roi_data['current_infestation']*100:.1f}%
208
+ PAK System Infestation Rate: {roi_data['pak_infestation']*100:.1f}%
209
+ Improvement: {(roi_data['current_infestation'] - roi_data['pak_infestation'])*100:.1f}%
210
+
211
+ YIELD IMPACT
212
+ ─────────────────────────────────────────────────────────────────��
213
+ Current IPM Yield: {roi_data['current_yield']:.0f} kg/ha
214
+ PAK System Yield: {roi_data['pak_yield']:.0f} kg/ha
215
+ Additional Yield: {roi_data['pak_yield'] - roi_data['current_yield']:.0f} kg/ha
216
+
217
+ FINANCIAL ANALYSIS (Annual)
218
+ ──────────────────────────────────────────────────────────────────
219
+ Current IPM:
220
+ β€’ Total Cost: S${roi_data['current_costs']:,.0f}
221
+ β€’ Revenue: S${roi_data['current_revenue']:,.0f}
222
+ β€’ Profit: S${roi_data['current_profit']:,.0f}
223
+
224
+ PAK System:
225
+ β€’ Total Cost: S${roi_data['pak_costs']:,.0f}
226
+ β€’ Revenue: S${roi_data['pak_revenue']:,.0f}
227
+ β€’ Profit: S${roi_data['pak_profit']:,.0f}
228
+
229
+ RETURN ON INVESTMENT
230
+ ──────────────────────────────────────────────────────────────────
231
+ Annual Profit Improvement: S${roi_data['profit_improvement']:,.0f}
232
+ Annual Cost Savings: S${roi_data['cost_savings']:,.0f}
233
+ ROI Percentage: {roi_data['roi_percentage']:.1f}%
234
+ Payback Period: {roi_data['payback_period_months']:.1f} months
235
+
236
+ 5-YEAR PROJECTION
237
+ ──────────────────────────────────────────────────────────────────
238
+ Current IPM Total Profit (5 years): S${roi_data['current_profit']*5:,.0f}
239
+ PAK System Total Profit (5 years): S${roi_data['pak_profit']*5:,.0f}
240
+ Additional Profit (5 years): S${(roi_data['pak_profit'] - roi_data['current_profit'])*5:,.0f}
241
+ """
242
+
243
+ comparison_chart = generate_comparison_chart(farm_size_ha)
244
+ timeline_chart = generate_timeline_projection(farm_size_ha, years=5)
245
+
246
+ return summary, comparison_chart, timeline_chart
247
+
248
+ def network_analysis(total_farmers, avg_farm_size_ha):
249
+ """Analyze PAK System impact across farmer network."""
250
+
251
+ if total_farmers <= 0 or avg_farm_size_ha <= 0:
252
+ return "Error: Please enter valid values", None
253
+
254
+ total_hectares = total_farmers * avg_farm_size_ha
255
+ roi_data = calculate_roi(total_hectares)
256
+
257
+ summary = f"""
258
+ ╔════════════════════════════════════════════════════════════════╗
259
+ β•‘ NETWORK-LEVEL PAK SYSTEM IMPACT ANALYSIS
260
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
261
+
262
+ NETWORK SCALE
263
+ ──────────────────────────────────────────────────────────────────
264
+ Total Farmers: {total_farmers:,}
265
+ Average Farm Size: {avg_farm_size_ha} hectares
266
+ Total Network Area: {total_hectares:,} hectares
267
+
268
+ AGGREGATE ANNUAL IMPACT
269
+ ──────────────────────────────────────────────────────────────────
270
+ Total Cost Savings: S${roi_data['cost_savings']:,.0f}
271
+ Total Profit Improvement: S${roi_data['profit_improvement']:,.0f}
272
+ Total Additional Yield: {(roi_data['pak_yield'] - roi_data['current_yield']) * total_hectares:,.0f} kg
273
+
274
+ PER-FARMER ANNUAL IMPACT
275
+ ──────────────────────────────────────────────────────────────────
276
+ Cost Savings per Farmer: S${roi_data['cost_savings']/total_farmers:,.0f}
277
+ Profit Improvement per Farmer: S${roi_data['profit_improvement']/total_farmers:,.0f}
278
+ Additional Income per Farmer: S${(roi_data['profit_improvement']/total_farmers):,.0f}
279
+
280
+ SUSTAINABILITY METRICS
281
+ ──────────────────────────────────────────────────────────────────
282
+ Synthetic Pesticide Elimination: 100%
283
+ Labor Reduction: 50%+
284
+ Organic Certification Compliance: 100%
285
+ Biodiversity Impact: Positive (no harm to beneficial insects)
286
+
287
+ 5-YEAR NETWORK PROJECTION
288
+ ──────────────────────────────────────────────────────────────────
289
+ Total Additional Income (5 years): S${(roi_data['profit_improvement'] - roi_data['cost_savings'])*5:,.0f}
290
+ Cumulative Farmers Benefited: {total_farmers:,}
291
+ Estimated Yield Increase (5 years): {(roi_data['pak_yield'] - roi_data['current_yield']) * total_hectares * 5:,.0f} kg
292
+ """
293
+
294
+ # Create network visualization
295
+ fig, axes = plt.subplots(1, 2, figsize=(14, 6))
296
+ fig.suptitle(f'Network Impact: {total_farmers:,} Farmers, {total_hectares:,} hectares',
297
+ fontsize=14, fontweight='bold')
298
+
299
+ # Cost savings breakdown
300
+ ax1 = axes[0]
301
+ categories = ['Material\nCosts', 'Labor\nCosts']
302
+ current_material = (total_hectares * CURRENT_IPM_COST_PER_HA)
303
+ current_labor = (total_hectares * CURRENT_IPM_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR)
304
+ pak_material = (total_hectares * PAK_COST_PER_HA)
305
+ pak_labor = (total_hectares * PAK_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR)
306
+
307
+ x = np.arange(len(categories))
308
+ width = 0.35
309
+
310
+ bars1 = ax1.bar(x - width/2, [current_material, current_labor], width,
311
+ label='Current IPM', color='#C85A3C', alpha=0.8, edgecolor='black')
312
+ bars2 = ax1.bar(x + width/2, [pak_material, pak_labor], width,
313
+ label='PAK System', color='#7A9E3F', alpha=0.8, edgecolor='black')
314
+
315
+ ax1.set_ylabel('Annual Cost (S$)', fontweight='bold')
316
+ ax1.set_title('Cost Breakdown Comparison', fontweight='bold')
317
+ ax1.set_xticks(x)
318
+ ax1.set_xticklabels(categories)
319
+ ax1.legend()
320
+ ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'S${x/1000:.0f}K'))
321
+
322
+ # Profit distribution
323
+ ax2 = axes[1]
324
+ profit_data = [roi_data['current_profit'], roi_data['pak_profit']]
325
+ colors = ['#C85A3C', '#7A9E3F']
326
+ bars = ax2.bar(['Current IPM', 'PAK System'], profit_data, color=colors, alpha=0.8, edgecolor='black')
327
+ ax2.set_ylabel('Annual Profit (S$)', fontweight='bold')
328
+ ax2.set_title('Network Annual Profit', fontweight='bold')
329
+ ax2.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'S${x/1000:.0f}K'))
330
+
331
+ for bar, profit in zip(bars, profit_data):
332
+ height = bar.get_height()
333
+ ax2.text(bar.get_x() + bar.get_width()/2., height,
334
+ f'S${profit/1000:.0f}K', ha='center', va='bottom', fontweight='bold')
335
+
336
+ plt.tight_layout()
337
+
338
+ return summary, fig
339
+
340
+ def generate_detailed_report(farm_size_ha, years=5):
341
+ """Generate comprehensive PDF-ready report."""
342
+
343
+ roi_data = calculate_roi(farm_size_ha)
344
+
345
+ report = f"""
346
+ ════════════════════════════════════════════════════════════════════════════════
347
+ PRECISION ATTRACT-AND-KILL (PAK) SYSTEM
348
+ DETAILED FEASIBILITY REPORT
349
+ ════════════════════════════════════════════════════════════════════════════════
350
+
351
+ EXECUTIVE SUMMARY
352
+ ────────────────────────────────────────────────────────────────────────────────
353
+
354
+ The Precision Attract-and-Kill System represents a transformative approach to
355
+ Coffee Berry Borer management. This report analyzes the technical, financial,
356
+ and operational feasibility of implementing the PAK System on a {farm_size_ha}-hectare
357
+ farm or network.
358
+
359
+ KEY FINDINGS:
360
+ β€’ Infestation Reduction: {roi_data['current_infestation']*100:.1f}% β†’ {roi_data['pak_infestation']*100:.1f}% ({(roi_data['current_infestation'] - roi_data['pak_infestation'])*100:.1f}% improvement)
361
+ β€’ Annual Cost Savings: S${roi_data['cost_savings']:,.0f}
362
+ β€’ Annual Profit Improvement: S${roi_data['profit_improvement']:,.0f}
363
+ β€’ ROI: {roi_data['roi_percentage']:.1f}%
364
+ β€’ Payback Period: {roi_data['payback_period_months']:.1f} months
365
+
366
+ ════════════════════════════════════════════════════════════════════════════════
367
+
368
+ TECHNICAL SPECIFICATIONS
369
+ ────────────────────────────────────────────────────────────────────────────────
370
+
371
+ Active Ingredients:
372
+ β€’ Semiochemical Lure: Optimized blend of CBB aggregation pheromone and host volatiles
373
+ β€’ Biological Agent: Beauveria bassiana (entomopathogenic fungus)
374
+ β€’ Formulation: Micro-encapsulated paste/gel for weather resistance
375
+
376
+ Application Methods:
377
+ β€’ Drone/UAV: Automated spot-spraying for estates and farmer clusters
378
+ β€’ Backpack Sprayer: Semi-automated application for individual smallholders
379
+ β€’ Application Frequency: 2-3 times per season during peak CBB activity
380
+
381
+ Safety & Compliance:
382
+ β€’ Organic Certification: Fully compliant (Rainforest Alliance, 4C, etc.)
383
+ β€’ Environmental Impact: No harm to pollinators or beneficial insects
384
+ β€’ Biodiversity: Supports regenerative agriculture practices
385
+
386
+ ════════════════════════════════════════════════════════════════════════════════
387
+
388
+ FINANCIAL ANALYSIS
389
+ ────────────────────────────────────────────────────────────────────────────────
390
+
391
+ YEAR 1 ANALYSIS ({farm_size_ha} hectares):
392
+
393
+ Current IPM Approach:
394
+ Material Costs: S${farm_size_ha * CURRENT_IPM_COST_PER_HA:,.0f}
395
+ Labor Costs: S${farm_size_ha * CURRENT_IPM_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR:,.0f}
396
+ Total Costs: S${roi_data['current_costs']:,.0f}
397
+ Gross Revenue: S${roi_data['current_revenue']:,.0f}
398
+ Net Profit: S${roi_data['current_profit']:,.0f}
399
+
400
+ PAK System Approach:
401
+ Material Costs: S${farm_size_ha * PAK_COST_PER_HA:,.0f}
402
+ Labor Costs: S${farm_size_ha * PAK_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR:,.0f}
403
+ Total Costs: S${roi_data['pak_costs']:,.0f}
404
+ Gross Revenue: S${roi_data['pak_revenue']:,.0f}
405
+ Net Profit: S${roi_data['pak_profit']:,.0f}
406
+
407
+ COMPARATIVE ADVANTAGE:
408
+ Cost Savings: S${roi_data['cost_savings']:,.0f} ({(roi_data['cost_savings']/roi_data['current_costs'])*100:.1f}%)
409
+ Revenue Increase: S${roi_data['pak_revenue'] - roi_data['current_revenue']:,.0f} ({((roi_data['pak_revenue'] - roi_data['current_revenue'])/roi_data['current_revenue'])*100:.1f}%)
410
+ Profit Improvement: S${roi_data['profit_improvement']:,.0f} ({(roi_data['profit_improvement']/roi_data['current_profit'])*100:.1f}%)
411
+
412
+ {years}-YEAR PROJECTION:
413
+ Current IPM Total Profit: S${roi_data['current_profit']*years:,.0f}
414
+ PAK System Total Profit: S${roi_data['pak_profit']*years:,.0f}
415
+ Additional Profit (5 years): S${(roi_data['pak_profit'] - roi_data['current_profit'])*years:,.0f}
416
+
417
+ ════════════════════════════════════════════════════════════════════════════════
418
+
419
+ IMPLEMENTATION ROADMAP
420
+ ────────────────────────────────────────────────────────────────────────────────
421
+
422
+ PHASE 1: PROOF OF CONCEPT (2026)
423
+ Timeline: 12 months
424
+ Investment: S$6,500 (for 5-10 hectares)
425
+ Deliverables:
426
+ β€’ Field trial validation in Vietnam
427
+ β€’ Efficacy data (target: 90%+ infestation reduction)
428
+ β€’ Cost-benefit analysis
429
+ β€’ Farmer feedback and adoption metrics
430
+
431
+ PHASE 2: EXPANSION & STANDARDIZATION (2027)
432
+ Timeline: 12 months
433
+ Investment: S$12,500-15,000 (for Indonesia & PNG)
434
+ Deliverables:
435
+ β€’ Formulation adaptation for regional conditions
436
+ β€’ Expanded field trials (50+ farmers)
437
+ β€’ Standardized protocols and training materials
438
+ β€’ Regional scale-up plan
439
+
440
+ PHASE 3: COMMERCIALIZATION (2028+)
441
+ Timeline: Ongoing
442
+ Model: IPM-as-a-Service
443
+ β€’ ECOM or partner provides formulation and application
444
+ β€’ Fixed post-harvest fee (S$5-10/bag)
445
+ β€’ Rapid adoption across farmer network
446
+
447
+ ════════════════════════════════════════════════════════════════════════════════
448
+
449
+ RISK ASSESSMENT & MITIGATION
450
+ ────────────────────────────────────────────────────────────────────────────────
451
+
452
+ Risk: Formulation efficacy below target
453
+ Probability: Medium | Impact: High
454
+ Mitigation: Preliminary lab testing; contingency budget for adjustments
455
+
456
+ Risk: Weather impact on field trials
457
+ Probability: Medium | Impact: Medium
458
+ Mitigation: Multiple demo plot locations; extended trial period if needed
459
+
460
+ Risk: Farmer adoption challenges
461
+ Probability: Medium | Impact: Medium
462
+ Mitigation: Early engagement; clear training; peer learning networks
463
+
464
+ Risk: Regulatory or certification issues
465
+ Probability: Low | Impact: High
466
+ Mitigation: Early engagement with certification bodies; full documentation
467
+
468
+ ════════════════════════════════════════════════════════════════════════════════
469
+
470
+ SUSTAINABILITY & LIVELIHOOD IMPACT
471
+ ────────────────────────────────────────────────────────────────────────────────
472
+
473
+ Environmental Benefits:
474
+ β€’ Elimination of synthetic pesticides
475
+ β€’ Support for soil health and biodiversity
476
+ β€’ Reduced carbon intensity of coffee production
477
+ β€’ Climate-smart agriculture alignment
478
+
479
+ Livelihood Benefits:
480
+ β€’ Reduced labor burden (50% reduction)
481
+ β€’ Improved income stability
482
+ β€’ Enhanced quality of life for farming communities
483
+ β€’ Scalable across ECOM's global network
484
+
485
+ ════════════════════════════════════════════════════════════════════════════════
486
+
487
+ CONCLUSION
488
+ ────────────────────────────────────────────────────────────────────────────────
489
+
490
+ The Precision Attract-and-Kill System represents a transformative opportunity
491
+ for ECOM to address the Coffee Berry Borer challenge with a single, nature-based,
492
+ and highly scalable solution. The financial analysis demonstrates clear ROI,
493
+ with payback periods under 12 months and substantial long-term profit improvements.
494
+
495
+ The modest Phase 1 investment of S$6,500 is justified by the potential impact
496
+ across ECOM's network of 6,000+ smallholder farmers, with estimated total
497
+ additional income exceeding S$300,000 annually once fully scaled.
498
+
499
+ We recommend proceeding with Phase 1 validation in Vietnam in 2026, with clear
500
+ success metrics and a defined pathway to Phase 2 expansion and commercialization.
501
+
502
+ ════════════════════════════════════════════════════════════════════════════════
503
+ Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
504
+ ════════════════════════════════════════════════════════════════════════════════
505
+ """
506
+
507
+ return report
508
+
509
+ # ============================================================================
510
+ # Gradio Interface Setup
511
+ # ============================================================================
512
+
513
+ def create_interface():
514
+ """Create the Gradio interface for the PAK System POC platform."""
515
+
516
+ with gr.Blocks(title="PAK System POC Platform", theme=gr.themes.Soft()) as demo:
517
+
518
+ gr.Markdown("""
519
+ # 🌱 Precision Attract-and-Kill (PAK) System
520
+ ## Interactive POC Platform for Coffee Berry Borer Management
521
+
522
+ Welcome to the PAK System Proof of Concept platform. Use the tools below to analyze
523
+ the financial and operational feasibility of implementing the PAK System on your farm
524
+ or across your farmer network.
525
+ """)
526
+
527
+ with gr.Tabs():
528
+
529
+ # ================================================================
530
+ # TAB 1: FARM-LEVEL ANALYSIS
531
+ # ================================================================
532
+ with gr.TabItem("🚜 Farm Analysis"):
533
+ gr.Markdown("""
534
+ ### Individual Farm ROI Calculator
535
+
536
+ Enter your farm size to see detailed financial projections comparing
537
+ the PAK System with current IPM approaches.
538
+ """)
539
+
540
+ with gr.Row():
541
+ with gr.Column():
542
+ farm_size = gr.Slider(
543
+ label="Farm Size (hectares)",
544
+ minimum=0.5,
545
+ maximum=50,
546
+ value=2,
547
+ step=0.5
548
+ )
549
+ analyze_btn = gr.Button("Analyze Farm", variant="primary", size="lg")
550
+
551
+ with gr.Column():
552
+ gr.Markdown("**Quick Reference**\n\n"
553
+ "β€’ Smallholder: 0.5-2 ha\n"
554
+ "β€’ Medium Farm: 2-10 ha\n"
555
+ "β€’ Estate: 10-50+ ha")
556
+
557
+ with gr.Row():
558
+ summary_output = gr.Textbox(
559
+ label="Analysis Summary",
560
+ lines=25,
561
+ interactive=False,
562
+ max_lines=50
563
+ )
564
+
565
+ with gr.Row():
566
+ with gr.Column():
567
+ chart1 = gr.Plot(label="Comparison Charts")
568
+ with gr.Column():
569
+ chart2 = gr.Plot(label="5-Year Projection")
570
+
571
+ analyze_btn.click(
572
+ fn=analyze_farm,
573
+ inputs=[farm_size],
574
+ outputs=[summary_output, chart1, chart2]
575
+ )
576
+
577
+ # ================================================================
578
+ # TAB 2: NETWORK ANALYSIS
579
+ # ================================================================
580
+ with gr.TabItem("🌍 Network Analysis"):
581
+ gr.Markdown("""
582
+ ### Farmer Network Impact Calculator
583
+
584
+ Analyze the aggregate impact of implementing the PAK System
585
+ across a farmer network or sourcing region.
586
+ """)
587
+
588
+ with gr.Row():
589
+ with gr.Column():
590
+ total_farmers = gr.Slider(
591
+ label="Total Farmers",
592
+ minimum=10,
593
+ maximum=10000,
594
+ value=100,
595
+ step=10
596
+ )
597
+ with gr.Column():
598
+ avg_farm_size = gr.Slider(
599
+ label="Average Farm Size (hectares)",
600
+ minimum=0.5,
601
+ maximum=10,
602
+ value=1.5,
603
+ step=0.5
604
+ )
605
+
606
+ analyze_network_btn = gr.Button("Analyze Network", variant="primary", size="lg")
607
+
608
+ with gr.Row():
609
+ network_summary = gr.Textbox(
610
+ label="Network Analysis",
611
+ lines=25,
612
+ interactive=False,
613
+ max_lines=50
614
+ )
615
+
616
+ with gr.Row():
617
+ network_chart = gr.Plot(label="Network Impact Visualization")
618
+
619
+ analyze_network_btn.click(
620
+ fn=network_analysis,
621
+ inputs=[total_farmers, avg_farm_size],
622
+ outputs=[network_summary, network_chart]
623
+ )
624
+
625
+ # ================================================================
626
+ # TAB 3: DETAILED REPORT
627
+ # ================================================================
628
+ with gr.TabItem("πŸ“Š Detailed Report"):
629
+ gr.Markdown("""
630
+ ### Comprehensive Feasibility Report
631
+
632
+ Generate a detailed, publication-ready report for stakeholder
633
+ presentations and decision-making.
634
+ """)
635
+
636
+ with gr.Row():
637
+ with gr.Column():
638
+ report_farm_size = gr.Slider(
639
+ label="Farm Size (hectares)",
640
+ minimum=0.5,
641
+ maximum=100,
642
+ value=5,
643
+ step=0.5
644
+ )
645
+ with gr.Column():
646
+ report_years = gr.Slider(
647
+ label="Projection Period (years)",
648
+ minimum=1,
649
+ maximum=10,
650
+ value=5,
651
+ step=1
652
+ )
653
+
654
+ generate_report_btn = gr.Button("Generate Report", variant="primary", size="lg")
655
+
656
+ report_output = gr.Textbox(
657
+ label="Detailed Report",
658
+ lines=40,
659
+ interactive=False,
660
+ max_lines=100
661
+ )
662
+
663
+ generate_report_btn.click(
664
+ fn=generate_detailed_report,
665
+ inputs=[report_farm_size, report_years],
666
+ outputs=report_output
667
+ )
668
+
669
+ # ================================================================
670
+ # TAB 4: SYSTEM INFORMATION
671
+ # ================================================================
672
+ with gr.TabItem("ℹ️ System Information"):
673
+ gr.Markdown("""
674
+ ### PAK System Technical Specifications
675
+
676
+ #### Active Ingredients
677
+ - **Semiochemical Lure**: Optimized blend of CBB aggregation pheromone and host volatiles
678
+ - **Biological Agent**: Beauveria bassiana (entomopathogenic fungus)
679
+ - **Formulation**: Micro-encapsulated paste/gel for weather resistance
680
+
681
+ #### Application Methods
682
+ - **Drone/UAV**: Automated spot-spraying for estates and farmer clusters
683
+ - **Backpack Sprayer**: Semi-automated application for individual smallholders
684
+ - **Frequency**: 2-3 applications per season during peak CBB activity
685
+
686
+ #### Performance Metrics
687
+ - **Infestation Reduction**: 90%+ (vs. 50-90% for current IPM)
688
+ - **Cost Reduction**: 33% (from S$150/ha to <S$100/ha)
689
+ - **Labor Reduction**: 50%+ (from 16 to 8 hours/ha)
690
+ - **Standardization**: High consistency across farm types
691
+
692
+ #### Safety & Compliance
693
+ - βœ… Organic Certification: Fully compliant
694
+ - βœ… Environmental Impact: No harm to beneficial insects
695
+ - βœ… Biodiversity: Supports regenerative agriculture
696
+ - βœ… Regulatory: Aligns with international standards
697
+
698
+ #### Implementation Timeline
699
+ - **Phase 1 (2026)**: Proof of Concept in Vietnam (S$6,500)
700
+ - **Phase 2 (2027)**: Expansion to Indonesia & PNG (S$12,500-15,000)
701
+ - **Phase 3 (2028+)**: Commercial rollout via IPM-as-a-Service model
702
+
703
+ #### Business Model
704
+ - **Service Delivery**: ECOM or partner provides formulation and application
705
+ - **Pricing**: Fixed post-harvest fee (S$5-10/bag)
706
+ - **Farmer Benefit**: Clear ROI with payback period <12 months
707
+ - **Scalability**: Applicable across ECOM's global network
708
+ """)
709
+
710
+ return demo
711
+
712
+ # ============================================================================
713
+ # Main Execution
714
+ # ============================================================================
715
+
716
+ if __name__ == "__main__":
717
+ demo = create_interface()
718
+ demo.launch(
719
+ server_name="0.0.0.0",
720
+ server_port=7860,
721
+ share=False,
722
+ show_error=True
723
+ )