File size: 36,844 Bytes
87121a2
8f066a6
 
 
 
 
43130d1
 
87121a2
8f066a6
 
 
87121a2
8f066a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43130d1
 
8f066a6
 
 
 
 
 
 
 
43130d1
 
8f066a6
 
 
 
 
43130d1
8f066a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43130d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f066a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43130d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f066a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43130d1
8f066a6
 
43130d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f066a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
import gradio as gr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import json
import io
from PIL import Image

# ============================================================================
# PAK System Configuration and Constants
# ============================================================================

PAK_EFFICACY = 0.92  # 92% infestation reduction
CURRENT_IPM_EFFICACY = 0.70  # 70% average for Triple IPM
PAK_COST_PER_HA = 95  # S$ per hectare
CURRENT_IPM_COST_PER_HA = 150  # S$ per hectare
PAK_LABOR_HOURS_PER_HA = 8  # hours per hectare
CURRENT_IPM_LABOR_HOURS_PER_HA = 16  # hours per hectare
LABOR_COST_PER_HOUR = 5  # S$ per hour

BASELINE_INFESTATION_RATE = 0.41  # 41% baseline infestation
YIELD_PER_HA_BASELINE = 1200  # kg per hectare
COFFEE_PRICE_PER_KG = 2.50  # S$ per kg

# ============================================================================
# Core Calculation Functions
# ============================================================================

def calculate_infestation_rate(baseline_rate, efficacy):
    """Calculate resulting infestation rate after treatment."""
    return baseline_rate * (1 - efficacy)

def calculate_yield_impact(baseline_yield, infestation_reduction):
    """
    Calculate yield improvement based on infestation reduction.
    Assumes 2% yield loss per 1% infestation rate.
    """
    yield_loss_per_infestation = 0.02
    yield_improvement = baseline_yield * infestation_reduction * yield_loss_per_infestation
    return baseline_yield + yield_improvement

def calculate_costs(farm_size_ha, use_pak=True):
    """Calculate total costs for pest management."""
    if use_pak:
        material_cost = farm_size_ha * PAK_COST_PER_HA
        labor_cost = farm_size_ha * PAK_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR
    else:
        material_cost = farm_size_ha * CURRENT_IPM_COST_PER_HA
        labor_cost = farm_size_ha * CURRENT_IPM_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR
    
    total_cost = material_cost + labor_cost
    return {
        'material_cost': material_cost,
        'labor_cost': labor_cost,
        'total_cost': total_cost
    }

def calculate_roi(farm_size_ha, years=1):
    """Calculate Return on Investment for PAK System vs Current IPM."""
    
    # Current IPM scenario
    current_infestation = calculate_infestation_rate(BASELINE_INFESTATION_RATE, CURRENT_IPM_EFFICACY)
    current_yield = calculate_yield_impact(YIELD_PER_HA_BASELINE, 
                                          CURRENT_IPM_EFFICACY * BASELINE_INFESTATION_RATE)
    current_revenue = farm_size_ha * current_yield * COFFEE_PRICE_PER_KG
    current_costs = calculate_costs(farm_size_ha, use_pak=False)['total_cost']
    current_profit = current_revenue - current_costs
    
    # PAK System scenario
    pak_infestation = calculate_infestation_rate(BASELINE_INFESTATION_RATE, PAK_EFFICACY)
    pak_yield = calculate_yield_impact(YIELD_PER_HA_BASELINE, 
                                       PAK_EFFICACY * BASELINE_INFESTATION_RATE)
    pak_revenue = farm_size_ha * pak_yield * COFFEE_PRICE_PER_KG
    pak_costs = calculate_costs(farm_size_ha, use_pak=True)['total_cost']
    pak_profit = pak_revenue - pak_costs
    
    # ROI Calculation
    profit_improvement = pak_profit - current_profit
    cost_savings = current_costs - pak_costs
    roi_percentage = (profit_improvement / current_costs) * 100 if current_costs > 0 else 0
    
    return {
        'current_infestation': current_infestation,
        'pak_infestation': pak_infestation,
        'current_yield': current_yield,
        'pak_yield': pak_yield,
        'current_revenue': current_revenue,
        'pak_revenue': pak_revenue,
        'current_costs': current_costs,
        'pak_costs': pak_costs,
        'current_profit': current_profit,
        'pak_profit': pak_profit,
        'profit_improvement': profit_improvement,
        'cost_savings': cost_savings,
        'roi_percentage': roi_percentage,
        'payback_period_months': (pak_costs / (profit_improvement / 12)) if profit_improvement > 0 else float('inf')
    }

def generate_comparison_chart(farm_size_ha):
    """Generate comparison charts for PAK vs Current IPM."""
    roi_data = calculate_roi(farm_size_ha)
    
    fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    fig.suptitle(f'PAK System vs Current IPM - {farm_size_ha} hectares', fontsize=16, fontweight='bold')
    
    # Infestation Rate Comparison
    ax1 = axes[0, 0]
    methods = ['Current IPM', 'PAK System']
    infestation_rates = [roi_data['current_infestation'] * 100, roi_data['pak_infestation'] * 100]
    colors = ['#C85A3C', '#7A9E3F']
    bars1 = ax1.bar(methods, infestation_rates, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
    ax1.set_ylabel('Infestation Rate (%)', fontweight='bold')
    ax1.set_title('Infestation Rate Comparison', fontweight='bold')
    ax1.set_ylim(0, 50)
    for bar, rate in zip(bars1, infestation_rates):
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                f'{rate:.1f}%', ha='center', va='bottom', fontweight='bold')
    
    # Yield Comparison
    ax2 = axes[0, 1]
    yields = [roi_data['current_yield'], roi_data['pak_yield']]
    bars2 = ax2.bar(methods, yields, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
    ax2.set_ylabel('Yield (kg/ha)', fontweight='bold')
    ax2.set_title('Yield Comparison', fontweight='bold')
    ax2.set_ylim(0, max(yields) * 1.2)
    for bar, yield_val in zip(bars2, yields):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height,
                f'{yield_val:.0f}', ha='center', va='bottom', fontweight='bold')
    
    # Cost Comparison
    ax3 = axes[1, 0]
    costs = [roi_data['current_costs'], roi_data['pak_costs']]
    bars3 = ax3.bar(methods, costs, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
    ax3.set_ylabel('Total Cost (S$)', fontweight='bold')
    ax3.set_title('Annual Cost Comparison', fontweight='bold')
    ax3.set_ylim(0, max(costs) * 1.2)
    for bar, cost in zip(bars3, costs):
        height = bar.get_height()
        ax3.text(bar.get_x() + bar.get_width()/2., height,
                f'S${cost:.0f}', ha='center', va='bottom', fontweight='bold')
    
    # Profit Comparison
    ax4 = axes[1, 1]
    profits = [roi_data['current_profit'], roi_data['pak_profit']]
    bars4 = ax4.bar(methods, profits, color=colors, alpha=0.8, edgecolor='black', linewidth=1.5)
    ax4.set_ylabel('Annual Profit (S$)', fontweight='bold')
    ax4.set_title('Annual Profit Comparison', fontweight='bold')
    ax4.set_ylim(0, max(profits) * 1.2)
    for bar, profit in zip(bars4, profits):
        height = bar.get_height()
        ax4.text(bar.get_x() + bar.get_width()/2., height,
                f'S${profit:.0f}', ha='center', va='bottom', fontweight='bold')
    
    plt.tight_layout()
    return fig

def generate_timeline_projection(farm_size_ha, years=5):
    """Generate 5-year financial projection."""
    years_range = np.arange(0, years + 1)
    current_profits = []
    pak_profits = []
    
    for year in years_range:
        roi = calculate_roi(farm_size_ha)
        current_profits.append(roi['current_profit'] * year)
        pak_profits.append(roi['pak_profit'] * year)
    
    fig, ax = plt.subplots(figsize=(12, 6))
    ax.plot(years_range, current_profits, marker='o', linewidth=2.5, markersize=8, 
            label='Current IPM', color='#C85A3C')
    ax.plot(years_range, pak_profits, marker='s', linewidth=2.5, markersize=8, 
            label='PAK System', color='#7A9E3F')
    
    ax.set_xlabel('Years', fontweight='bold', fontsize=12)
    ax.set_ylabel('Cumulative Profit (S$)', fontweight='bold', fontsize=12)
    ax.set_title(f'5-Year Financial Projection - {farm_size_ha} hectares', fontweight='bold', fontsize=14)
    ax.legend(fontsize=11, loc='upper left')
    ax.grid(True, alpha=0.3)
    
    # Format y-axis as currency
    ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'S${x/1000:.0f}K'))
    
    plt.tight_layout()
    return fig

# ============================================================================
# Gradio Interface Functions
# ============================================================================

def analyze_farm(farm_size_ha, baseline_infestation=41):
    """Main analysis function for farm-level ROI calculation."""
    
    if farm_size_ha <= 0:
        return "Error: Farm size must be greater than 0", None, None
    
    roi_data = calculate_roi(farm_size_ha)
    
    # Generate summary report
    summary = f"""
╔════════════════════════════════════════════════════════════════╗
β•‘         PAK SYSTEM ROI ANALYSIS - {farm_size_ha} HECTARES
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

INFESTATION CONTROL
──────────────────────────────────────────────────────────────────
Current IPM Infestation Rate:        {roi_data['current_infestation']*100:.1f}%
PAK System Infestation Rate:         {roi_data['pak_infestation']*100:.1f}%
Improvement:                         {(roi_data['current_infestation'] - roi_data['pak_infestation'])*100:.1f}%

YIELD IMPACT
──────────────────────────────────────────────────────────────────
Current IPM Yield:                   {roi_data['current_yield']:.0f} kg/ha
PAK System Yield:                    {roi_data['pak_yield']:.0f} kg/ha
Additional Yield:                    {roi_data['pak_yield'] - roi_data['current_yield']:.0f} kg/ha

FINANCIAL ANALYSIS (Annual)
──────────────────────────────────────────────────────────────────
Current IPM:
  β€’ Total Cost:                      S${roi_data['current_costs']:,.0f}
  β€’ Revenue:                         S${roi_data['current_revenue']:,.0f}
  β€’ Profit:                          S${roi_data['current_profit']:,.0f}

PAK System:
  β€’ Total Cost:                      S${roi_data['pak_costs']:,.0f}
  β€’ Revenue:                         S${roi_data['pak_revenue']:,.0f}
  β€’ Profit:                          S${roi_data['pak_profit']:,.0f}

RETURN ON INVESTMENT
──────────────────────────────────────────────────────────────────
Annual Profit Improvement:           S${roi_data['profit_improvement']:,.0f}
Annual Cost Savings:                 S${roi_data['cost_savings']:,.0f}
ROI Percentage:                      {roi_data['roi_percentage']:.1f}%
Payback Period:                      {roi_data['payback_period_months']:.1f} months

5-YEAR PROJECTION
──────────────────────────────────────────────────────────────────
Current IPM Total Profit (5 years):  S${roi_data['current_profit']*5:,.0f}
PAK System Total Profit (5 years):   S${roi_data['pak_profit']*5:,.0f}
Additional Profit (5 years):         S${(roi_data['pak_profit'] - roi_data['current_profit'])*5:,.0f}
"""
    
    comparison_chart = generate_comparison_chart(farm_size_ha)
    timeline_chart = generate_timeline_projection(farm_size_ha, years=5)
    
    return summary, comparison_chart, timeline_chart

def network_analysis(total_farmers, avg_farm_size_ha):
    """Analyze PAK System impact across farmer network."""
    
    if total_farmers <= 0 or avg_farm_size_ha <= 0:
        return "Error: Please enter valid values", None
    
    total_hectares = total_farmers * avg_farm_size_ha
    roi_data = calculate_roi(total_hectares)
    
    summary = f"""
╔════════════════════════════════════════════════════════════════╗
β•‘         NETWORK-LEVEL PAK SYSTEM IMPACT ANALYSIS
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

NETWORK SCALE
──────────────────────────────────────────────────────────────────
Total Farmers:                       {total_farmers:,}
Average Farm Size:                   {avg_farm_size_ha} hectares
Total Network Area:                  {total_hectares:,} hectares

AGGREGATE ANNUAL IMPACT
──────────────────────────────────────────────────────────────────
Total Cost Savings:                  S${roi_data['cost_savings']:,.0f}
Total Profit Improvement:            S${roi_data['profit_improvement']:,.0f}
Total Additional Yield:              {(roi_data['pak_yield'] - roi_data['current_yield']) * total_hectares:,.0f} kg

PER-FARMER ANNUAL IMPACT
──────────────────────────────────────────────────────────────────
Cost Savings per Farmer:             S${roi_data['cost_savings']/total_farmers:,.0f}
Profit Improvement per Farmer:       S${roi_data['profit_improvement']/total_farmers:,.0f}
Additional Income per Farmer:        S${(roi_data['profit_improvement']/total_farmers):,.0f}

SUSTAINABILITY METRICS
──────────────────────────────────────────────────────────────────
Synthetic Pesticide Elimination:     100%
Labor Reduction:                     50%+
Organic Certification Compliance:    100%
Biodiversity Impact:                 Positive (no harm to beneficial insects)

5-YEAR NETWORK PROJECTION
──────────────────────────────────────────────────────────────────
Total Additional Income (5 years):   S${(roi_data['profit_improvement'] - roi_data['cost_savings'])*5:,.0f}
Cumulative Farmers Benefited:        {total_farmers:,}
Estimated Yield Increase (5 years):  {(roi_data['pak_yield'] - roi_data['current_yield']) * total_hectares * 5:,.0f} kg
"""
    
    # Create network visualization
    fig, axes = plt.subplots(1, 2, figsize=(14, 6))
    fig.suptitle(f'Network Impact: {total_farmers:,} Farmers, {total_hectares:,} hectares', 
                 fontsize=14, fontweight='bold')
    
    # Cost savings breakdown
    ax1 = axes[0]
    categories = ['Material\nCosts', 'Labor\nCosts']
    current_material = (total_hectares * CURRENT_IPM_COST_PER_HA)
    current_labor = (total_hectares * CURRENT_IPM_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR)
    pak_material = (total_hectares * PAK_COST_PER_HA)
    pak_labor = (total_hectares * PAK_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR)
    
    x = np.arange(len(categories))
    width = 0.35
    
    bars1 = ax1.bar(x - width/2, [current_material, current_labor], width, 
                    label='Current IPM', color='#C85A3C', alpha=0.8, edgecolor='black')
    bars2 = ax1.bar(x + width/2, [pak_material, pak_labor], width, 
                    label='PAK System', color='#7A9E3F', alpha=0.8, edgecolor='black')
    
    ax1.set_ylabel('Annual Cost (S$)', fontweight='bold')
    ax1.set_title('Cost Breakdown Comparison', fontweight='bold')
    ax1.set_xticks(x)
    ax1.set_xticklabels(categories)
    ax1.legend()
    ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'S${x/1000:.0f}K'))
    
    # Profit distribution
    ax2 = axes[1]
    profit_data = [roi_data['current_profit'], roi_data['pak_profit']]
    colors = ['#C85A3C', '#7A9E3F']
    bars = ax2.bar(['Current IPM', 'PAK System'], profit_data, color=colors, alpha=0.8, edgecolor='black')
    ax2.set_ylabel('Annual Profit (S$)', fontweight='bold')
    ax2.set_title('Network Annual Profit', fontweight='bold')
    ax2.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'S${x/1000:.0f}K'))
    
    for bar, profit in zip(bars, profit_data):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height,
                f'S${profit/1000:.0f}K', ha='center', va='bottom', fontweight='bold')
    
    plt.tight_layout()
    
    return summary, fig

def generate_detailed_report(farm_size_ha, years=5):
    """Generate comprehensive PDF-ready report."""
    
    roi_data = calculate_roi(farm_size_ha)
    
    report = f"""
════════════════════════════════════════════════════════════════════════════════
                    PRECISION ATTRACT-AND-KILL (PAK) SYSTEM
                         DETAILED FEASIBILITY REPORT
════════════════════════════════════════════════════════════════════════════════

EXECUTIVE SUMMARY
────────────────────────────────────────────────────────────────────────────────

The Precision Attract-and-Kill System represents a transformative approach to 
Coffee Berry Borer management. This report analyzes the technical, financial, 
and operational feasibility of implementing the PAK System on a {farm_size_ha}-hectare 
farm or network.

KEY FINDINGS:
β€’ 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)
β€’ Annual Cost Savings: S${roi_data['cost_savings']:,.0f}
β€’ Annual Profit Improvement: S${roi_data['profit_improvement']:,.0f}
β€’ ROI: {roi_data['roi_percentage']:.1f}%
β€’ Payback Period: {roi_data['payback_period_months']:.1f} months

════════════════════════════════════════════════════════════════════════════════

TECHNICAL SPECIFICATIONS
────────────────────────────────────────────────────────────────────────────────

Active Ingredients:
β€’ Semiochemical Lure: Optimized blend of CBB aggregation pheromone and host volatiles
β€’ Biological Agent: Beauveria bassiana (entomopathogenic fungus)
β€’ Formulation: Micro-encapsulated paste/gel for weather resistance

Application Methods:
β€’ Drone/UAV: Automated spot-spraying for estates and farmer clusters
β€’ Backpack Sprayer: Semi-automated application for individual smallholders
β€’ Application Frequency: 2-3 times per season during peak CBB activity

Safety & Compliance:
β€’ Organic Certification: Fully compliant (Rainforest Alliance, 4C, etc.)
β€’ Environmental Impact: No harm to pollinators or beneficial insects
β€’ Biodiversity: Supports regenerative agriculture practices

════════════════════════════════════════════════════════════════════════════════

FINANCIAL ANALYSIS
────────────────────────────────────────────────────────────────────────────────

YEAR 1 ANALYSIS ({farm_size_ha} hectares):

Current IPM Approach:
  Material Costs:                    S${farm_size_ha * CURRENT_IPM_COST_PER_HA:,.0f}
  Labor Costs:                       S${farm_size_ha * CURRENT_IPM_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR:,.0f}
  Total Costs:                       S${roi_data['current_costs']:,.0f}
  Gross Revenue:                     S${roi_data['current_revenue']:,.0f}
  Net Profit:                        S${roi_data['current_profit']:,.0f}

PAK System Approach:
  Material Costs:                    S${farm_size_ha * PAK_COST_PER_HA:,.0f}
  Labor Costs:                       S${farm_size_ha * PAK_LABOR_HOURS_PER_HA * LABOR_COST_PER_HOUR:,.0f}
  Total Costs:                       S${roi_data['pak_costs']:,.0f}
  Gross Revenue:                     S${roi_data['pak_revenue']:,.0f}
  Net Profit:                        S${roi_data['pak_profit']:,.0f}

COMPARATIVE ADVANTAGE:
  Cost Savings:                      S${roi_data['cost_savings']:,.0f} ({(roi_data['cost_savings']/roi_data['current_costs'])*100:.1f}%)
  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}%)
  Profit Improvement:                S${roi_data['profit_improvement']:,.0f} ({(roi_data['profit_improvement']/roi_data['current_profit'])*100:.1f}%)

{years}-YEAR PROJECTION:
  Current IPM Total Profit:          S${roi_data['current_profit']*years:,.0f}
  PAK System Total Profit:           S${roi_data['pak_profit']*years:,.0f}
  Additional Profit ({years} years):       S${(roi_data['pak_profit'] - roi_data['current_profit'])*years:,.0f}

════════════════════════════════════════════════════════════════════════════════

IMPLEMENTATION ROADMAP
────────────────────────────────────────────────────────────────────────────────

PHASE 1: PROOF OF CONCEPT (2026)
Timeline: 12 months
Investment: S$6,500 (for 5-10 hectares)
Deliverables:
  β€’ Field trial validation in Vietnam
  β€’ Efficacy data (target: 90%+ infestation reduction)
  β€’ Cost-benefit analysis
  β€’ Farmer feedback and adoption metrics

PHASE 2: EXPANSION & STANDARDIZATION (2027)
Timeline: 12 months
Investment: S$12,500-15,000 (for Indonesia & PNG)
Deliverables:
  β€’ Formulation adaptation for regional conditions
  β€’ Expanded field trials (50+ farmers)
  β€’ Standardized protocols and training materials
  β€’ Regional scale-up plan

PHASE 3: COMMERCIALIZATION (2028+)
Timeline: Ongoing
Model: IPM-as-a-Service
  β€’ ECOM or partner provides formulation and application
  β€’ Fixed post-harvest fee (S$5-10/bag)
  β€’ Rapid adoption across farmer network

════════════════════════════════════════════════════════════════════════════════

RISK ASSESSMENT & MITIGATION
────────────────────────────────────────────────────────────────────────────────

Risk: Formulation efficacy below target
Probability: Medium | Impact: High
Mitigation: Preliminary lab testing; contingency budget for adjustments

Risk: Weather impact on field trials
Probability: Medium | Impact: Medium
Mitigation: Multiple demo plot locations; extended trial period if needed

Risk: Farmer adoption challenges
Probability: Medium | Impact: Medium
Mitigation: Early engagement; clear training; peer learning networks

Risk: Regulatory or certification issues
Probability: Low | Impact: High
Mitigation: Early engagement with certification bodies; full documentation

════════════════════════════════════════════════════════════════════════════════

SUSTAINABILITY & LIVELIHOOD IMPACT
────────────────────────────────────────────────────────────────────────────────

Environmental Benefits:
β€’ Elimination of synthetic pesticides
β€’ Support for soil health and biodiversity
β€’ Reduced carbon intensity of coffee production
β€’ Climate-smart agriculture alignment

Livelihood Benefits:
β€’ Reduced labor burden (50% reduction)
β€’ Improved income stability
β€’ Enhanced quality of life for farming communities
β€’ Scalable across ECOM's global network

════════════════════════════════════════════════════════════════════════════════

CONCLUSION
────────────────────────────────────────────────────────────────────────────────

The Precision Attract-and-Kill System represents a transformative opportunity 
for ECOM to address the Coffee Berry Borer challenge with a single, nature-based, 
and highly scalable solution. The financial analysis demonstrates clear ROI, 
with payback periods under 12 months and substantial long-term profit improvements.

The modest Phase 1 investment of S$6,500 is justified by the potential impact 
across ECOM's network of 6,000+ smallholder farmers, with estimated total 
additional income exceeding S$300,000 annually once fully scaled.

We recommend proceeding with Phase 1 validation in Vietnam in 2026, with clear 
success metrics and a defined pathway to Phase 2 expansion and commercialization.

════════════════════════════════════════════════════════════════════════════════
Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
════════════════════════════════════════════════════════════════════════════════
"""
    
    return report

# ============================================================================
# Gradio Interface Setup
# ============================================================================

def create_interface():
    """Create the Gradio interface for the PAK System POC platform."""
    
    with gr.Blocks(title="PAK System POC Platform", theme=gr.themes.Soft()) as demo:
        
        gr.Markdown("""
        # 🌱 Precision Attract-and-Kill (PAK) System
        ## Interactive POC Platform for Coffee Berry Borer Management
        
        Welcome to the PAK System Proof of Concept platform. Use the tools below to analyze 
        the financial and operational feasibility of implementing the PAK System on your farm 
        or across your farmer network.
        """)
        
        with gr.Tabs():
            
            # ================================================================
            # TAB 1: FARM-LEVEL ANALYSIS
            # ================================================================
            with gr.TabItem("🚜 Farm Analysis"):
                gr.Markdown("""
                ### Individual Farm ROI Calculator
                
                Enter your farm size to see detailed financial projections comparing 
                the PAK System with current IPM approaches.
                """)
                
                with gr.Row():
                    with gr.Column():
                        farm_size = gr.Slider(
                            label="Farm Size (hectares)",
                            minimum=0.5,
                            maximum=50,
                            value=2,
                            step=0.5
                        )
                        analyze_btn = gr.Button("Analyze Farm", variant="primary", size="lg")
                    
                    with gr.Column():
                        gr.Markdown("**Quick Reference**\n\n"
                                   "β€’ Smallholder: 0.5-2 ha\n"
                                   "β€’ Medium Farm: 2-10 ha\n"
                                   "β€’ Estate: 10-50+ ha")
                
                with gr.Row():
                    summary_output = gr.Textbox(
                        label="Analysis Summary",
                        lines=25,
                        interactive=False,
                        max_lines=50
                    )
                
                with gr.Row():
                    with gr.Column():
                        chart1 = gr.Plot(label="Comparison Charts")
                    with gr.Column():
                        chart2 = gr.Plot(label="5-Year Projection")
                
                analyze_btn.click(
                    fn=analyze_farm,
                    inputs=[farm_size],
                    outputs=[summary_output, chart1, chart2]
                )
            
            # ================================================================
            # TAB 2: NETWORK ANALYSIS
            # ================================================================
            with gr.TabItem("🌍 Network Analysis"):
                gr.Markdown("""
                ### Farmer Network Impact Calculator
                
                Analyze the aggregate impact of implementing the PAK System 
                across a farmer network or sourcing region.
                """)
                
                with gr.Row():
                    with gr.Column():
                        total_farmers = gr.Slider(
                            label="Total Farmers",
                            minimum=10,
                            maximum=10000,
                            value=100,
                            step=10
                        )
                    with gr.Column():
                        avg_farm_size = gr.Slider(
                            label="Average Farm Size (hectares)",
                            minimum=0.5,
                            maximum=10,
                            value=1.5,
                            step=0.5
                        )
                
                analyze_network_btn = gr.Button("Analyze Network", variant="primary", size="lg")
                
                with gr.Row():
                    network_summary = gr.Textbox(
                        label="Network Analysis",
                        lines=25,
                        interactive=False,
                        max_lines=50
                    )
                
                with gr.Row():
                    network_chart = gr.Plot(label="Network Impact Visualization")
                
                analyze_network_btn.click(
                    fn=network_analysis,
                    inputs=[total_farmers, avg_farm_size],
                    outputs=[network_summary, network_chart]
                )
            
            # ================================================================
            # TAB 3: DETAILED REPORT
            # ================================================================
            with gr.TabItem("πŸ“Š Detailed Report"):
                gr.Markdown("""
                ### Comprehensive Feasibility Report
                
                Generate a detailed, publication-ready report for stakeholder 
                presentations and decision-making.
                """)
                
                with gr.Row():
                    with gr.Column():
                        report_farm_size = gr.Slider(
                            label="Farm Size (hectares)",
                            minimum=0.5,
                            maximum=100,
                            value=5,
                            step=0.5
                        )
                    with gr.Column():
                        report_years = gr.Slider(
                            label="Projection Period (years)",
                            minimum=1,
                            maximum=10,
                            value=5,
                            step=1
                        )
                
                generate_report_btn = gr.Button("Generate Report", variant="primary", size="lg")
                
                report_output = gr.Textbox(
                    label="Detailed Report",
                    lines=40,
                    interactive=False,
                    max_lines=100
                )
                
                generate_report_btn.click(
                    fn=generate_detailed_report,
                    inputs=[report_farm_size, report_years],
                    outputs=report_output
                )
            
            # ================================================================
            # TAB 4: SYSTEM INFORMATION
            # ================================================================
            with gr.TabItem("ℹ️ System Information"):
                gr.Markdown("""
                ### PAK System Technical Specifications
                
                #### Active Ingredients
                - **Semiochemical Lure**: Optimized blend of CBB aggregation pheromone and host volatiles
                - **Biological Agent**: Beauveria bassiana (entomopathogenic fungus)
                - **Formulation**: Micro-encapsulated paste/gel for weather resistance
                
                #### Application Methods
                - **Drone/UAV**: Automated spot-spraying for estates and farmer clusters
                - **Backpack Sprayer**: Semi-automated application for individual smallholders
                - **Frequency**: 2-3 applications per season during peak CBB activity
                
                #### Performance Metrics
                - **Infestation Reduction**: 90%+ (vs. 50-90% for current IPM)
                - **Cost Reduction**: 33% (from S$150/ha to <S$100/ha)
                - **Labor Reduction**: 50%+ (from 16 to 8 hours/ha)
                - **Standardization**: High consistency across farm types
                
                #### Safety & Compliance
                - βœ… Organic Certification: Fully compliant
                - βœ… Environmental Impact: No harm to beneficial insects
                - βœ… Biodiversity: Supports regenerative agriculture
                - βœ… Regulatory: Aligns with international standards
                
                #### Implementation Timeline
                - **Phase 1 (2026)**: Proof of Concept in Vietnam (S$6,500)
                - **Phase 2 (2027)**: Expansion to Indonesia & PNG (S$12,500-15,000)
                - **Phase 3 (2028+)**: Commercial rollout via IPM-as-a-Service model
                
                #### Business Model
                - **Service Delivery**: ECOM or partner provides formulation and application
                - **Pricing**: Fixed post-harvest fee (S$5-10/bag)
                - **Farmer Benefit**: Clear ROI with payback period <12 months
                - **Scalability**: Applicable across ECOM's global network
                """)
    
    return demo

# ============================================================================
# Main Execution
# ============================================================================

if __name__ == "__main__":
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )