NTEIGBANAM OKE commited on
Commit
f977694
·
verified ·
1 Parent(s): 00e41a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -577
app.py CHANGED
@@ -1,624 +1,210 @@
 
 
 
 
1
  import math
 
 
2
  import pandas as pd
3
  import gradio as gr
4
 
5
-
6
- # ============================================================
7
- # ROSS 308 / ROSS 308 FF — AS-HATCHED PERFORMANCE OBJECTIVES
8
- # Weekly checkpoints based on Aviagen performance objectives.
9
- # ============================================================
10
-
11
  ROSS_WEEKLY = pd.DataFrame([
12
- {
13
- "Week": 0,
14
- "Day": 0,
15
- "Body Weight (kg/bird)": 0.044,
16
- "Daily Intake (g/bird/day)": None,
17
- "Cumulative Feed (kg/bird)": 0.000,
18
- "FCR": None,
19
- },
20
- {
21
- "Week": 1,
22
- "Day": 7,
23
- "Body Weight (kg/bird)": 0.213,
24
- "Daily Intake (g/bird/day)": 35,
25
- "Cumulative Feed (kg/bird)": 0.166,
26
- "FCR": 0.780,
27
- },
28
- {
29
- "Week": 2,
30
- "Day": 14,
31
- "Body Weight (kg/bird)": 0.533,
32
- "Daily Intake (g/bird/day)": 67,
33
- "Cumulative Feed (kg/bird)": 0.535,
34
- "FCR": 1.005,
35
- },
36
- {
37
- "Week": 3,
38
- "Day": 21,
39
- "Body Weight (kg/bird)": 1.046,
40
- "Daily Intake (g/bird/day)": 111,
41
- "Cumulative Feed (kg/bird)": 1.193,
42
- "FCR": 1.141,
43
- },
44
- {
45
- "Week": 4,
46
- "Day": 28,
47
- "Body Weight (kg/bird)": 1.697,
48
- "Daily Intake (g/bird/day)": 155,
49
- "Cumulative Feed (kg/bird)": 2.147,
50
- "FCR": 1.266,
51
- },
52
- {
53
- "Week": 5,
54
- "Day": 35,
55
- "Body Weight (kg/bird)": 2.441,
56
- "Daily Intake (g/bird/day)": 195,
57
- "Cumulative Feed (kg/bird)": 3.394,
58
- "FCR": 1.390,
59
- },
60
- {
61
- "Week": 6,
62
- "Day": 42,
63
- "Body Weight (kg/bird)": 3.222,
64
- "Daily Intake (g/bird/day)": 226,
65
- "Cumulative Feed (kg/bird)": 4.886,
66
- "FCR": 1.517,
67
- },
68
- {
69
- "Week": 7,
70
- "Day": 49,
71
- "Body Weight (kg/bird)": 3.991,
72
- "Daily Intake (g/bird/day)": 247,
73
- "Cumulative Feed (kg/bird)": 6.556,
74
- "FCR": 1.643,
75
- },
76
- {
77
- "Week": 8,
78
- "Day": 56,
79
- "Body Weight (kg/bird)": 4.714,
80
- "Daily Intake (g/bird/day)": 258,
81
- "Cumulative Feed (kg/bird)": 8.332,
82
- "FCR": 1.768,
83
- },
84
  ])
85
 
86
 
87
- # ============================================================
88
- # CALCULATOR
89
- # ============================================================
90
-
91
- def calculate(
92
- birds,
93
- age,
94
- bag_size,
95
- bag_price,
96
- actual_feed,
97
- actual_weight,
98
- ):
99
- """
100
- Calculate expected feed requirement, bags, cost,
101
- benchmark weight and optional farm comparison.
102
- """
103
-
104
- # ----------------------------
105
- # Clean inputs
106
- # ----------------------------
107
-
108
- try:
109
- birds = max(1, int(birds))
110
- except Exception:
111
- birds = 100
112
-
113
  try:
114
- age = int(age)
115
  except Exception:
116
- age = 6
117
-
118
- try:
119
- bag_size = max(1.0, float(bag_size))
120
- except Exception:
121
- bag_size = 25.0
122
-
123
- try:
124
- bag_price = max(0.0, float(bag_price))
125
- except Exception:
126
- bag_price = 24000.0
127
-
128
- try:
129
- actual_feed = max(0.0, float(actual_feed))
130
- except Exception:
131
- actual_feed = 0.0
132
-
133
- try:
134
- actual_weight = max(0.0, float(actual_weight))
135
- except Exception:
136
- actual_weight = 0.0
137
-
138
- # Make sure age is valid.
139
- if age < 1:
140
- age = 1
141
-
142
- if age > 8:
143
- age = 8
144
-
145
- # ----------------------------
146
- # Get Ross benchmark
147
- # ----------------------------
148
-
149
- row = ROSS_WEEKLY.loc[
150
- ROSS_WEEKLY["Week"] == age
151
- ].iloc[0]
152
-
153
- cumulative_feed = float(
154
- row["Cumulative Feed (kg/bird)"]
155
- )
156
-
157
- body_weight = float(
158
- row["Body Weight (kg/bird)"]
159
- )
160
-
161
- daily_intake = row[
162
- "Daily Intake (g/bird/day)"
163
- ]
164
-
165
- fcr = row["FCR"]
166
-
167
- # ----------------------------
168
- # Feed calculations
169
- # ----------------------------
170
-
171
- expected_feed_total = (
172
- birds * cumulative_feed
173
- )
174
-
175
- expected_bags = (
176
- expected_feed_total / bag_size
177
- )
178
-
179
- bags_to_buy = math.ceil(
180
- expected_bags
181
- )
182
-
183
- expected_cost = (
184
- bags_to_buy * bag_price
185
- )
186
-
187
- expected_live_weight = (
188
- birds * body_weight
189
- )
190
-
191
- bags_25kg = (
192
- expected_feed_total / 25.0
193
- )
194
-
195
- # ----------------------------
196
- # Summary
197
- # ----------------------------
198
-
199
- summary = f"""
200
- ## 🐔 Results — Week {age}
201
-
202
- | Metric | Result |
203
- |---|---:|
204
- | Expected weight / bird | **{body_weight:.2f} kg** |
205
- | Cumulative feed / bird | **{cumulative_feed:.2f} kg** |
206
- | Feed needed for {birds:,} birds | **{expected_feed_total:,.1f} kg** |
207
- | Exact bags at {bag_size:g} kg | **{expected_bags:,.2f} bags** |
208
- | Whole bags to buy | **{bags_to_buy:,}** |
209
- | Estimated feed cost | **₦{expected_cost:,.0f}** |
210
- | Expected flock live weight | **{expected_live_weight:,.1f} kg** |
211
- | 25-kg equivalent bags | **{bags_25kg:,.1f}** |
212
  """
213
 
214
- # ----------------------------
215
- # Benchmark
216
- # ----------------------------
217
 
218
- daily_intake_text = (
219
- "-"
220
- if pd.isna(daily_intake)
221
- else f"{int(daily_intake)}"
222
- )
223
 
224
- fcr_text = (
225
- "-"
226
- if pd.isna(fcr)
227
- else f"{float(fcr):.3f}"
228
- )
229
 
230
- benchmark = f"""
231
- ## 📊 Ross 308 benchmark — Week {age}
 
232
 
233
- - **Body weight:** {body_weight:.3f} kg/bird
234
- - **Daily feed intake at checkpoint:** {daily_intake_text} g/bird/day
235
- - **Cumulative feed:** {cumulative_feed:.3f} kg/bird
236
- - **Benchmark FCR:** {fcr_text}
237
  """
 
238
 
239
- # ----------------------------
240
- # Farm comparison
241
- # ----------------------------
242
-
243
- comparison = ""
244
-
245
- if actual_feed > 0 or actual_weight > 0:
246
-
247
- lines = [
248
- "## 📈 Your farm vs benchmark"
249
- ]
250
 
251
- if actual_feed > 0:
252
 
253
- feed_diff = (
254
- actual_feed
255
- - expected_feed_total
256
- )
257
 
258
- lines.append(
259
- f"- **Actual feed used:** "
260
- f"{actual_feed:,.1f} kg "
261
- f"({feed_diff:+,.1f} kg vs benchmark)"
262
- )
 
 
 
 
 
 
 
 
263
 
264
- if actual_weight > 0:
265
 
266
- weight_diff = (
267
- actual_weight
268
- - body_weight
269
- )
 
 
 
 
 
 
 
270
 
271
- lines.append(
272
- f"- **Actual average weight:** "
273
- f"{actual_weight:.2f} kg "
274
- f"({weight_diff:+.2f} kg vs benchmark)"
275
- )
276
-
277
- if actual_weight > 0 and actual_feed > 0:
278
-
279
- # Starting chick weight.
280
- starting_weight = 0.044
281
-
282
- gain_per_bird = (
283
- actual_weight
284
- - starting_weight
285
- )
286
-
287
- total_gain = (
288
- birds * gain_per_bird
289
- )
290
-
291
- if total_gain > 0:
292
-
293
- actual_fcr = (
294
- actual_feed
295
- / total_gain
296
- )
297
-
298
- lines.append(
299
- f"- **Approx. FCR:** "
300
- f"{actual_fcr:.3f}"
301
- )
302
-
303
- else:
304
-
305
- lines.append(
306
- "- **Approx. FCR:** "
307
- "not available yet"
308
- )
309
-
310
- comparison = "\n".join(lines)
311
-
312
- return (
313
- summary,
314
- benchmark,
315
- comparison,
316
- )
317
-
318
-
319
- # ============================================================
320
- # BENCHMARK TABLE
321
- # ============================================================
322
 
323
  def benchmark_table():
 
 
 
 
 
 
324
 
325
- display = ROSS_WEEKLY.copy()
326
 
327
- display[
328
- "Body Weight (kg/bird)"
329
- ] = display[
330
- "Body Weight (kg/bird)"
331
- ].map(
332
- lambda x: f"{x:.3f}"
333
- )
334
-
335
- display[
336
- "Cumulative Feed (kg/bird)"
337
- ] = display[
338
- "Cumulative Feed (kg/bird)"
339
- ].map(
340
- lambda x: f"{x:.3f}"
341
- )
342
-
343
- display[
344
- "Daily Intake (g/bird/day)"
345
- ] = display[
346
- "Daily Intake (g/bird/day)"
347
- ].map(
348
- lambda x:
349
- "-"
350
- if pd.isna(x)
351
- else f"{int(x)}"
352
- )
353
-
354
- display["FCR"] = display[
355
- "FCR"
356
- ].map(
357
- lambda x:
358
- "-"
359
- if pd.isna(x)
360
- else f"{x:.3f}"
361
- )
362
-
363
- return display
364
-
365
-
366
- # ============================================================
367
- # GRADIO APP
368
- # ============================================================
369
-
370
- with gr.Blocks(
371
- title="PoultryFeedCalc"
372
- ) as demo:
373
-
374
- gr.Markdown(
375
- """
376
- # 🐔 PoultryFeedCalc
377
-
378
- ### Broiler feed, weight and cost calculator — Nigeria MVP
379
-
380
- Use this calculator to estimate feed requirements,
381
- feed bags, feed cost and expected broiler weight.
382
- """
383
- )
384
-
385
- gr.Markdown(
386
- """
387
- **Important:** Ross performance objectives are used as
388
- the numerical benchmark. Nigerian management guidance
389
- is presented separately and should not be treated as
390
- a replacement for veterinary or farm-specific advice.
391
- """
392
- )
393
-
394
- # ========================================================
395
- # INPUT / RESULTS
396
- # ========================================================
397
 
398
  with gr.Row():
399
-
400
- # ----------------------------------------------------
401
- # INPUTS
402
- # ----------------------------------------------------
403
-
404
  with gr.Column(scale=1):
405
-
406
- gr.Markdown(
407
- "## 🧮 Farm inputs"
408
- )
409
-
410
- birds = gr.Number(
411
- label="Number of birds",
412
- minimum=1,
413
- value=100,
414
- precision=0,
415
- )
416
-
417
- age = gr.Dropdown(
418
- label="Target age",
419
- choices=list(range(1, 9)),
420
- value=6,
421
- )
422
-
423
- bag_size = gr.Number(
424
- label="Feed bag size (kg)",
425
- minimum=1,
426
- value=25,
427
- )
428
-
429
- bag_price = gr.Number(
430
- label="Price per bag (₦)",
431
- minimum=0,
432
- value=24000,
433
- )
434
-
435
- gr.Markdown(
436
- "### Optional actual farm figures"
437
- )
438
-
439
- actual_feed = gr.Number(
440
- label="Feed already used (kg)",
441
- minimum=0,
442
- value=0,
443
- )
444
-
445
- actual_weight = gr.Number(
446
- label="Current average weight (kg/bird)",
447
- minimum=0,
448
- value=0,
449
- )
450
-
451
- calculate_btn = gr.Button(
452
- "🐔 Calculate",
453
- variant="primary",
454
- )
455
-
456
- # ----------------------------------------------------
457
- # RESULTS
458
- # ----------------------------------------------------
459
 
460
  with gr.Column(scale=2):
461
-
462
  summary = gr.Markdown()
 
463
 
464
- benchmark = gr.Markdown()
465
-
466
- comparison = gr.Markdown()
467
-
468
- # ========================================================
469
- # BENCHMARK TABLE
470
- # ========================================================
471
-
472
- gr.Markdown(
473
- "## 📊 Ross 308 weekly benchmark"
474
- )
475
-
476
- gr.Dataframe(
477
- value=benchmark_table(),
478
- interactive=False,
479
- wrap=True,
480
- )
481
-
482
- # ========================================================
483
- # NIGERIA MANAGEMENT REFERENCE
484
- # ========================================================
485
-
486
- gr.Markdown(
487
- "## 🇳🇬 Nigeria management reference"
488
- )
489
-
490
- gr.Info(
491
- """
492
- Agrited's Nigeria broiler guide is kept separate from
493
- the Ross numerical benchmark.
494
-
495
- It covers brooding temperature, crop-fill checks,
496
- 7-day weight and mortality monitoring, ventilation,
497
- feed handling, water quality, stocking density,
498
- vaccination handling and biosecurity.
499
- """
500
- )
501
-
502
  with gr.Row():
 
 
 
 
 
 
 
503
 
504
- with gr.Column():
505
-
506
- gr.Markdown(
507
- """
508
- ### 🌡️ Brooding
509
-
510
- Agrited guidance:
511
-
512
- Start warming the brooding area
513
- 24–48 hours before chick arrival.
514
-
515
- Initial chick-level temperature:
516
- **31–33°C**
517
-
518
- Temperature is reduced progressively
519
- toward approximately **21°C by day 28**.
520
- """
521
- )
522
-
523
- with gr.Column():
524
-
525
- gr.Markdown(
526
- """
527
- ### 💧 Water
528
-
529
- Use tested water.
530
-
531
- Reference pH:
532
- **5.5–7.5**
533
-
534
- Avoid supplying water above
535
- approximately **30°C**.
536
- """
537
- )
538
-
539
- with gr.Column():
540
-
541
- gr.Markdown(
542
- """
543
- ### 🐔 Stocking density
544
-
545
- Agrited reference:
546
-
547
- Around **25 kg live weight/m²**
548
- at slaughter for hot Nigerian conditions.
549
-
550
- Actual stocking density should account
551
- for house design, ventilation and climate.
552
- """
553
- )
554
-
555
- # ========================================================
556
- # SOURCES / DISCLAIMER
557
- # ========================================================
558
-
559
- gr.Markdown(
560
- """
561
- ---
562
-
563
- ### 📚 References
564
-
565
- **Benchmark source:**
566
- Aviagen — Ross 308 / Ross 308 FF Broiler Performance Objectives (2022).
567
 
568
- **Nigeria management reference:**
569
- Agrited — *Everything You Need To Know About Raising Excellent Broiler Chickens in Nigeria*.
570
 
571
- This MVP is a planning and calculation tool.
572
- It is not veterinary advice.
573
- """
574
- )
575
 
576
- # ========================================================
577
- # BUTTON ACTION
578
- # ========================================================
579
 
 
580
  calculate_btn.click(
581
- fn=calculate,
582
- inputs=[
583
- birds,
584
- age,
585
- bag_size,
586
- bag_price,
587
- actual_feed,
588
- actual_weight,
589
- ],
590
- outputs=[
591
- summary,
592
- benchmark,
593
- comparison,
594
- ],
595
  )
596
-
597
- # ========================================================
598
- # INITIAL LOAD
599
- # ========================================================
600
-
601
  demo.load(
602
- fn=calculate,
603
- inputs=[
604
- birds,
605
- age,
606
- bag_size,
607
- bag_price,
608
- actual_feed,
609
- actual_weight,
610
- ],
611
- outputs=[
612
- summary,
613
- benchmark,
614
- comparison,
615
- ],
616
  )
617
 
618
-
619
- # ============================================================
620
- # START APP
621
- # ============================================================
622
-
623
  if __name__ == "__main__":
624
- demo.launch()
 
1
+ # Updated PoultryFeedCalc MVP
2
+ # Features: simple selections, age in weeks + days, day-based interpolation,
3
+ # starter/finisher split, whole-bag cost estimate, and farmer question collection.
4
+
5
  import math
6
+ import os
7
+ from datetime import datetime
8
  import pandas as pd
9
  import gradio as gr
10
 
 
 
 
 
 
 
11
  ROSS_WEEKLY = pd.DataFrame([
12
+ {"Week":0,"Day":0,"Body Weight (kg/bird)":0.044,"Daily Intake (g/bird/day)":None,"Cumulative Feed (kg/bird)":0.000,"FCR":None},
13
+ {"Week":1,"Day":7,"Body Weight (kg/bird)":0.213,"Daily Intake (g/bird/day)":35,"Cumulative Feed (kg/bird)":0.166,"FCR":0.780},
14
+ {"Week":2,"Day":14,"Body Weight (kg/bird)":0.533,"Daily Intake (g/bird/day)":67,"Cumulative Feed (kg/bird)":0.535,"FCR":1.005},
15
+ {"Week":3,"Day":21,"Body Weight (kg/bird)":1.046,"Daily Intake (g/bird/day)":111,"Cumulative Feed (kg/bird)":1.193,"FCR":1.141},
16
+ {"Week":4,"Day":28,"Body Weight (kg/bird)":1.697,"Daily Intake (g/bird/day)":155,"Cumulative Feed (kg/bird)":2.147,"FCR":1.266},
17
+ {"Week":5,"Day":35,"Body Weight (kg/bird)":2.441,"Daily Intake (g/bird/day)":195,"Cumulative Feed (kg/bird)":3.394,"FCR":1.390},
18
+ {"Week":6,"Day":42,"Body Weight (kg/bird)":3.222,"Daily Intake (g/bird/day)":226,"Cumulative Feed (kg/bird)":4.886,"FCR":1.517},
19
+ {"Week":7,"Day":49,"Body Weight (kg/bird)":3.991,"Daily Intake (g/bird/day)":247,"Cumulative Feed (kg/bird)":6.556,"FCR":1.643},
20
+ {"Week":8,"Day":56,"Body Weight (kg/bird)":4.714,"Daily Intake (g/bird/day)":258,"Cumulative Feed (kg/bird)":8.332,"FCR":1.768},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  ])
22
 
23
 
24
+ def num(value, default):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
+ return float(value)
27
  except Exception:
28
+ return float(default)
29
+
30
+
31
+ def interpolate_at_day(day):
32
+ day = max(0, min(56, int(day)))
33
+ out = {}
34
+ for col, key in [
35
+ ("Body Weight (kg/bird)", "body_weight"),
36
+ ("Cumulative Feed (kg/bird)", "cumulative_feed"),
37
+ ("Daily Intake (g/bird/day)", "daily_intake"),
38
+ ("FCR", "fcr"),
39
+ ]:
40
+ values = ROSS_WEEKLY[col].astype(float).interpolate().bfill().ffill()
41
+ out[key] = float(__import__("numpy").interp(day, ROSS_WEEKLY["Day"], values))
42
+ return out
43
+
44
+
45
+ def calculate(birds, weeks, days, bag_size, bag_price):
46
+ birds = max(1, int(num(birds, 100)))
47
+ weeks = max(0, min(8, int(num(weeks, 6))))
48
+ days = max(0, min(6, int(num(days, 0))))
49
+ bag_size = max(1, num(bag_size, 25))
50
+ bag_price = max(0, num(bag_price, 24000))
51
+
52
+ total_days = min(56, weeks * 7 + days)
53
+ age_w, age_d = divmod(total_days, 7)
54
+ age_text = f"{age_w} week{'s' if age_w != 1 else ''}"
55
+ if age_d:
56
+ age_text += f" + {age_d} day{'s' if age_d != 1 else ''}"
57
+
58
+ b = interpolate_at_day(total_days)
59
+ total_feed = birds * b["cumulative_feed"]
60
+ exact_bags = total_feed / bag_size
61
+ bags_to_buy = math.ceil(exact_bags)
62
+ total_cost = bags_to_buy * bag_price
63
+
64
+ # Starter through day 21; finisher after day 21.
65
+ starter_per_bird = min(b["cumulative_feed"], 1.193)
66
+ finisher_per_bird = max(0, b["cumulative_feed"] - 1.193)
67
+ starter_kg = birds * starter_per_bird
68
+ finisher_kg = birds * finisher_per_bird
69
+ starter_bags = math.ceil(starter_kg / bag_size) if starter_kg else 0
70
+ finisher_bags = math.ceil(finisher_kg / bag_size) if finisher_kg else 0
71
+ phase_cost = (starter_bags + finisher_bags) * bag_price
72
+
73
+ summary = f"""# 🐔 Your feed requirement
74
+
75
+ ### You will require approximately **{bags_to_buy} bags of {bag_size:g} kg feed**
76
+ to raise **{birds:,} birds to {age_text} ({total_days} days)**.
77
+
78
+ | Feed | Quantity | Whole bags to buy |
79
+ |---|---:|---:|
80
+ | 🌱 Starter | **{starter_kg:,.1f} kg** | **{starter_bags} bags** |
81
+ | 🌾 Finisher | **{finisher_kg:,.1f} kg** | **{finisher_bags} bags** |
82
+ | **Total** | **{total_feed:,.1f} kg** | **{bags_to_buy} bags** |
83
+
84
+ ### 💰 Estimated feed cost
85
+ **₦{phase_cost:,.0f}** on feed alone.
86
+
87
+ *Based on ₦{bag_price:,.0f} per {bag_size:g}-kg bag.*
88
+
89
+ > **Quick answer:** {birds:,} birds × {total_days} days → **{bags_to_buy} bags** ({starter_bags} Starter + {finisher_bags} Finisher), costing approximately **₦{phase_cost:,.0f}**.
90
+
91
+ ### 📊 Ross benchmark at {total_days} days
92
+ - Expected body weight: **{b['body_weight']:.2f} kg/bird**
93
+ - Expected flock live weight: **{birds*b['body_weight']:,.1f} kg**
94
+ - Cumulative feed: **{b['cumulative_feed']:.2f} kg/bird**
95
+ - Approx. daily intake: **{b['daily_intake']:.0f} g/bird/day**
96
+ - Benchmark FCR: **{b['fcr']:.3f}**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  """
98
 
99
+ explanation = f"""## 📌 How the estimate works
 
 
100
 
101
+ The calculator converts **Weeks + Days into total days**. For example, 6 weeks + 3 days = **45 days**.
 
 
 
 
102
 
103
+ It interpolates between the weekly Ross checkpoints to estimate feed at ages between whole weeks.
 
 
 
 
104
 
105
+ - **Starter:** feed through day 21
106
+ - **Finisher:** feed after day 21
107
+ - Bag count is rounded up to the number of whole bags to buy.
108
 
109
+ Actual farm consumption can vary with genetics, sex, mortality, feed quality, temperature, management and other farm conditions.
 
 
 
110
  """
111
+ return summary, explanation
112
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ QUESTIONS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "farmer_questions.csv")
115
 
 
 
 
 
116
 
117
+ def answer_farmer_question(question):
118
+ q = (question or "").strip().lower()
119
+ if not q:
120
+ return "Type a question first."
121
+ if any(x in q for x in ["how many bags", "bags of feed", "how much feed", "feed do i need", "feed needed"]):
122
+ return "Use the calculator above: select your number of birds, age in weeks + days, bag size and price. It will calculate total feed, Starter/Finisher bags and estimated feed cost."
123
+ if "starter" in q and "finisher" in q:
124
+ return "The calculator treats Starter as feed through day 21 and Finisher as feed after day 21, using the selected age in total days."
125
+ if "cost" in q or "price" in q or "money" in q:
126
+ return "Enter your current price per bag above. The app multiplies the required whole bags by your price to estimate feed cost."
127
+ if "3 bags" in q or "enough" in q:
128
+ return "Enter the exact number of birds, age and bag size above. The calculator will compare the required whole bags with the number you have."
129
+ return "Thanks. Your question can be saved below for future app improvements. For a feed calculation, use the calculator above."
130
 
 
131
 
132
+ def save_question(question, audio_path):
133
+ question = (question or "").strip()
134
+ if not question and not audio_path:
135
+ return "Please type or record a question first."
136
+ row = pd.DataFrame([{
137
+ "timestamp": datetime.now().isoformat(timespec="seconds"),
138
+ "question": question,
139
+ "voice_recording": audio_path or "",
140
+ }])
141
+ row.to_csv(QUESTIONS_FILE, mode="a", header=not os.path.exists(QUESTIONS_FILE), index=False)
142
+ return "✅ Question saved for future app improvements."
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  def benchmark_table():
146
+ d = ROSS_WEEKLY.copy()
147
+ d["Body Weight (kg/bird)"] = d["Body Weight (kg/bird)"].map(lambda x: f"{x:.3f}")
148
+ d["Cumulative Feed (kg/bird)"] = d["Cumulative Feed (kg/bird)"].map(lambda x: f"{x:.3f}")
149
+ d["Daily Intake (g/bird/day)"] = d["Daily Intake (g/bird/day)"].map(lambda x: "-" if pd.isna(x) else f"{int(x)}")
150
+ d["FCR"] = d["FCR"].map(lambda x: "-" if pd.isna(x) else f"{x:.3f}")
151
+ return d
152
 
 
153
 
154
+ with gr.Blocks(title="PoultryFeedCalc") as demo:
155
+ gr.Markdown("""# 🐔 PoultryFeedCalc
156
+ ### Simple broiler feed calculator for farmers
157
+ Choose the number of birds, age, bag size and price — **no calculations required.**""")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
  with gr.Row():
 
 
 
 
 
160
  with gr.Column(scale=1):
161
+ gr.Markdown("## 🧮 Farm inputs")
162
+ birds = gr.Dropdown(label="🐔 Number of birds", choices=["25","50","75","100","150","200","500","1,000","Custom"], value="100")
163
+ custom_birds = gr.Number(label="Custom number of birds", minimum=1, value=100, precision=0, visible=False)
164
+ weeks = gr.Dropdown(label="📅 Age — Weeks", choices=list(range(0,9)), value=6)
165
+ days = gr.Dropdown(label="📅 Age — Days", choices=list(range(0,7)), value=0)
166
+ bag_size = gr.Dropdown(label="🌾 Feed bag size", choices=[10,25,50], value=25)
167
+ bag_price = gr.Number(label="💰 Price per bag (₦)", minimum=0, value=24000, precision=0)
168
+ calculate_btn = gr.Button("🐔 Calculate Feed Requirement", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  with gr.Column(scale=2):
 
171
  summary = gr.Markdown()
172
+ explanation = gr.Markdown()
173
 
174
+ gr.Markdown("---")
175
+ gr.Markdown("## ❓ Ask a question")
176
+ gr.Markdown("**What would you like to know about raising your birds?**\n\nType your question or use the microphone. Questions are saved to guide future upgrades and answers.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  with gr.Row():
178
+ farmer_question = gr.Textbox(label="Your question", placeholder="Type your question here...", lines=3, scale=3)
179
+ farmer_voice = gr.Audio(label="🎤 Speak your question", sources=["microphone"], type="filepath", scale=1)
180
+ with gr.Row():
181
+ answer_btn = gr.Button("🤖 Get Answer")
182
+ save_question_btn = gr.Button("💾 Save Question")
183
+ question_answer = gr.Markdown()
184
+ question_status = gr.Markdown()
185
 
186
+ gr.Markdown("---\n## 📊 Ross 308 weekly benchmark")
187
+ gr.Dataframe(value=benchmark_table(), interactive=False, wrap=True)
188
+ gr.Markdown("""## 🇳🇬 Nigeria management reference
189
+ Use local management guidance alongside the numerical benchmark. Farm results vary with housing, ventilation, temperature, water, feed quality, stocking density, vaccination, mortality and management.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
+ **Benchmark source:** Aviagen — Ross 308 / Ross 308 FF Broiler Performance Objectives (2022).
 
192
 
193
+ **Nigeria management reference:** Agrited — *Everything You Need To Know About Raising Excellent Broiler Chickens in Nigeria*.
 
 
 
194
 
195
+ This MVP is a planning and calculation tool. It is not veterinary advice.""")
 
 
196
 
197
+ birds.change(lambda v: gr.update(visible=v == "Custom"), inputs=birds, outputs=custom_birds)
198
  calculate_btn.click(
199
+ lambda selected, custom, w, d, size, price: calculate(int(str(custom if selected == "Custom" else selected).replace(",", "")), w, d, size, price),
200
+ inputs=[birds, custom_birds, weeks, days, bag_size, bag_price], outputs=[summary, explanation]
 
 
 
 
 
 
 
 
 
 
 
 
201
  )
202
+ answer_btn.click(answer_farmer_question, inputs=farmer_question, outputs=question_answer)
203
+ save_question_btn.click(save_question, inputs=[farmer_question, farmer_voice], outputs=question_status)
 
 
 
204
  demo.load(
205
+ lambda selected, custom, w, d, size, price: calculate(int(str(custom if selected == "Custom" else selected).replace(",", "")), w, d, size, price),
206
+ inputs=[birds, custom_birds, weeks, days, bag_size, bag_price], outputs=[summary, explanation]
 
 
 
 
 
 
 
 
 
 
 
 
207
  )
208
 
 
 
 
 
 
209
  if __name__ == "__main__":
210
+ demo.launch()