NTEIGBANAM OKE commited on
Commit
796ba07
·
verified ·
1 Parent(s): 8062816

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +711 -1309
app.py CHANGED
@@ -1,1159 +1,844 @@
1
- import os
2
  import math
 
3
  import re
4
- from datetime import datetime, timezone
5
- from urllib.parse import urlparse, urlunparse
6
 
7
- import requests
8
- import pandas as pd
9
  import gradio as gr
10
 
11
- from fastapi import FastAPI, Request
12
- from fastapi.responses import RedirectResponse
13
- from starlette.config import Config
14
- from starlette.middleware.sessions import SessionMiddleware
15
-
16
- from authlib.integrations.starlette_client import OAuth, OAuthError
17
-
18
 
19
  # ============================================================
20
- # CONFIGURATION
21
  # ============================================================
22
 
23
- APP_NAME = "PoultryFeedCalc"
24
 
25
- DEFAULT_BAG_SIZE = 25
26
- DEFAULT_BAG_PRICE = 24000
27
 
28
- # Practical allowance above the Ross benchmark.
29
- # Example:
30
- # 25 birds × 6 weeks = about 4.89 benchmark bags
31
- # 4.89 × 1.20 = about 5.86 bags
32
- # Rounded up = 6 bags
33
- FEED_ALLOWANCE = 1.20
34
 
35
- # External webhook for mailing list + questions.
 
 
36
  #
37
- # Recommended:
38
- # Google Apps Script Web App
 
39
  #
40
- # Set in Hugging Face Space Secrets:
41
- # LEADS_WEBHOOK_URL=https://script.google.com/macros/s/XXXXXXXX/exec
42
  #
43
- LEADS_WEBHOOK_URL = os.getenv("LEADS_WEBHOOK_URL", "").strip()
44
-
45
- # Optional OpenAI API key for answering farmer questions.
46
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
47
-
48
- # Google OAuth settings.
49
- GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID", "").strip()
50
- GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET", "").strip()
51
-
52
- # Session secret.
53
- SESSION_SECRET = os.getenv(
54
- "SESSION_SECRET",
55
- "CHANGE_THIS_SECRET_IN_HUGGINGFACE_SECRETS"
56
- )
57
-
58
- # Your public Space URL.
59
- # Example:
60
- # https://okejonah1-poultry-feed-calculator.hf.space
61
- SPACE_URL = os.getenv(
62
- "SPACE_URL",
63
- "https://okejonah1-poultry-feed-calculator.hf.space"
64
- ).rstrip("/")
65
-
66
-
67
- # ============================================================
68
- # ROSS 308 PERFORMANCE DATA
69
  # ============================================================
70
 
71
- ROSS_WEEKLY = pd.DataFrame([
72
- {
73
- "Week": 0,
74
- "Day": 0,
75
- "Body Weight (kg/bird)": 0.044,
76
- "Daily Intake (g/bird/day)": None,
77
- "Cumulative Feed (kg/bird)": 0.000,
78
- "FCR": None,
79
  },
80
- {
81
- "Week": 1,
82
- "Day": 7,
83
- "Body Weight (kg/bird)": 0.213,
84
- "Daily Intake (g/bird/day)": 35,
85
- "Cumulative Feed (kg/bird)": 0.166,
86
- "FCR": 0.780,
87
  },
88
- {
89
- "Week": 2,
90
- "Day": 14,
91
- "Body Weight (kg/bird)": 0.533,
92
- "Daily Intake (g/bird/day)": 67,
93
- "Cumulative Feed (kg/bird)": 0.535,
94
- "FCR": 1.005,
95
  },
96
- {
97
- "Week": 3,
98
- "Day": 21,
99
- "Body Weight (kg/bird)": 1.046,
100
- "Daily Intake (g/bird/day)": 111,
101
- "Cumulative Feed (kg/bird)": 1.193,
102
- "FCR": 1.141,
103
  },
104
- {
105
- "Week": 4,
106
- "Day": 28,
107
- "Body Weight (kg/bird)": 1.697,
108
- "Daily Intake (g/bird/day)": 155,
109
- "Cumulative Feed (kg/bird)": 2.147,
110
- "FCR": 1.266,
111
  },
112
- {
113
- "Week": 5,
114
- "Day": 35,
115
- "Body Weight (kg/bird)": 2.441,
116
- "Daily Intake (g/bird/day)": 195,
117
- "Cumulative Feed (kg/bird)": 3.394,
118
- "FCR": 1.390,
119
  },
120
- {
121
- "Week": 6,
122
- "Day": 42,
123
- "Body Weight (kg/bird)": 3.222,
124
- "Daily Intake (g/bird/day)": 226,
125
- "Cumulative Feed (kg/bird)": 4.886,
126
- "FCR": 1.517,
127
  },
128
- {
129
- "Week": 7,
130
- "Day": 49,
131
- "Body Weight (kg/bird)": 3.991,
132
- "Daily Intake (g/bird/day)": 247,
133
- "Cumulative Feed (kg/bird)": 6.556,
134
- "FCR": 1.643,
135
  },
136
- {
137
- "Week": 8,
138
- "Day": 56,
139
- "Body Weight (kg/bird)": 4.714,
140
- "Daily Intake (g/bird/day)": 258,
141
- "Cumulative Feed (kg/bird)": 8.332,
142
- "FCR": 1.768,
143
  },
144
- ])
145
 
146
 
147
  # ============================================================
148
- # HELPER FUNCTIONS
149
  # ============================================================
150
 
151
  def clean_email(email):
152
- if not email:
 
153
  return ""
154
 
155
  email = str(email).strip().lower()
156
 
 
 
 
157
  pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
158
 
159
- if re.match(pattern, email):
160
- return email
161
 
162
- return ""
163
 
164
 
165
- def get_google_user(request: gr.Request):
166
- """
167
- Retrieve the Google OAuth user stored in the Starlette session.
168
- """
169
 
170
- if request is None:
171
- return None
 
 
172
 
173
  try:
174
- session = getattr(request, "session", None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
- if session is None and getattr(request, "request", None):
177
- session = getattr(request.request, "session", None)
 
 
 
 
 
178
 
179
- if not session:
180
- return None
181
 
182
- # Authlib session structure.
183
- oauth_info = session.get("user")
 
184
 
185
- if oauth_info:
186
- return oauth_info
187
 
188
- oauth_info = session.get("oauth_info")
 
 
 
 
 
 
 
 
189
 
190
- if oauth_info:
191
- return oauth_info.get("userinfo", oauth_info)
192
 
193
- except Exception:
194
- pass
195
 
196
- return None
197
 
 
198
 
199
- def get_logged_in_email(request: gr.Request):
200
- user = get_google_user(request)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
- if not user:
203
- return ""
 
 
 
 
 
 
 
 
 
204
 
205
- email = (
206
- user.get("email")
207
- if isinstance(user, dict)
208
- else ""
209
- )
210
 
211
- return clean_email(email)
 
 
212
 
213
 
214
- def post_to_webhook(payload):
215
  """
216
- Save lead/question to external Google Apps Script webhook.
217
-
218
- The app remains functional if the webhook is not configured.
219
  """
220
 
221
- if not LEADS_WEBHOOK_URL:
222
- return False
223
 
224
- try:
225
- response = requests.post(
226
- LEADS_WEBHOOK_URL,
227
- json=payload,
228
- timeout=10,
229
- )
230
 
231
- return response.ok
 
232
 
233
- except Exception:
234
- return False
235
 
 
 
236
 
237
- def save_lead(
238
- email,
239
- source="calculator",
240
- question="",
241
- birds=None,
242
- age_days=None,
243
- ):
244
- email = clean_email(email)
245
 
246
- if not email:
247
- return False
248
 
249
- payload = {
250
- "type": "lead",
251
- "email": email,
252
- "source": source,
253
- "question": question or "",
254
- "birds": birds,
255
- "age_days": age_days,
256
- "timestamp": datetime.now(
257
- timezone.utc
258
- ).isoformat(),
259
- }
260
 
261
- return post_to_webhook(payload)
262
 
 
263
 
264
- def save_question(
265
- email,
266
- question,
267
- birds=None,
268
- age_days=None,
269
- ):
270
- """
271
- Called automatically when Get Answer is clicked.
272
- """
273
 
274
- question = str(question or "").strip()
 
 
275
 
276
- if not question:
277
- return False
278
 
279
- payload = {
280
- "type": "farmer_question",
281
- "email": clean_email(email),
282
- "question": question,
283
- "birds": birds,
284
- "age_days": age_days,
285
- "timestamp": datetime.now(
286
- timezone.utc
287
- ).isoformat(),
288
- }
289
 
290
- return post_to_webhook(payload)
291
 
 
 
 
292
 
293
- def interpolate_benchmark(total_days):
 
 
 
 
 
 
294
  """
295
- Interpolate between Ross weekly checkpoints.
296
 
297
- Example:
298
- 45 days = between week 6 and week 7.
299
  """
300
 
301
- total_days = float(total_days)
 
 
 
 
 
 
302
 
303
  if total_days <= 0:
304
- row = ROSS_WEEKLY.iloc[0]
305
-
306
- return {
307
- "body_weight": float(row["Body Weight (kg/bird)"]),
308
- "cumulative_feed": float(row["Cumulative Feed (kg/bird)"]),
309
- "daily_intake": row["Daily Intake (g/bird/day)"],
310
- "fcr": row["FCR"],
311
- "week": 0,
312
- }
313
-
314
- if total_days >= 56:
315
- row = ROSS_WEEKLY.iloc[-1]
316
-
317
- return {
318
- "body_weight": float(row["Body Weight (kg/bird)"]),
319
- "cumulative_feed": float(row["Cumulative Feed (kg/bird)"]),
320
- "daily_intake": row["Daily Intake (g/bird/day)"],
321
- "fcr": row["FCR"],
322
- "week": 8,
323
- }
324
-
325
- for i in range(len(ROSS_WEEKLY) - 1):
326
-
327
- left = ROSS_WEEKLY.iloc[i]
328
- right = ROSS_WEEKLY.iloc[i + 1]
329
-
330
- left_day = float(left["Day"])
331
- right_day = float(right["Day"])
332
-
333
- if left_day <= total_days <= right_day:
334
-
335
- span = right_day - left_day
336
-
337
- if span == 0:
338
- ratio = 0
339
- else:
340
- ratio = (
341
- total_days - left_day
342
- ) / span
343
-
344
- def interp(a, b):
345
- return float(a) + (
346
- float(b) - float(a)
347
- ) * ratio
348
-
349
- body_weight = interp(
350
- left["Body Weight (kg/bird)"],
351
- right["Body Weight (kg/bird)"],
352
- )
353
 
354
- cumulative_feed = interp(
355
- left["Cumulative Feed (kg/bird)"],
356
- right["Cumulative Feed (kg/bird)"],
357
- )
358
 
359
- left_intake = left[
360
- "Daily Intake (g/bird/day)"
361
- ]
362
 
363
- right_intake = right[
364
- "Daily Intake (g/bird/day)"
365
- ]
366
 
367
- if pd.isna(left_intake):
368
- daily_intake = right_intake
369
- else:
370
- daily_intake = interp(
371
- left_intake,
372
- right_intake,
373
- )
374
 
375
- left_fcr = left["FCR"]
376
- right_fcr = right["FCR"]
 
 
377
 
378
- if pd.isna(left_fcr):
379
- fcr = right_fcr
380
- else:
381
- fcr = interp(
382
- left_fcr,
383
- right_fcr,
384
- )
385
 
386
- return {
387
- "body_weight": body_weight,
388
- "cumulative_feed": cumulative_feed,
389
- "daily_intake": daily_intake,
390
- "fcr": fcr,
391
- "week": total_days / 7,
392
- }
393
 
394
- return None
 
 
395
 
 
 
396
 
397
- # ============================================================
398
- # FEED PHASE CALCULATION
399
- # ============================================================
 
400
 
401
- def calculate_phase_feed(total_days, birds):
402
- """
403
- Starter is treated as feed through day 21.
404
- Finisher is feed after day 21.
405
 
406
- We derive each phase from the cumulative Ross benchmark.
407
- """
 
 
 
 
 
408
 
409
- benchmark = interpolate_benchmark(total_days)
 
 
410
 
411
- total_feed_per_bird = benchmark[
412
- "cumulative_feed"
413
- ]
414
 
415
- total_feed = (
416
- total_feed_per_bird * birds
417
  )
418
 
419
- starter_days = min(total_days, 21)
420
-
421
- starter_benchmark = interpolate_benchmark(
422
- starter_days
423
  )
424
 
425
- starter_per_bird = starter_benchmark[
426
- "cumulative_feed"
427
- ]
 
 
 
 
 
 
 
 
 
 
428
 
429
- starter_feed = (
430
- starter_per_bird * birds
 
 
 
 
 
431
  )
432
 
433
- finisher_feed = max(
434
  0,
435
- total_feed - starter_feed
436
  )
437
 
438
- return (
439
- starter_feed,
440
- finisher_feed,
441
- total_feed,
442
  )
443
 
 
 
 
 
444
 
445
- def allocate_phase_bags(
446
- total_bags,
447
- starter_feed,
448
- finisher_feed,
449
- ):
450
- """
451
- Allocate the already-rounded TOTAL bags
452
- between Starter and Finisher.
 
 
 
453
 
454
- This prevents the previous error where:
455
- ceil(Starter bags) + ceil(Finisher bags)
 
 
456
 
457
- could produce more bags than the actual total.
458
 
459
- The sum of Starter + Finisher ALWAYS equals total_bags.
460
- """
 
461
 
462
- total_phase_feed = (
463
- starter_feed + finisher_feed
464
  )
465
 
466
- if total_bags <= 0 or total_phase_feed <= 0:
467
- return 0, 0
468
-
469
- starter_share = (
470
- starter_feed / total_phase_feed
471
  )
472
 
473
- starter_bags = round(
474
- total_bags * starter_share
475
- )
 
 
476
 
477
- starter_bags = max(
478
  0,
479
- min(total_bags, starter_bags)
480
  )
481
 
482
- finisher_bags = (
483
- total_bags - starter_bags
 
484
  )
485
 
486
- # If Starter exists, make sure it receives
487
- # at least one bag when total feed reaches it.
488
- if starter_feed > 0 and total_bags >= 1:
489
- starter_bags = max(
490
- 1,
491
- starter_bags
492
- )
493
-
494
- starter_bags = min(
495
- starter_bags,
496
- total_bags
497
- )
498
-
499
- finisher_bags = (
500
- total_bags - starter_bags
501
- )
502
-
503
- return (
504
- starter_bags,
505
- finisher_bags,
506
  )
507
 
 
 
 
 
 
 
508
 
509
- # ============================================================
510
- # MAIN CALCULATOR
511
- # ============================================================
512
-
513
- def calculate(
514
- birds,
515
- weeks,
516
- days,
517
- bag_size,
518
- bag_price,
519
- email,
520
- consent,
521
- request: gr.Request = None,
522
- ):
523
- """
524
- Main calculator.
525
-
526
- Email is required before calculation.
527
- Google email is used automatically when available.
528
- """
529
 
530
- # --------------------------------------------------------
531
- # EMAIL / GOOGLE SIGN-IN
532
- # --------------------------------------------------------
533
 
534
- google_email = get_logged_in_email(request)
 
535
 
536
- typed_email = clean_email(email)
 
537
 
538
- final_email = (
539
- google_email
540
- if google_email
541
- else typed_email
542
- )
543
 
544
- if not final_email:
545
- return (
546
- "### 🔐 Email required\n\n"
547
- "Please enter your email address or "
548
- "use **Continue with Google** before "
549
- "calculating your feed requirement.",
550
- "",
551
- "",
552
- gr.update(),
553
- "⚠️ Please provide your email first.",
554
- )
555
 
556
- if not consent:
557
- return (
558
- "### 📩 One small step first\n\n"
559
- "Please tick the box confirming that "
560
- "you agree to receive farming tips and "
561
- "updates by email.",
562
- "",
563
- "",
564
- gr.update(value=final_email),
565
- "⚠️ Please confirm email consent.",
566
- )
567
 
568
- # --------------------------------------------------------
569
- # CLEAN INPUTS
570
- # --------------------------------------------------------
571
 
572
- try:
573
- birds = int(float(birds))
574
- except Exception:
575
- birds = 100
576
 
577
- birds = max(1, birds)
 
578
 
579
- try:
580
- weeks = int(float(weeks))
581
- except Exception:
582
- weeks = 6
583
 
584
- try:
585
- days = int(float(days))
586
- except Exception:
587
- days = 0
588
 
589
- weeks = max(0, min(8, weeks))
590
- days = max(0, min(6, days))
591
 
592
- total_days = (
593
- weeks * 7
594
- ) + days
595
 
596
- total_days = max(
597
- 1,
598
- min(56, total_days)
599
- )
600
 
601
- try:
602
- bag_size = float(bag_size)
603
- except Exception:
604
- bag_size = DEFAULT_BAG_SIZE
605
 
606
- bag_size = max(
607
- 1,
608
- bag_size
609
- )
610
 
611
- try:
612
- bag_price = float(bag_price)
613
- except Exception:
614
- bag_price = DEFAULT_BAG_PRICE
615
 
616
- bag_price = max(
617
- 0,
618
- bag_price
619
- )
620
 
621
- # --------------------------------------------------------
622
- # BENCHMARK
623
- # --------------------------------------------------------
 
624
 
625
- benchmark = interpolate_benchmark(
626
- total_days
627
- )
628
 
629
- body_weight = benchmark[
630
- "body_weight"
631
- ]
632
 
633
- cumulative_feed = benchmark[
634
- "cumulative_feed"
635
- ]
636
 
637
- daily_intake = benchmark[
638
- "daily_intake"
639
- ]
640
 
641
- fcr = benchmark[
642
- "fcr"
643
- ]
644
 
645
- # --------------------------------------------------------
646
- # FEED REQUIREMENT
647
- # --------------------------------------------------------
648
 
649
- (
650
- starter_feed,
651
- finisher_feed,
652
- benchmark_total_feed,
653
- ) = calculate_phase_feed(
654
- total_days,
655
- birds,
656
- )
657
 
658
- # Add practical allowance.
659
- adjusted_feed = (
660
- benchmark_total_feed
661
- * FEED_ALLOWANCE
662
- )
663
 
664
- adjusted_starter_feed = (
665
- starter_feed
666
- * FEED_ALLOWANCE
667
- )
668
 
669
- adjusted_finisher_feed = (
670
- finisher_feed
671
- * FEED_ALLOWANCE
672
- )
673
 
674
- # IMPORTANT:
675
- # Round ONLY after calculating the TOTAL.
676
- exact_bags = (
677
- adjusted_feed
678
- / bag_size
679
- )
680
 
681
- whole_bags = math.ceil(
682
- exact_bags
683
- )
684
 
685
- # Allocate those final bags between phases.
686
- starter_bags, finisher_bags = (
687
- allocate_phase_bags(
688
- whole_bags,
689
- adjusted_starter_feed,
690
- adjusted_finisher_feed,
691
- )
692
- )
693
 
694
- estimated_cost = (
695
- whole_bags
696
- * bag_price
697
- )
698
 
699
- expected_live_weight = (
700
- birds
701
- * body_weight
702
- )
703
 
704
  # --------------------------------------------------------
705
- # DISPLAY TEXT
706
  # --------------------------------------------------------
707
 
708
- age_text = (
709
- f"{weeks} week"
710
- f"{'s' if weeks != 1 else ''}"
711
- )
712
-
713
- if days > 0:
714
- age_text += (
715
- f" + {days} day"
716
- f"{'s' if days != 1 else ''}"
717
- )
718
-
719
- age_text_full = (
720
- f"{age_text} ({total_days} days)"
721
- )
722
-
723
- exact_text = (
724
- f"{exact_bags:.1f}"
725
- )
726
-
727
- summary = f"""
728
- # 🐔 Your feed requirement
729
 
730
- ## You will require approximately **{whole_bags} bags of {bag_size:g} kg feed**
731
 
732
- To raise **{birds:,} birds** to **{age_text_full}**.
733
 
734
  ### 🌾 Feed breakdown
735
 
736
- | Feed | Bags |
737
- |---|---:|
738
- | 🌱 Starter | **{starter_bags} bags** |
739
- | 🌽 Finisher | **{finisher_bags} bags** |
740
- | **TOTAL** | **{whole_bags} bags** |
741
 
742
- ### 💰 Estimated feed cost
743
 
744
- # **₦{estimated_cost:,.0f}**
745
 
746
- **Feed only.**
747
 
748
- Based on approximately **{exact_text} bags** before rounding up.
749
 
750
  ---
751
 
752
  ## 🎯 Quick answer
753
 
754
- **To raise {birds:,} birds for {total_days} days ({weeks} week{'s' if weeks != 1 else ''}), you will require an estimated {whole_bags} bags of {bag_size:g} kg feed ({starter_bags} Starter + {finisher_bags} Finisher), costing approximately ₦{estimated_cost:,.0f} on feed alone.**
755
 
756
- We have included a **20% practical allowance** above the Ross benchmark to give the farmer a safer planning estimate.
757
-
758
- Actual feed consumption can vary with genetics, sex, mortality, feed quality, temperature, management and farm conditions.
759
- """
760
-
761
- # --------------------------------------------------------
762
- # BENCHMARK OUTPUT
763
- # --------------------------------------------------------
764
-
765
- daily_intake_text = (
766
- "-"
767
- if pd.isna(daily_intake)
768
- else f"{float(daily_intake):.0f}"
769
- )
770
-
771
- fcr_text = (
772
- "-"
773
- if pd.isna(fcr)
774
- else f"{float(fcr):.3f}"
775
- )
776
 
777
- benchmark_text = f"""
778
  ## 📊 Ross 308 benchmark at {total_days} days
779
 
780
- - **Expected body weight:** {body_weight:.2f} kg/bird
781
- - **Expected flock live weight:** {expected_live_weight:,.1f} kg
782
- - **Cumulative benchmark feed:** {cumulative_feed:.3f} kg/bird
783
- - **Daily feed intake near this age:** {daily_intake_text} g/bird/day
784
- - **Benchmark FCR:** {fcr_text}
785
 
786
- ### How the estimate works
787
 
788
- Ross benchmark feed:
789
- **{benchmark_total_feed:,.1f} kg**
790
 
791
- Practical allowance:
792
- **+20%**
793
 
794
- Planning feed:
795
- **{adjusted_feed:,.1f} kg**
796
 
797
- Equivalent:
798
- **{exact_bags:.1f} bags**
 
 
 
 
 
 
 
 
 
799
 
800
- Rounded up:
801
- **{whole_bags} bags**
802
  """
803
 
804
- # --------------------------------------------------------
805
- # SAVE LEAD
806
- # --------------------------------------------------------
807
-
808
- saved = save_lead(
809
- email=final_email,
810
- source="feed_calculator",
811
- birds=birds,
812
- age_days=total_days,
813
- )
814
-
815
- if saved:
816
- status = (
817
- f"✅ Calculation complete. "
818
- f"Your email has been saved for "
819
- f"farming tips and updates."
820
- )
821
- else:
822
- status = (
823
- "✅ Calculation complete."
824
- )
825
-
826
- return (
827
- summary,
828
- benchmark_text,
829
- "",
830
- gr.update(
831
- value=final_email
832
- ),
833
- status,
834
- )
835
 
836
 
837
  # ============================================================
838
- # FARMER QUESTION ANSWER
839
  # ============================================================
840
 
841
- def simple_question_answer(question):
 
 
 
 
 
 
 
 
842
  """
843
- Fallback answer engine when OPENAI_API_KEY
844
- is not configured.
845
 
846
- Questions are still saved automatically.
 
847
  """
848
 
849
- q = question.lower().strip()
850
 
851
- if "bag" in q or "feed" in q:
852
  return (
853
- "Use the feed calculator above and select "
854
- "your number of birds, age in weeks + days, "
855
- "bag size and price. It will estimate the "
856
- "Starter and Finisher feed requirement and "
857
- "total feed cost."
858
  )
859
 
860
- if "water" in q:
861
- return (
862
- "Clean, safe drinking water is essential "
863
- "for broilers. Water quality and availability "
864
- "can strongly affect feed intake and bird "
865
- "performance."
 
866
  )
867
 
868
- if "weight" in q:
869
- return (
870
- "Expected weight varies with genetics, sex, "
871
- "nutrition, temperature and management. "
872
- "The calculator uses Ross 308 performance "
873
- "objectives as its numerical benchmark."
874
- )
875
 
876
- if "vaccin" in q:
877
  return (
878
- "Vaccination programs should follow the "
879
- "recommendation of your veterinarian and "
880
- "local poultry health program because disease "
881
- "risk varies by location and farm."
882
  )
883
 
884
- return (
885
- "Your question has been recorded. The app will "
886
- "use farmer questions like this to improve the "
887
- "answers available in future versions."
888
- )
889
 
 
890
 
891
- def ai_question_answer(question):
892
- """
893
- Optional OpenAI-powered answer.
 
 
 
894
 
895
- If OPENAI_API_KEY is not configured, use the
896
- built-in fallback answer.
897
- """
898
 
899
- if not OPENAI_API_KEY:
900
- return simple_question_answer(
901
- question
902
- )
903
 
904
- try:
905
- from openai import OpenAI
906
-
907
- client = OpenAI(
908
- api_key=OPENAI_API_KEY
 
 
909
  )
910
 
911
- response = client.responses.create(
912
- model="gpt-5-mini",
913
- input=[
914
- {
915
- "role": "system",
916
- "content": (
917
- "You are a practical poultry farming "
918
- "assistant for farmers in Nigeria. "
919
- "Give clear, simple and useful answers. "
920
- "Use metric units and Nigerian naira where "
921
- "appropriate. Do not invent veterinary "
922
- "instructions. If a question requires "
923
- "veterinary diagnosis or treatment, advise "
924
- "the farmer to consult a qualified poultry "
925
- "veterinarian. Keep answers farmer-friendly."
926
- ),
927
- },
928
- {
929
- "role": "user",
930
- "content": question,
931
- },
932
- ],
933
  )
934
 
935
- return response.output_text
936
 
937
- except Exception:
938
- return simple_question_answer(
939
- question
940
  )
941
 
 
942
 
943
- def answer_farmer_question(
944
- question,
 
 
 
 
 
 
945
  email,
946
- consent,
947
- birds,
948
- weeks,
949
- days,
950
- request: gr.Request = None,
951
  ):
952
  """
953
- IMPORTANT:
954
- Clicking GET ANSWER automatically saves the question.
 
955
  """
956
 
957
- question = str(
958
- question or ""
959
- ).strip()
960
-
961
- if not question:
962
- return (
963
- "Please type or speak your question first.",
964
- "⚠️ No question was entered.",
965
- )
966
-
967
- google_email = get_logged_in_email(
968
- request
969
- )
970
-
971
- final_email = (
972
- google_email
973
- or clean_email(email)
974
- )
975
 
976
- if not final_email:
977
- return (
978
- "### 🔐 Email required\n\n"
979
- "Please enter your email or use "
980
- "**Continue with Google** first.",
981
- "⚠️ Please provide your email first.",
982
- )
983
 
984
- if not consent:
985
- return (
986
- "### 📩 Almost there\n\n"
987
- "Please confirm that you agree to receive "
988
- "farming tips and updates by email.",
989
- "⚠️ Please confirm email consent.",
990
- )
991
 
992
- try:
993
- total_days = (
994
- int(weeks) * 7
995
- + int(days)
996
- )
997
- except Exception:
998
- total_days = 0
999
 
1000
- # SAVE QUESTION FIRST.
1001
- saved = save_question(
1002
- email=final_email,
1003
  question=question,
1004
- birds=birds,
1005
- age_days=total_days,
1006
- )
1007
-
1008
- # Answer after saving.
1009
- answer = ai_question_answer(
1010
- question
1011
- )
1012
-
1013
- if saved:
1014
- status = (
1015
- "✅ Question saved automatically. "
1016
- "Thank you — this helps us understand "
1017
- "what farmers need."
1018
- )
1019
- else:
1020
- status = (
1021
- "✅ Answer generated. "
1022
- "The question was also processed for "
1023
- "future improvements."
1024
  )
1025
 
1026
- return (
1027
- f"## 🤖 Answer\n\n{answer}",
1028
- status,
1029
- )
1030
 
1031
 
1032
  # ============================================================
1033
- # GOOGLE OAUTH
1034
  # ============================================================
1035
 
1036
- oauth = OAuth(
1037
- Config(
1038
- environ={
1039
- "GOOGLE_CLIENT_ID": GOOGLE_CLIENT_ID,
1040
- "GOOGLE_CLIENT_SECRET": GOOGLE_CLIENT_SECRET,
1041
- }
1042
- )
1043
- )
1044
 
1045
- if GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
 
 
 
 
1046
 
1047
- oauth.register(
1048
- name="google",
1049
- server_metadata_url=(
1050
- "https://accounts.google.com/"
1051
- ".well-known/openid-configuration"
1052
- ),
1053
- client_kwargs={
1054
- "scope": (
1055
- "openid email profile"
1056
- )
1057
- },
1058
  )
1059
 
1060
 
1061
- # ============================================================
1062
- # FASTAPI APP
1063
- # ============================================================
1064
-
1065
- fastapi_app = FastAPI()
1066
 
1067
- fastapi_app.add_middleware(
1068
- SessionMiddleware,
1069
- secret_key=SESSION_SECRET,
1070
- same_site="lax",
1071
- https_only=True,
1072
- )
1073
 
 
 
 
 
1074
 
1075
- @fastapi_app.get("/login")
1076
- async def google_login(request: Request):
1077
 
1078
- if not (
1079
- GOOGLE_CLIENT_ID
1080
- and GOOGLE_CLIENT_SECRET
1081
- ):
1082
- return RedirectResponse(
1083
- url="/"
1084
- )
1085
-
1086
- redirect_uri = (
1087
- SPACE_URL
1088
- + "/auth"
1089
- )
1090
 
1091
- return await oauth.google.authorize_redirect(
1092
- request,
1093
- redirect_uri,
1094
- )
1095
 
 
1096
 
1097
- @fastapi_app.get("/auth")
1098
- async def google_auth(request: Request):
1099
 
1100
- if not (
1101
- GOOGLE_CLIENT_ID
1102
- and GOOGLE_CLIENT_SECRET
1103
- ):
1104
- return RedirectResponse(
1105
- url="/"
1106
- )
 
 
 
 
1107
 
1108
  try:
1109
-
1110
- token = await oauth.google.authorize_access_token(
1111
- request
1112
- )
1113
-
1114
- userinfo = dict(
1115
- token.get("userinfo", {})
1116
  )
1117
 
1118
- request.session[
1119
- "user"
1120
- ] = userinfo
1121
-
1122
- request.session[
1123
- "oauth_info"
1124
- ] = {
1125
- "userinfo": userinfo
1126
- }
1127
-
1128
- except OAuthError:
1129
 
1130
- return RedirectResponse(
1131
- url="/"
 
1132
  )
1133
 
1134
- return RedirectResponse(
1135
- url="/"
1136
- )
1137
-
1138
-
1139
- @fastapi_app.get("/logout")
1140
- async def logout(request: Request):
1141
-
1142
- request.session.clear()
1143
-
1144
- return RedirectResponse(
1145
- url="/"
1146
  )
1147
 
1148
 
1149
  # ============================================================
1150
- # GRADIO UI
1151
  # ============================================================
1152
 
1153
- with gr.Blocks(
1154
- title=APP_NAME,
1155
- theme=gr.themes.Soft(),
1156
- ) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1157
 
1158
  gr.Markdown(
1159
  """
@@ -1164,75 +849,50 @@ with gr.Blocks(
1164
  Choose the number of birds, age, feed bag size and price —
1165
  **no calculations required.**
1166
 
1167
- The calculator converts **weeks + days into total days**
1168
- and estimates the feed required to raise your birds.
1169
  """
1170
  )
1171
 
1172
- # --------------------------------------------------------
1173
- # EMAIL / SIGN-IN
1174
- # --------------------------------------------------------
1175
 
1176
- with gr.Group():
1177
 
1178
  gr.Markdown(
1179
  """
1180
- ## 🔐 Before you calculate
1181
 
1182
- Enter your email address so we can send you useful
1183
- poultry-farming tips, updates and new tools.
1184
 
1185
- You can type your email **or sign in with Google**.
1186
  """
1187
  )
1188
 
1189
- with gr.Row():
1190
-
1191
- email = gr.Textbox(
1192
- label="📧 Email address",
1193
- placeholder="farmer@example.com",
1194
- type="email",
1195
- )
1196
-
1197
- if GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
1198
-
1199
- google_btn = gr.Button(
1200
- "🔵 Continue with Google",
1201
- link="/login",
1202
- )
1203
-
1204
- else:
1205
-
1206
- gr.Markdown(
1207
- """
1208
- **Google Sign-In will appear once Google OAuth
1209
- credentials are configured in the Space Secrets.**
1210
- """
1211
- )
1212
-
1213
- consent = gr.Checkbox(
1214
- label=(
1215
- "Yes, I agree to receive poultry farming "
1216
- "tips, useful updates and new tools by email."
1217
- ),
1218
- value=False,
1219
  )
1220
 
1221
- # --------------------------------------------------------
1222
- # CALCULATOR
1223
- # --------------------------------------------------------
1224
 
1225
  with gr.Row():
1226
 
1227
- with gr.Column(
1228
- scale=1
1229
- ):
 
 
1230
 
1231
  gr.Markdown(
1232
  "## 🧮 Farm inputs"
1233
  )
1234
 
1235
- birds = gr.Dropdown(
1236
  label="🐔 Number of birds",
1237
  choices=[
1238
  "25",
@@ -1242,7 +902,7 @@ credentials are configured in the Space Secrets.**
1242
  "150",
1243
  "200",
1244
  "500",
1245
- "1000",
1246
  "Custom",
1247
  ],
1248
  value="25",
@@ -1250,42 +910,21 @@ credentials are configured in the Space Secrets.**
1250
 
1251
  custom_birds = gr.Number(
1252
  label="Custom number of birds",
 
1253
  minimum=1,
1254
  precision=0,
1255
- value=25,
1256
  visible=False,
1257
  )
1258
 
1259
- def show_custom_birds(value):
1260
-
1261
- if value == "Custom":
1262
- return gr.update(
1263
- visible=True
1264
- )
1265
-
1266
- return gr.update(
1267
- visible=False
1268
- )
1269
-
1270
- birds.change(
1271
- show_custom_birds,
1272
- inputs=birds,
1273
- outputs=custom_birds,
1274
- )
1275
-
1276
  weeks = gr.Dropdown(
1277
  label="📅 Age — Weeks",
1278
- choices=list(
1279
- range(0, 9)
1280
- ),
1281
- value=6,
1282
  )
1283
 
1284
- days = gr.Dropdown(
1285
  label="📅 Age — Days",
1286
- choices=list(
1287
- range(0, 7)
1288
- ),
1289
  value=0,
1290
  )
1291
 
@@ -1295,156 +934,53 @@ credentials are configured in the Space Secrets.**
1295
  10,
1296
  25,
1297
  50,
1298
- 70,
1299
- "Custom",
1300
  ],
1301
  value=25,
1302
  )
1303
 
1304
- custom_bag_size = gr.Number(
1305
- label="Custom bag size (kg)",
1306
- minimum=1,
1307
- value=25,
1308
- visible=False,
1309
- )
1310
-
1311
- def show_custom_bag(value):
1312
-
1313
- if value == "Custom":
1314
- return gr.update(
1315
- visible=True
1316
- )
1317
-
1318
- return gr.update(
1319
- visible=False
1320
- )
1321
-
1322
- bag_size.change(
1323
- show_custom_bag,
1324
- inputs=bag_size,
1325
- outputs=custom_bag_size,
1326
- )
1327
-
1328
- bag_price = gr.Number(
1329
  label="💰 Price per bag (₦)",
 
1330
  minimum=0,
1331
- value=DEFAULT_BAG_PRICE,
1332
- )
1333
-
1334
- calculate_btn = gr.Button(
1335
- "🐔 Calculate Feed Requirement",
1336
- variant="primary",
1337
- size="lg",
1338
  )
1339
 
1340
  # ----------------------------------------------------
1341
- # RESULTS
1342
  # ----------------------------------------------------
1343
 
1344
  with gr.Column(
1345
- scale=2
1346
  ):
1347
 
1348
- summary = gr.Markdown()
1349
-
1350
- benchmark = gr.Markdown()
1351
-
1352
- comparison = gr.Markdown()
1353
-
1354
- calculation_status = gr.Markdown()
1355
-
1356
- # --------------------------------------------------------
1357
- # CALCULATION WRAPPER
1358
- # --------------------------------------------------------
1359
-
1360
- def run_calculation(
1361
- birds_value,
1362
- custom_birds_value,
1363
- weeks_value,
1364
- days_value,
1365
- bag_value,
1366
- custom_bag_value,
1367
- bag_price_value,
1368
- email_value,
1369
- consent_value,
1370
- request=None,
1371
- ):
1372
-
1373
- if birds_value == "Custom":
1374
-
1375
- actual_birds = (
1376
- custom_birds_value
1377
- )
1378
-
1379
- else:
1380
-
1381
- actual_birds = (
1382
- birds_value
1383
- )
1384
-
1385
- if bag_value == "Custom":
1386
-
1387
- actual_bag_size = (
1388
- custom_bag_value
1389
  )
1390
 
1391
- else:
 
 
1392
 
1393
- actual_bag_size = (
1394
- bag_value
 
1395
  )
1396
 
1397
- return calculate(
1398
- actual_birds,
1399
- weeks_value,
1400
- days_value,
1401
- actual_bag_size,
1402
- bag_price_value,
1403
- email_value,
1404
- consent_value,
1405
- request,
1406
- )
1407
-
1408
- calculate_btn.click(
1409
- fn=run_calculation,
1410
- inputs=[
1411
- birds,
1412
- custom_birds,
1413
- weeks,
1414
- days,
1415
- bag_size,
1416
- custom_bag_size,
1417
- bag_price,
1418
- email,
1419
- consent,
1420
- ],
1421
- outputs=[
1422
- summary,
1423
- benchmark,
1424
- comparison,
1425
- email,
1426
- calculation_status,
1427
- ],
1428
- api_name="calculate_feed",
1429
- )
1430
 
1431
- # --------------------------------------------------------
1432
- # ASK A QUESTION
1433
- # --------------------------------------------------------
1434
 
1435
  gr.Markdown(
1436
  """
1437
- ---
1438
-
1439
  # ❓ Ask a question
1440
 
1441
  ### What would you like to know about raising your birds?
1442
 
1443
- Type your question or use the microphone.
1444
 
1445
- Questions are automatically saved when you click
1446
- **Get Answer**. This helps us understand what farmers
1447
- want to know and improve future versions of the app.
1448
  """
1449
  )
1450
 
@@ -1452,289 +988,155 @@ want to know and improve future versions of the app.
1452
  label="Your question",
1453
  placeholder=(
1454
  "Example: How many bags of feed do I need "
1455
- "for 100 broilers to 8 weeks?"
1456
  ),
1457
  lines=4,
1458
  )
1459
 
1460
  gr.Markdown(
1461
- "**🎤 You can also speak your question:**"
1462
- )
1463
-
1464
- question_audio = gr.Audio(
1465
- sources=["microphone"],
1466
- type="filepath",
1467
- label="Speak your question",
 
 
 
 
 
 
 
1468
  )
1469
 
1470
- def transcribe_question(
1471
- audio,
1472
- current_question,
1473
- ):
1474
-
1475
- if not audio:
1476
- return current_question
1477
-
1478
- try:
1479
-
1480
- from openai import OpenAI
1481
-
1482
- if not OPENAI_API_KEY:
1483
- return current_question
1484
-
1485
- client = OpenAI(
1486
- api_key=OPENAI_API_KEY
1487
- )
1488
-
1489
- with open(
1490
- audio,
1491
- "rb"
1492
- ) as audio_file:
1493
 
1494
- transcription = (
1495
- client.audio.transcriptions.create(
1496
- model="gpt-4o-mini-transcribe",
1497
- file=audio_file,
1498
- )
1499
- )
1500
-
1501
- return transcription.text
1502
-
1503
- except Exception:
1504
-
1505
- return current_question
1506
-
1507
- question_audio.stop_recording(
1508
- fn=transcribe_question,
1509
- inputs=[
1510
- question_audio,
1511
- question,
1512
- ],
1513
- outputs=question,
1514
  )
1515
 
1516
- with gr.Row():
1517
 
1518
- get_answer_btn = gr.Button(
1519
- "🤖 Get Answer",
1520
- variant="primary",
1521
- size="lg",
1522
- )
1523
 
1524
- clear_question_btn = gr.Button(
1525
- "Clear",
1526
- variant="secondary",
1527
- )
1528
 
1529
- question_answer = gr.Markdown()
 
 
1530
 
1531
- question_status = gr.Markdown()
 
 
 
 
1532
 
1533
- get_answer_btn.click(
1534
- fn=answer_farmer_question,
1535
  inputs=[
1536
- question,
1537
  email,
1538
- consent,
1539
- birds,
1540
  weeks,
1541
- days,
 
 
 
1542
  ],
1543
  outputs=[
1544
- question_answer,
1545
  question_status,
1546
  ],
1547
- api_name="ask_farmer_question",
1548
  )
1549
 
1550
- clear_question_btn.click(
1551
- fn=lambda: (
1552
- "",
1553
- "",
1554
- "",
1555
- ),
1556
- inputs=None,
1557
- outputs=[
1558
  question,
1559
- question_answer,
 
1560
  question_status,
1561
  ],
1562
  )
1563
 
1564
- # --------------------------------------------------------
1565
- # ROSS BENCHMARK TABLE
1566
- # --------------------------------------------------------
1567
-
1568
- gr.Markdown(
1569
- """
1570
- ---
1571
-
1572
- ## 📊 Ross 308 weekly benchmark
1573
-
1574
- These figures are the numerical benchmark used by the
1575
- calculator.
1576
- """
1577
- )
1578
-
1579
- benchmark_display = ROSS_WEEKLY.copy()
1580
-
1581
- benchmark_display[
1582
- "Body Weight (kg/bird)"
1583
- ] = benchmark_display[
1584
- "Body Weight (kg/bird)"
1585
- ].map(
1586
- lambda x: f"{x:.3f}"
1587
- )
1588
-
1589
- benchmark_display[
1590
- "Cumulative Feed (kg/bird)"
1591
- ] = benchmark_display[
1592
- "Cumulative Feed (kg/bird)"
1593
- ].map(
1594
- lambda x: f"{x:.3f}"
1595
- )
1596
-
1597
- benchmark_display[
1598
- "Daily Intake (g/bird/day)"
1599
- ] = benchmark_display[
1600
- "Daily Intake (g/bird/day)"
1601
- ].map(
1602
- lambda x:
1603
- "-"
1604
- if pd.isna(x)
1605
- else f"{int(x)}"
1606
- )
1607
-
1608
- benchmark_display[
1609
- "FCR"
1610
- ] = benchmark_display[
1611
- "FCR"
1612
- ].map(
1613
- lambda x:
1614
- "-"
1615
- if pd.isna(x)
1616
- else f"{x:.3f}"
1617
- )
1618
-
1619
- gr.Dataframe(
1620
- value=benchmark_display,
1621
- interactive=False,
1622
- wrap=True,
1623
- )
1624
-
1625
- # --------------------------------------------------------
1626
- # NIGERIA MANAGEMENT REFERENCE
1627
- # --------------------------------------------------------
1628
 
1629
  gr.Markdown(
1630
  """
1631
  ---
1632
 
1633
- ## 🇳🇬 Nigeria management reference
1634
-
1635
- ### 🌡️ Brooding
1636
-
1637
- Start warming the brooding area 24–48 hours before
1638
- chick arrival.
1639
-
1640
- Initial chick-level temperature:
1641
-
1642
- **31–33°C**
1643
-
1644
- Temperature should be reduced progressively toward
1645
- approximately **21°C by day 28**.
1646
-
1647
- ### 💧 Water
1648
-
1649
- Use clean, tested drinking water.
1650
 
1651
- Reference pH:
1652
 
1653
- **5.5–7.5**
 
 
 
 
 
 
1654
 
1655
- Avoid supplying excessively warm water.
1656
 
1657
- ### 🐔 Stocking density
1658
 
1659
- A practical reference is approximately:
1660
 
1661
- **25 kg live weight/m²**
1662
 
1663
- at slaughter for hot Nigerian conditions.
1664
 
1665
- Actual stocking density should take account of housing,
1666
- ventilation and climate.
1667
 
1668
  ---
1669
 
1670
- ### ⚠️ Important
1671
-
1672
- Ross performance objectives are used as the numerical
1673
- benchmark.
1674
 
1675
- Actual farm performance can differ because of genetics,
1676
- sex, mortality, feed quality, temperature, management,
1677
- water quality and other farm conditions.
1678
 
1679
- This application is a planning and calculation tool.
1680
- It is **not veterinary advice**.
1681
- """
1682
- )
1683
-
1684
- # --------------------------------------------------------
1685
- # SOURCES
1686
- # --------------------------------------------------------
1687
 
1688
- gr.Markdown(
1689
- """
1690
  ---
1691
 
1692
- ### 📚 References
1693
-
1694
- **Numerical benchmark:**
1695
- Aviagen — Ross 308 / Ross 308 FF Broiler Performance
1696
- Objectives.
1697
-
1698
- **Nigeria management reference:**
1699
- Agrited — *Everything You Need To Know About Raising
1700
- Excellent Broiler Chickens in Nigeria*.
1701
 
1702
- The Ross performance objectives themselves note that
1703
- actual performance may be lower because of local factors
1704
- such as raw-material availability, climate and production
1705
- conditions. :contentReference[oaicite:2]{index=2}
1706
  """
1707
  )
1708
 
1709
 
1710
  # ============================================================
1711
- # MOUNT GRADIO
1712
- # ============================================================
1713
-
1714
- fastapi_app = gr.mount_gradio_app(
1715
- fastapi_app,
1716
- demo,
1717
- path="/",
1718
- )
1719
-
1720
-
1721
  # ============================================================
1722
- # START
 
 
 
 
 
1723
  # ============================================================
1724
 
1725
  if __name__ == "__main__":
1726
-
1727
- import uvicorn
1728
-
1729
- port = int(
1730
- os.getenv(
1731
- "PORT",
1732
- "7860"
1733
- )
1734
- )
1735
-
1736
- uvicorn.run(
1737
- fastapi_app,
1738
- host="0.0.0.0",
1739
- port=port,
1740
  )
 
1
+ import csv
2
  import math
3
+ import os
4
  import re
5
+ from datetime import datetime
 
6
 
 
 
7
  import gradio as gr
8
 
 
 
 
 
 
 
 
9
 
10
  # ============================================================
11
+ # APP CONFIGURATION
12
  # ============================================================
13
 
14
+ APP_TITLE = "🐔 PoultryFeedCalc"
15
 
16
+ LEADS_FILE = "farmer_leads.csv"
17
+ QUESTIONS_FILE = "farmer_questions.csv"
18
 
 
 
 
 
 
 
19
 
20
+ # ============================================================
21
+ # ROSS 308 BROILER BENCHMARK
22
+ # ============================================================
23
  #
24
+ # These are benchmark estimates used by the calculator.
25
+ # The app interpolates between weekly checkpoints so that
26
+ # weeks + days can be calculated as exact total days.
27
  #
28
+ # Feed figures are cumulative feed consumption per bird.
 
29
  #
30
+ # Starter = feed through day 21
31
+ # Finisher = feed after day 21
32
+ #
33
+ # IMPORTANT:
34
+ # These are planning estimates, not a guarantee of actual
35
+ # farm consumption.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  # ============================================================
37
 
38
+ ROSS_BENCHMARK = {
39
+ 0: {
40
+ "body_weight": 0.044,
41
+ "cumulative_feed": 0.000,
 
 
 
 
42
  },
43
+ 7: {
44
+ "body_weight": 0.213,
45
+ "cumulative_feed": 0.180,
 
 
 
 
46
  },
47
+ 14: {
48
+ "body_weight": 0.526,
49
+ "cumulative_feed": 0.690,
 
 
 
 
50
  },
51
+ 21: {
52
+ "body_weight": 1.087,
53
+ "cumulative_feed": 1.410,
 
 
 
 
54
  },
55
+ 28: {
56
+ "body_weight": 1.697,
57
+ "cumulative_feed": 2.147,
 
 
 
 
58
  },
59
+ 35: {
60
+ "body_weight": 2.440,
61
+ "cumulative_feed": 3.390,
 
 
 
 
62
  },
63
+ 42: {
64
+ "body_weight": 3.220,
65
+ "cumulative_feed": 4.890,
 
 
 
 
66
  },
67
+ 49: {
68
+ "body_weight": 4.020,
69
+ "cumulative_feed": 6.580,
 
 
 
 
70
  },
71
+ 56: {
72
+ "body_weight": 4.800,
73
+ "cumulative_feed": 8.330,
 
 
 
 
74
  },
75
+ }
76
 
77
 
78
  # ============================================================
79
+ # GENERAL HELPERS
80
  # ============================================================
81
 
82
  def clean_email(email):
83
+ """Clean and validate an email address."""
84
+ if email is None:
85
  return ""
86
 
87
  email = str(email).strip().lower()
88
 
89
+ if not email:
90
+ return ""
91
+
92
  pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
93
 
94
+ if not re.match(pattern, email):
95
+ return ""
96
 
97
+ return email
98
 
99
 
100
+ def save_lead(email):
101
+ """Save farmer email to the local mailing-list CSV."""
102
+ email = clean_email(email)
 
103
 
104
+ if not email:
105
+ return False
106
+
107
+ file_exists = os.path.exists(LEADS_FILE)
108
 
109
  try:
110
+ with open(
111
+ LEADS_FILE,
112
+ "a",
113
+ newline="",
114
+ encoding="utf-8",
115
+ ) as f:
116
+
117
+ writer = csv.writer(f)
118
+
119
+ if not file_exists:
120
+ writer.writerow(
121
+ [
122
+ "email",
123
+ "date",
124
+ "source",
125
+ ]
126
+ )
127
 
128
+ writer.writerow(
129
+ [
130
+ email,
131
+ datetime.now().isoformat(timespec="seconds"),
132
+ "PoultryFeedCalc",
133
+ ]
134
+ )
135
 
136
+ return True
 
137
 
138
+ except Exception as e:
139
+ print("Lead save error:", e)
140
+ return False
141
 
 
 
142
 
143
+ def save_question(
144
+ email,
145
+ question,
146
+ birds=None,
147
+ total_days=None,
148
+ bag_size=None,
149
+ price=None,
150
+ ):
151
+ """Save farmer question for future product development."""
152
 
153
+ question = (question or "").strip()
 
154
 
155
+ if not question:
156
+ return False
157
 
158
+ email = clean_email(email)
159
 
160
+ file_exists = os.path.exists(QUESTIONS_FILE)
161
 
162
+ try:
163
+ with open(
164
+ QUESTIONS_FILE,
165
+ "a",
166
+ newline="",
167
+ encoding="utf-8",
168
+ ) as f:
169
+
170
+ writer = csv.writer(f)
171
+
172
+ if not file_exists:
173
+ writer.writerow(
174
+ [
175
+ "date",
176
+ "email",
177
+ "question",
178
+ "birds",
179
+ "age_days",
180
+ "bag_size_kg",
181
+ "price_per_bag",
182
+ ]
183
+ )
184
 
185
+ writer.writerow(
186
+ [
187
+ datetime.now().isoformat(timespec="seconds"),
188
+ email,
189
+ question,
190
+ birds if birds is not None else "",
191
+ total_days if total_days is not None else "",
192
+ bag_size if bag_size is not None else "",
193
+ price if price is not None else "",
194
+ ]
195
+ )
196
 
197
+ return True
 
 
 
 
198
 
199
+ except Exception as e:
200
+ print("Question save error:", e)
201
+ return False
202
 
203
 
204
+ def interpolate(day, key):
205
  """
206
+ Linearly interpolate a benchmark value between
207
+ the nearest weekly checkpoints.
 
208
  """
209
 
210
+ days = sorted(ROSS_BENCHMARK.keys())
 
211
 
212
+ if day <= days[0]:
213
+ return ROSS_BENCHMARK[days[0]][key]
 
 
 
 
214
 
215
+ if day >= days[-1]:
216
+ return ROSS_BENCHMARK[days[-1]][key]
217
 
218
+ for i in range(len(days) - 1):
 
219
 
220
+ d1 = days[i]
221
+ d2 = days[i + 1]
222
 
223
+ if d1 <= day <= d2:
 
 
 
 
 
 
 
224
 
225
+ v1 = ROSS_BENCHMARK[d1][key]
226
+ v2 = ROSS_BENCHMARK[d2][key]
227
 
228
+ fraction = (day - d1) / (d2 - d1)
 
 
 
 
 
 
 
 
 
 
229
 
230
+ return v1 + (v2 - v1) * fraction
231
 
232
+ return ROSS_BENCHMARK[days[-1]][key]
233
 
 
 
 
 
 
 
 
 
 
234
 
235
+ def format_naira(amount):
236
+ """Format Nigerian Naira."""
237
+ return f"₦{amount:,.0f}"
238
 
 
 
239
 
240
+ def format_number(value, decimals=1):
241
+ return f"{value:,.{decimals}f}"
 
 
 
 
 
 
 
 
242
 
 
243
 
244
+ # ============================================================
245
+ # FEED CALCULATION
246
+ # ============================================================
247
 
248
+ def calculate_feed(
249
+ birds,
250
+ weeks,
251
+ extra_days,
252
+ bag_size,
253
+ price_per_bag,
254
+ ):
255
  """
256
+ Main feed calculator.
257
 
258
+ Returns a dictionary containing all calculated values.
 
259
  """
260
 
261
+ birds = int(birds)
262
+ weeks = int(weeks)
263
+ extra_days = int(extra_days)
264
+ bag_size = float(bag_size)
265
+ price_per_bag = float(price_per_bag)
266
+
267
+ total_days = (weeks * 7) + extra_days
268
 
269
  if total_days <= 0:
270
+ raise ValueError("Age must be at least 1 day.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
+ if birds <= 0:
273
+ raise ValueError("Number of birds must be greater than zero.")
 
 
274
 
275
+ if bag_size <= 0:
276
+ raise ValueError("Feed bag size must be greater than zero.")
 
277
 
278
+ if price_per_bag < 0:
279
+ raise ValueError("Price per bag cannot be negative.")
 
280
 
281
+ # --------------------------------------------------------
282
+ # CUMULATIVE FEED PER BIRD
283
+ # --------------------------------------------------------
 
 
 
 
284
 
285
+ cumulative_feed_per_bird = interpolate(
286
+ total_days,
287
+ "cumulative_feed",
288
+ )
289
 
290
+ body_weight_per_bird = interpolate(
291
+ total_days,
292
+ "body_weight",
293
+ )
 
 
 
294
 
295
+ total_feed_kg = (
296
+ cumulative_feed_per_bird * birds
297
+ )
 
 
 
 
298
 
299
+ # --------------------------------------------------------
300
+ # STARTER / FINISHER SPLIT
301
+ # --------------------------------------------------------
302
 
303
+ # Starter feed is estimated through day 21.
304
+ starter_cutoff = min(total_days, 21)
305
 
306
+ starter_feed_per_bird = interpolate(
307
+ starter_cutoff,
308
+ "cumulative_feed",
309
+ )
310
 
311
+ starter_total_kg = (
312
+ starter_feed_per_bird * birds
313
+ )
 
314
 
315
+ # If the flock is older than 21 days,
316
+ # everything above the day-21 cumulative figure
317
+ # becomes finisher.
318
+ finisher_total_kg = max(
319
+ 0,
320
+ total_feed_kg - starter_total_kg,
321
+ )
322
 
323
+ # --------------------------------------------------------
324
+ # BAG CALCULATIONS
325
+ # --------------------------------------------------------
326
 
327
+ exact_total_bags = total_feed_kg / bag_size
 
 
328
 
329
+ exact_starter_bags = (
330
+ starter_total_kg / bag_size
331
  )
332
 
333
+ exact_finisher_bags = (
334
+ finisher_total_kg / bag_size
 
 
335
  )
336
 
337
+ # Whole bags to buy.
338
+ #
339
+ # IMPORTANT:
340
+ # We calculate total required bags from total kg
341
+ # and round THAT total upward.
342
+ #
343
+ # Example:
344
+ # 145 kg / 25 kg = 5.8 bags
345
+ # => 6 bags
346
+ #
347
+ whole_total_bags = math.ceil(
348
+ exact_total_bags
349
+ )
350
 
351
+ # Split purchases between starter and finisher.
352
+ #
353
+ # Starter bags are rounded up, then finisher bags
354
+ # are adjusted so that the combined number of bags
355
+ # never exceeds the total number needed.
356
+ starter_bags_to_buy = math.ceil(
357
+ exact_starter_bags
358
  )
359
 
360
+ remaining_bags = max(
361
  0,
362
+ whole_total_bags - starter_bags_to_buy,
363
  )
364
 
365
+ # Finisher cannot exceed its actual required quantity.
366
+ finisher_bags_needed = math.ceil(
367
+ exact_finisher_bags
 
368
  )
369
 
370
+ finisher_bags_to_buy = min(
371
+ finisher_bags_needed,
372
+ remaining_bags,
373
+ )
374
 
375
+ # If rounding the starter portion consumes too many
376
+ # bags relative to the total, correct it.
377
+ #
378
+ # This keeps:
379
+ #
380
+ # starter + finisher <= total bags
381
+ #
382
+ total_split_bags = (
383
+ starter_bags_to_buy
384
+ + finisher_bags_to_buy
385
+ )
386
 
387
+ if total_split_bags < whole_total_bags:
388
+ additional = (
389
+ whole_total_bags - total_split_bags
390
+ )
391
 
392
+ finisher_bags_to_buy += additional
393
 
394
+ # --------------------------------------------------------
395
+ # COST
396
+ # --------------------------------------------------------
397
 
398
+ estimated_cost = (
399
+ whole_total_bags * price_per_bag
400
  )
401
 
402
+ flock_live_weight = (
403
+ body_weight_per_bird * birds
 
 
 
404
  )
405
 
406
+ # Approximate daily feed intake at this age.
407
+ #
408
+ # Difference between cumulative feed at current
409
+ # day and previous day.
410
+ # --------------------------------------------------------
411
 
412
+ previous_day = max(
413
  0,
414
+ total_days - 1,
415
  )
416
 
417
+ previous_feed = interpolate(
418
+ previous_day,
419
+ "cumulative_feed",
420
  )
421
 
422
+ daily_feed_per_bird = max(
423
+ 0,
424
+ cumulative_feed_per_bird
425
+ - previous_feed,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  )
427
 
428
+ benchmark_fcr = (
429
+ cumulative_feed_per_bird
430
+ / body_weight_per_bird
431
+ if body_weight_per_bird > 0
432
+ else 0
433
+ )
434
 
435
+ return {
436
+ "birds": birds,
437
+ "weeks": weeks,
438
+ "extra_days": extra_days,
439
+ "total_days": total_days,
440
+ "bag_size": bag_size,
441
+ "price_per_bag": price_per_bag,
 
 
 
 
 
 
 
 
 
 
 
 
 
442
 
443
+ "body_weight_per_bird":
444
+ body_weight_per_bird,
 
445
 
446
+ "cumulative_feed_per_bird":
447
+ cumulative_feed_per_bird,
448
 
449
+ "total_feed_kg":
450
+ total_feed_kg,
451
 
452
+ "starter_total_kg":
453
+ starter_total_kg,
 
 
 
454
 
455
+ "finisher_total_kg":
456
+ finisher_total_kg,
 
 
 
 
 
 
 
 
 
457
 
458
+ "exact_total_bags":
459
+ exact_total_bags,
 
 
 
 
 
 
 
 
 
460
 
461
+ "exact_starter_bags":
462
+ exact_starter_bags,
 
463
 
464
+ "exact_finisher_bags":
465
+ exact_finisher_bags,
 
 
466
 
467
+ "whole_total_bags":
468
+ whole_total_bags,
469
 
470
+ "starter_bags_to_buy":
471
+ starter_bags_to_buy,
 
 
472
 
473
+ "finisher_bags_to_buy":
474
+ finisher_bags_to_buy,
 
 
475
 
476
+ "estimated_cost":
477
+ estimated_cost,
478
 
479
+ "flock_live_weight":
480
+ flock_live_weight,
 
481
 
482
+ "daily_feed_per_bird":
483
+ daily_feed_per_bird,
 
 
484
 
485
+ "benchmark_fcr":
486
+ benchmark_fcr,
487
+ }
 
488
 
 
 
 
 
489
 
490
+ # ============================================================
491
+ # DISPLAY CALCULATION
492
+ # ============================================================
 
493
 
494
+ def render_result(result):
495
+ """Create the farmer-friendly result."""
 
 
496
 
497
+ birds = result["birds"]
498
+ weeks = result["weeks"]
499
+ extra_days = result["extra_days"]
500
+ total_days = result["total_days"]
501
 
502
+ bag_size = result["bag_size"]
 
 
503
 
504
+ total_feed = result["total_feed_kg"]
 
 
505
 
506
+ starter_kg = result["starter_total_kg"]
507
+ finisher_kg = result["finisher_total_kg"]
 
508
 
509
+ exact_bags = result["exact_total_bags"]
 
 
510
 
511
+ total_bags = result["whole_total_bags"]
 
 
512
 
513
+ starter_bags = result["starter_bags_to_buy"]
514
+ finisher_bags = result["finisher_bags_to_buy"]
 
515
 
516
+ cost = result["estimated_cost"]
 
 
 
 
 
 
 
517
 
518
+ weight = result["body_weight_per_bird"]
 
 
 
 
519
 
520
+ flock_weight = result["flock_live_weight"]
 
 
 
521
 
522
+ daily_feed = result["daily_feed_per_bird"]
 
 
 
523
 
524
+ fcr = result["benchmark_fcr"]
 
 
 
 
 
525
 
526
+ age_text = f"{weeks} week"
 
 
527
 
528
+ if weeks != 1:
529
+ age_text += "s"
 
 
 
 
 
 
530
 
531
+ if extra_days > 0:
532
+ age_text += f" + {extra_days} day"
 
 
533
 
534
+ if extra_days != 1:
535
+ age_text += "s"
 
 
536
 
537
  # --------------------------------------------------------
538
+ # LARGE FARMER-FRIENDLY ANSWER
539
  # --------------------------------------------------------
540
 
541
+ quick_answer = f"""
542
+ # 🐔 Your Feed Requirement
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
 
544
+ ## You will require approximately **{total_bags} bags of {format_number(bag_size, 0)} kg feed**
545
 
546
+ ### To raise **{birds:,} birds** for **{age_text} ({total_days} days)**.
547
 
548
  ### 🌾 Feed breakdown
549
 
550
+ | Feed | Estimated quantity | Bags to buy |
551
+ |---|---:|---:|
552
+ | 🌱 Starter | **{starter_kg:,.1f} kg** | **{starter_bags} bags** |
553
+ | 🌽 Finisher | **{finisher_kg:,.1f} kg** | **{finisher_bags} bags** |
554
+ | **TOTAL** | **{total_feed:,.1f} kg** | **{total_bags} bags** |
555
 
556
+ ---
557
 
558
+ # 💰 Estimated feed cost
559
 
560
+ ## **{format_naira(cost)}**
561
 
562
+ This is approximately **{total_bags} bags × {format_naira(result["price_per_bag"])} per bag**.
563
 
564
  ---
565
 
566
  ## 🎯 Quick answer
567
 
568
+ **To raise {birds:,} birds for {total_days} days ({age_text}), you will need an estimated {exact_bags:.1f} bags of feed — so plan to buy {total_bags} bags ({starter_bags} Starter + {finisher_bags} Finisher), costing approximately {format_naira(cost)} on feeds alone.**
569
 
570
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
571
 
 
572
  ## 📊 Ross 308 benchmark at {total_days} days
573
 
574
+ - Expected body weight: **{weight:.2f} kg/bird**
575
+ - Expected flock live weight: **{flock_weight:.1f} kg**
576
+ - Cumulative feed: **{result["cumulative_feed_per_bird"]:.2f} kg/bird**
577
+ - Approx. daily feed intake: **{daily_feed:.3f} kg/bird/day**
578
+ - Benchmark FCR: **{fcr:.2f}**
579
 
580
+ ---
581
 
582
+ ### ⚠️ Important
 
583
 
584
+ This is a planning estimate based on the Ross 308 benchmark.
 
585
 
586
+ Actual farm feed consumption can vary because of:
 
587
 
588
+ - genetics
589
+ - sex
590
+ - mortality
591
+ - feed quality
592
+ - temperature
593
+ - housing
594
+ - management
595
+ - disease
596
+ - stocking density
597
+ - water availability
598
+ - other farm conditions
599
 
600
+ Use the result as a practical estimate, not a guarantee of actual consumption.
 
601
  """
602
 
603
+ return quick_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604
 
605
 
606
  # ============================================================
607
+ # EMAIL GATE + CALCULATION
608
  # ============================================================
609
 
610
+ def calculate_after_email(
611
+ email,
612
+ birds,
613
+ weeks,
614
+ extra_days,
615
+ bag_size,
616
+ price_per_bag,
617
+ question,
618
+ ):
619
  """
620
+ The farmer must provide an email before getting
621
+ the calculator result.
622
 
623
+ The question is automatically saved when the farmer
624
+ clicks Calculate / Get Answer.
625
  """
626
 
627
+ email = clean_email(email)
628
 
629
+ if not email:
630
  return (
631
+ "### 📧 Email required\n\n"
632
+ "Please enter a valid email address before "
633
+ "calculating your feed requirement.",
634
+ "",
 
635
  )
636
 
637
+ try:
638
+ result = calculate_feed(
639
+ birds,
640
+ weeks,
641
+ extra_days,
642
+ bag_size,
643
+ price_per_bag,
644
  )
645
 
646
+ except Exception as e:
 
 
 
 
 
 
647
 
 
648
  return (
649
+ f"### ❌ Please check your inputs\n\n{str(e)}",
650
+ "",
 
 
651
  )
652
 
653
+ # --------------------------------------------------------
654
+ # SAVE EMAIL
655
+ # --------------------------------------------------------
 
 
656
 
657
+ save_lead(email)
658
 
659
+ # --------------------------------------------------------
660
+ # AUTOMATICALLY SAVE QUESTION
661
+ #
662
+ # This happens when Get Answer is clicked.
663
+ # No separate Save Question button is necessary.
664
+ # --------------------------------------------------------
665
 
666
+ question = (question or "").strip()
 
 
667
 
668
+ if question:
 
 
 
669
 
670
+ save_question(
671
+ email=email,
672
+ question=question,
673
+ birds=result["birds"],
674
+ total_days=result["total_days"],
675
+ bag_size=result["bag_size"],
676
+ price=result["price_per_bag"],
677
  )
678
 
679
+ question_status = (
680
+ "✅ Your question has been saved. "
681
+ "It will help us improve PoultryFeedCalc."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682
  )
683
 
684
+ else:
685
 
686
+ question_status = (
687
+ "Your calculation has been completed."
 
688
  )
689
 
690
+ answer = render_result(result)
691
 
692
+ return answer, question_status
693
+
694
+
695
+ # ============================================================
696
+ # QUESTION ANSWER / COLLECTION
697
+ # ============================================================
698
+
699
+ def save_farmer_question(
700
  email,
701
+ question,
 
 
 
 
702
  ):
703
  """
704
+ Optional standalone question saving.
705
+ The main calculator already saves questions automatically
706
+ when Get Answer is clicked.
707
  """
708
 
709
+ email = clean_email(email)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
710
 
711
+ question = (question or "").strip()
 
 
 
 
 
 
712
 
713
+ if not email:
714
+ return "📧 Please enter your email address first."
 
 
 
 
 
715
 
716
+ if not question:
717
+ return "❓ Please type a question first."
 
 
 
 
 
718
 
719
+ if save_question(
720
+ email=email,
 
721
  question=question,
722
+ ):
723
+ return (
724
+ "✅ Question saved. "
725
+ "Thank you — this helps us build future answers."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
726
  )
727
 
728
+ return "❌ We could not save the question."
 
 
 
729
 
730
 
731
  # ============================================================
732
+ # CUSTOM BIRD SELECTION
733
  # ============================================================
734
 
735
+ def bird_selection_changed(value):
736
+ """
737
+ If the farmer chooses Custom, show a custom bird field.
738
+ Otherwise hide it.
739
+ """
 
 
 
740
 
741
+ if value == "Custom":
742
+ return gr.update(
743
+ visible=True,
744
+ value=100,
745
+ )
746
 
747
+ return gr.update(
748
+ visible=False,
749
+ value=None,
 
 
 
 
 
 
 
 
750
  )
751
 
752
 
753
+ def get_bird_number(selection, custom_birds):
754
+ """Convert bird selection into an integer."""
 
 
 
755
 
756
+ if selection == "Custom":
 
 
 
 
 
757
 
758
+ if custom_birds is None:
759
+ raise ValueError(
760
+ "Please enter your number of birds."
761
+ )
762
 
763
+ birds = int(custom_birds)
 
764
 
765
+ if birds <= 0:
766
+ raise ValueError(
767
+ "Number of birds must be greater than zero."
768
+ )
 
 
 
 
 
 
 
 
769
 
770
+ return birds
 
 
 
771
 
772
+ return int(selection)
773
 
 
 
774
 
775
+ def calculate_with_selection(
776
+ email,
777
+ bird_selection,
778
+ custom_birds,
779
+ weeks,
780
+ extra_days,
781
+ bag_size,
782
+ price_per_bag,
783
+ question,
784
+ ):
785
+ """Wrapper around the main calculator."""
786
 
787
  try:
788
+ birds = get_bird_number(
789
+ bird_selection,
790
+ custom_birds,
 
 
 
 
791
  )
792
 
793
+ except Exception as e:
 
 
 
 
 
 
 
 
 
 
794
 
795
+ return (
796
+ f"### ❌ Please check your bird number\n\n{str(e)}",
797
+ "",
798
  )
799
 
800
+ return calculate_after_email(
801
+ email,
802
+ birds,
803
+ weeks,
804
+ extra_days,
805
+ bag_size,
806
+ price_per_bag,
807
+ question,
 
 
 
 
808
  )
809
 
810
 
811
  # ============================================================
812
+ # UI
813
  # ============================================================
814
 
815
+ CSS = """
816
+ .gradio-container {
817
+ max-width: 1250px !important;
818
+ margin: auto !important;
819
+ }
820
+
821
+ .big-answer {
822
+ font-size: 1.08rem;
823
+ }
824
+
825
+ .email-box {
826
+ border: 2px solid #f97316;
827
+ border-radius: 12px;
828
+ padding: 12px;
829
+ }
830
+
831
+ .hero-answer {
832
+ border-radius: 14px;
833
+ }
834
+
835
+ button.primary {
836
+ font-size: 1.1rem !important;
837
+ }
838
+ """
839
+
840
+
841
+ with gr.Blocks(css=CSS) as demo:
842
 
843
  gr.Markdown(
844
  """
 
849
  Choose the number of birds, age, feed bag size and price —
850
  **no calculations required.**
851
 
852
+ The calculator converts **weeks + days into total days** and estimates the feed required using a Ross 308 benchmark.
 
853
  """
854
  )
855
 
856
+ # ========================================================
857
+ # EMAIL SECTION
858
+ # ========================================================
859
 
860
+ with gr.Group(elem_classes="email-box"):
861
 
862
  gr.Markdown(
863
  """
864
+ ### 📧 Before you calculate
865
 
866
+ Enter your email so we can send you future PoultryFeedCalc
867
+ updates and improvements.
868
 
869
+ **Your email is only used for PoultryFeedCalc communications.**
870
  """
871
  )
872
 
873
+ email = gr.Textbox(
874
+ label="Email address",
875
+ placeholder="farmer@example.com",
876
+ type="email",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
  )
878
 
879
+ # ========================================================
880
+ # MAIN CALCULATOR
881
+ # ========================================================
882
 
883
  with gr.Row():
884
 
885
+ # ----------------------------------------------------
886
+ # INPUTS
887
+ # ----------------------------------------------------
888
+
889
+ with gr.Column(scale=1):
890
 
891
  gr.Markdown(
892
  "## 🧮 Farm inputs"
893
  )
894
 
895
+ bird_selection = gr.Dropdown(
896
  label="🐔 Number of birds",
897
  choices=[
898
  "25",
 
902
  "150",
903
  "200",
904
  "500",
905
+ "1,000",
906
  "Custom",
907
  ],
908
  value="25",
 
910
 
911
  custom_birds = gr.Number(
912
  label="Custom number of birds",
913
+ value=100,
914
  minimum=1,
915
  precision=0,
 
916
  visible=False,
917
  )
918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
919
  weeks = gr.Dropdown(
920
  label="📅 Age — Weeks",
921
+ choices=list(range(0, 13)),
922
+ value=5,
 
 
923
  )
924
 
925
+ extra_days = gr.Dropdown(
926
  label="📅 Age — Days",
927
+ choices=list(range(0, 7)),
 
 
928
  value=0,
929
  )
930
 
 
934
  10,
935
  25,
936
  50,
 
 
937
  ],
938
  value=25,
939
  )
940
 
941
+ price_per_bag = gr.Number(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
942
  label="💰 Price per bag (₦)",
943
+ value=24000,
944
  minimum=0,
945
+ precision=0,
 
 
 
 
 
 
946
  )
947
 
948
  # ----------------------------------------------------
949
+ # RESULT
950
  # ----------------------------------------------------
951
 
952
  with gr.Column(
953
+ scale=1,
954
  ):
955
 
956
+ gr.Markdown(
957
+ "## 🐔 Your feed requirement"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
958
  )
959
 
960
+ result = gr.Markdown(
961
+ """
962
+ ### Enter your details and click **Calculate Feed Requirement**.
963
 
964
+ Your answer will appear here.
965
+ """,
966
+ elem_classes="hero-answer",
967
  )
968
 
969
+ # ========================================================
970
+ # QUESTION BOX
971
+ # ========================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
972
 
973
+ gr.Markdown("---")
 
 
974
 
975
  gr.Markdown(
976
  """
 
 
977
  # ❓ Ask a question
978
 
979
  ### What would you like to know about raising your birds?
980
 
981
+ You can type a question or use your device's microphone.
982
 
983
+ **When you click Get Answer, the question is automatically saved for future app improvements.**
 
 
984
  """
985
  )
986
 
 
988
  label="Your question",
989
  placeholder=(
990
  "Example: How many bags of feed do I need "
991
+ "for 100 broilers to 6 weeks?"
992
  ),
993
  lines=4,
994
  )
995
 
996
  gr.Markdown(
997
+ """
998
+ 💡 **Examples of questions farmers can ask:**
999
+
1000
+ - How many bags for 50 birds for 6 weeks?
1001
+ - How many bags for 100 broilers for 8 weeks?
1002
+ - Is 3 bags enough for 51 birds at 3 weeks?
1003
+ - How much feed will 200 birds need?
1004
+ - How much will feed cost?
1005
+ - How much Starter feed do I need?
1006
+ - When should I change from Starter to Finisher?
1007
+ - What weight should my broilers reach?
1008
+ - Why are my birds eating more feed?
1009
+ - How can I reduce feed wastage?
1010
+ """
1011
  )
1012
 
1013
+ # ========================================================
1014
+ # BUTTONS
1015
+ # ========================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1016
 
1017
+ calculate_button = gr.Button(
1018
+ "🐔 Get Answer / Calculate Feed Requirement",
1019
+ variant="primary",
1020
+ size="lg",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1021
  )
1022
 
1023
+ question_status = gr.Markdown()
1024
 
1025
+ # Optional separate question save button.
1026
+ # The main Calculate button automatically saves it,
1027
+ # but this allows farmers to submit questions even
1028
+ # without running a calculation.
 
1029
 
1030
+ save_question_button = gr.Button(
1031
+ "💾 Save Question for Future Answers",
1032
+ variant="secondary",
1033
+ )
1034
 
1035
+ # ========================================================
1036
+ # EVENTS
1037
+ # ========================================================
1038
 
1039
+ bird_selection.change(
1040
+ fn=bird_selection_changed,
1041
+ inputs=bird_selection,
1042
+ outputs=custom_birds,
1043
+ )
1044
 
1045
+ calculate_button.click(
1046
+ fn=calculate_with_selection,
1047
  inputs=[
 
1048
  email,
1049
+ bird_selection,
1050
+ custom_birds,
1051
  weeks,
1052
+ extra_days,
1053
+ bag_size,
1054
+ price_per_bag,
1055
+ question,
1056
  ],
1057
  outputs=[
1058
+ result,
1059
  question_status,
1060
  ],
 
1061
  )
1062
 
1063
+ save_question_button.click(
1064
+ fn=save_farmer_question,
1065
+ inputs=[
1066
+ email,
 
 
 
 
1067
  question,
1068
+ ],
1069
+ outputs=[
1070
  question_status,
1071
  ],
1072
  )
1073
 
1074
+ # ========================================================
1075
+ # HOW IT WORKS
1076
+ # ========================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1077
 
1078
  gr.Markdown(
1079
  """
1080
  ---
1081
 
1082
+ ## 📌 How the estimate works
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1083
 
1084
+ The calculator:
1085
 
1086
+ 1. Converts **weeks + days into total days**.
1087
+ 2. Estimates cumulative feed consumption per bird.
1088
+ 3. Calculates total feed for the flock.
1089
+ 4. Splits the estimate into **Starter and Finisher**.
1090
+ 5. Converts kilograms into the selected bag size.
1091
+ 6. Calculates the exact number of bags.
1092
+ 7. **Rounds the total number of bags UP** so the farmer does not under-buy.
1093
 
1094
+ ### Example
1095
 
1096
+ If the calculation gives:
1097
 
1098
+ **145 kg ÷ 25 kg = 5.8 bags**
1099
 
1100
+ the app will tell the farmer to plan for:
1101
 
1102
+ ## **6 bags**
1103
 
1104
+ rather than incorrectly displaying only 5 bags.
 
1105
 
1106
  ---
1107
 
1108
+ ## ⚠️ Important
 
 
 
1109
 
1110
+ Actual farm consumption can vary with genetics, sex, mortality,
1111
+ feed quality, temperature, management, disease, stocking density,
1112
+ water availability and other farm conditions.
1113
 
1114
+ This calculator provides a **planning estimate**, not veterinary
1115
+ or farm-specific advice.
 
 
 
 
 
 
1116
 
 
 
1117
  ---
1118
 
1119
+ ## 💡 Help us build better tools
 
 
 
 
 
 
 
 
1120
 
1121
+ The questions farmers submit are collected so we can identify
1122
+ the most common questions and build better answers into
1123
+ future versions of PoultryFeedCalc.
 
1124
  """
1125
  )
1126
 
1127
 
1128
  # ============================================================
1129
+ # IMPORTANT FOR HUGGING FACE SPACES
 
 
 
 
 
 
 
 
 
1130
  # ============================================================
1131
+ #
1132
+ # DO NOT specify port 7860 manually.
1133
+ # DO NOT start uvicorn separately.
1134
+ # DO NOT call demo.launch() more than once.
1135
+ #
1136
+ # Hugging Face Spaces manages the server/port.
1137
  # ============================================================
1138
 
1139
  if __name__ == "__main__":
1140
+ demo.launch(
1141
+ theme=gr.themes.Soft(),
 
 
 
 
 
 
 
 
 
 
 
 
1142
  )