NTEIGBANAM OKE commited on
Commit
9e09c4d
Β·
verified Β·
1 Parent(s): 8d49fc7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +641 -382
app.py CHANGED
@@ -1,209 +1,299 @@
1
- from pathlib import Path
2
-
3
- app_code = r'''
4
  import os
5
- import csv
6
  import math
7
  import re
8
- from datetime import datetime, timezone
 
9
  from pathlib import Path
10
 
11
  import gradio as gr
12
 
13
- APP_NAME = "PoultryFeedCalc"
14
- DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
15
- DATA_DIR.mkdir(parents=True, exist_ok=True)
16
- LEADS_FILE = DATA_DIR / "farmer_leads.csv"
17
- QUESTIONS_FILE = DATA_DIR / "farmer_questions.csv"
18
-
19
- # ---------------------------------------------------------------------
20
- # BREED BENCHMARKS
21
- # Source basis: manufacturer 2022 "As-Hatched" performance objectives.
22
- # Values are grams/bird at the stated day.
23
- # For days between the published checkpoints, the app linearly
24
- # interpolates between the adjacent daily benchmark values.
25
- # ---------------------------------------------------------------------
26
-
27
- # Ross 308 AP - As-Hatched, 2022
28
- # Daily body weight and cumulative feed intake, days 0-56.
29
- ROSS_WEIGHT_G = [
30
- 44, 62, 80, 101, 125, 151, 181, 214, 250, 289, 332, 377, 426, 479,
31
- 537, 600, 668, 740, 818, 900, 986, 1076, 1170, 1268, 1370, 1476,
32
- 1586, 1700, 1818, 1940, 2066, 2196, 2330, 2468, 2610, 2756, 2906,
33
- 3060, 3218, 3380, 3546, 3716, 3890, 4068, 4250, 4436, 4626, 4819,
34
- 5016, 5217, 5422, 5631, 5843, 6060, 6280, 6503, 6730, 6961, 7195
35
- ]
36
- ROSS_CUM_FEED_G = [
37
- 0, 12, 28, 48, 71, 98, 130, 165, 204, 245, 290, 337, 387, 441,
38
- 498, 560, 624, 691, 762, 838, 917, 1000, 1086, 1176, 1270, 1368,
39
- 1469, 1574, 1683, 1795, 1910, 2027, 2147, 2270, 2396, 2525, 2657,
40
- 2792, 2930, 3071, 3215, 3362, 3512, 3665, 3821, 3980, 4142, 4307,
41
- 4475, 4646, 4820, 4997, 5177, 5359, 5544, 5732, 5923
42
- ]
43
-
44
- # Cobb 500 - As-Hatched, 2022
45
- # Daily values are taken from the published metric table.
46
- COBB_WEIGHT_G = [
47
- 42, 55, 71, 90, 112, 138, 168, 202, 240, 283, 330, 382, 440, 503,
48
- 570, 639, 711, 786, 864, 945, 1029, 1116, 1205, 1296, 1390, 1486,
49
- 1583, 1682, 1783, 1886, 1989, 2094, 2200, 2306, 2413, 2521, 2629,
50
- 2738, 2846, 2954, 3062, 3170, 3278, 3384, 3490, 3595, 3699, 3801,
51
- 3902, 4001, 4099, 4195, 4289, 4380, 4470, 4557, 4641
52
- ]
53
- COBB_CUM_FEED_G = [
54
- 0, 0, 0, 0, 0, 0, 0, 180, 220, 264, 314, 371, 435, 508,
55
- 588, 672, 763, 861, 966, 1077, 1195, 1320, 1451, 1588, 1731,
56
- 1880, 2034, 2194, 2359, 2528, 2702, 2880, 3063, 3250, 3441, 3635,
57
- 3833, 4035, 4241, 4450, 4663, 4880, 5100, 5324, 5552, 5784, 6020,
58
- 6259, 6502, 6749, 6999, 7252, 7508, 7766, 8026, 8287, 8549
59
- ]
60
- # Cobb's published table does not list cumulative feed for days 1-6.
61
- # The calculator therefore uses the first published cumulative-feed
62
- # checkpoint (day 7) for feed calculations in that early period.
63
-
64
- # Arbor Acres Plus - As-Hatched, 2022.
65
- # Daily values transcribed from the published objective table.
66
- AA_WEIGHT_G = [
67
- 43, 60, 78, 99, 123, 149, 179, 209, 246, 287, 333, 382, 435, 492,
68
- 527, 596, 666, 736, 808, 881, 956, 1006, 1089, 1174, 1260, 1347,
69
- 1435, 1523, 1611, 1710, 1809, 1908, 2008, 2107, 2206, 2297, 2386,
70
- 2486, 2585, 2684, 2784, 2882, 2981, 3079, 3176, 3272, 3368, 3462,
71
- 3556, 3649, 3740, 3831, 3921, 4010, 4098, 4185, 4272
72
- ]
73
- AA_CUM_FEED_G = [
74
- 0, 12, 28, 48, 71, 98, 130, 168, 210, 257, 308, 363, 422, 486,
75
- 538, 605, 675, 749, 827, 909, 994, 1163, 1253, 1350, 1453, 1561,
76
- 1673, 1789, 1909, 2033, 2161, 2293, 2429, 2569, 2713, 2862, 3015,
77
- 3173, 3336, 3503, 3673, 3849, 4029, 4214, 4405, 4601, 4801, 5006,
78
- 5216, 5429, 5648, 5869, 6093, 6320, 6550, 6783, 7019
79
- ]
80
-
81
- BREEDS = {
82
- "Ross 308 AP": (ROSS_WEIGHT_G, ROSS_CUM_FEED_G),
83
- "Cobb 500": (COBB_WEIGHT_G, COBB_CUM_FEED_G),
84
- "Arbor Acres Plus": (AA_WEIGHT_G, AA_CUM_FEED_G),
85
  }
86
 
87
- # Currency defaults. Country detection uses proxy headers when available.
88
- CURRENCY_BY_COUNTRY = {
89
- "NG": ("₦", "NGN", 1.0),
90
- "GH": ("β‚΅", "GHS", 0.00072),
91
- "KE": ("KSh", "KES", 0.00047),
92
- "UG": ("USh", "UGX", 0.00093),
93
- "TZ": ("TSh", "TZS", 0.00061),
94
- "ZA": ("R", "ZAR", 0.00055),
95
- "ZM": ("ZK", "ZMW", 0.00071),
96
- "US": ("$", "USD", 0.00062),
97
- "GB": ("Β£", "GBP", 0.00049),
98
- "CA": ("C$", "CAD", 0.00084),
99
- "AU": ("A$", "AUD", 0.00095),
 
 
 
 
100
  }
101
 
102
- # These are only used to suggest a local currency and convert the entered
103
- # local bag price into the app's internal NGN-equivalent benchmark.
104
- # The farmer can always edit the price per bag.
105
- def detect_country(request: gr.Request | None) -> str:
106
- if request is not None:
107
- headers = request.headers or {}
108
- for key in ("x-country", "cf-ipcountry", "x-vercel-ip-country", "x-country-code"):
109
- value = headers.get(key)
110
- if value and len(value) == 2:
111
- return value.upper()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  return "NG"
113
 
114
- def money(value: float, symbol: str) -> str:
115
- return f"{symbol}{value:,.0f}"
116
-
117
- def interpolate(values, day_float):
118
- if day_float <= 0:
119
- return float(values[0])
120
- max_day = len(values) - 1
121
- if day_float >= max_day:
122
- return float(values[-1])
123
- lo = int(math.floor(day_float))
124
- hi = lo + 1
125
- frac = day_float - lo
126
- return values[lo] + (values[hi] - values[lo]) * frac
127
-
128
- def feed_at_day(feed_values, day_float, breed):
129
- # Cobb has no published cumulative-feed entries for days 1-6.
130
- # Use the first published point rather than inventing early cumulative
131
- # feed values. For days <= 7, use a proportional interpolation from
132
- # hatch to day 7 as a transparent estimate.
133
- if breed == "Cobb 500" and day_float < 7:
134
- return 180.0 * (day_float / 7.0)
135
- return interpolate(feed_values, day_float)
136
-
137
- def age_label(weeks, days):
138
- total = weeks * 7 + days
139
- return f"{weeks} week{'s' if weeks != 1 else ''} + {days} day{'s' if days != 1 else ''} ({total} days)"
140
-
141
- def ensure_file(path: Path, header):
142
- if not path.exists():
143
- with path.open("w", newline="", encoding="utf-8") as f:
144
- csv.writer(f).writerow(header)
145
-
146
- ensure_file(LEADS_FILE, ["timestamp_utc", "email", "country", "currency"])
147
- ensure_file(QUESTIONS_FILE, ["timestamp_utc", "email", "question"])
148
-
149
- def save_lead(email, country, currency):
150
- email = (email or "").strip().lower()
151
- if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
152
- return False
153
- with LEADS_FILE.open("a", newline="", encoding="utf-8") as f:
154
- csv.writer(f).writerow([
155
- datetime.now(timezone.utc).isoformat(),
156
- email,
157
- country,
158
- currency,
159
- ])
160
- return True
161
-
162
- def save_question(email, question):
163
- email = (email or "").strip().lower()
164
- question = (question or "").strip()
165
- if not question:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  return False
167
- with QUESTIONS_FILE.open("a", newline="", encoding="utf-8") as f:
168
- csv.writer(f).writerow([
169
- datetime.now(timezone.utc).isoformat(),
170
- email,
171
- question,
172
- ])
173
- return True
174
-
175
- def country_currency(request):
176
- country = detect_country(request)
177
- symbol, code, _ = CURRENCY_BY_COUNTRY.get(country, ("$", "USD", 0.00062))
178
- return country, symbol, code
179
-
180
- def update_currency(request):
181
- country, symbol, code = country_currency(request)
182
- default_price = 24000 if code == "NGN" else 0
183
- return (
184
- gr.update(value=f"{symbol} {code}"),
185
- gr.update(value=default_price),
186
- f"Detected country: **{country}** Β· Currency: **{symbol} {code}**"
187
- )
188
 
189
- def calculate(
190
- email,
191
- breed,
192
- birds,
193
- weeks,
194
- days,
195
- bag_size,
196
- price_per_bag,
197
- request: gr.Request | None = None,
198
- ):
199
- email = (email or "").strip().lower()
200
-
201
- if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
202
- return (
203
- gr.update(value="### Email required\nPlease enter a valid email address before calculating."),
204
- gr.update(visible=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  )
 
 
 
 
 
 
 
 
 
206
 
 
 
 
 
 
 
207
  try:
208
  birds = int(birds)
209
  weeks = int(weeks)
@@ -211,269 +301,438 @@ def calculate(
211
  bag_size = float(bag_size)
212
  price_per_bag = float(price_per_bag)
213
  except Exception:
214
- return (
215
- gr.update(value="### Please check your inputs\nEnter valid numbers."),
216
- gr.update(visible=True),
217
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
- if birds <= 0 or weeks < 0 or days < 0 or days > 6 or bag_size <= 0 or price_per_bag < 0:
220
- return (
221
- gr.update(value="### Please check your inputs\nThe age days must be 0–6 and all quantities must be positive."),
222
- gr.update(visible=True),
223
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
- total_days = weeks * 7 + days
226
- if total_days > 56:
227
- return (
228
- gr.update(value="### Maximum benchmark age is 8 weeks (56 days).\nPlease select an age from 0–56 days."),
229
- gr.update(visible=True),
230
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
- country, symbol, code = country_currency(request)
233
- save_lead(email, country, code)
234
 
235
- weight_values, feed_values = BREEDS[breed]
236
- weight_g = interpolate(weight_values, total_days)
237
- cumulative_g = feed_at_day(feed_values, total_days, breed)
238
 
239
- # Starter is the benchmark cumulative feed through day 21.
240
- starter_cutoff = min(total_days, 21)
241
- starter_g_per_bird = feed_at_day(feed_values, starter_cutoff, breed)
242
- total_g_per_bird = cumulative_g
243
- finisher_g_per_bird = max(0.0, total_g_per_bird - starter_g_per_bird)
244
 
245
- total_feed_kg = birds * total_g_per_bird / 1000
246
- starter_kg = birds * starter_g_per_bird / 1000
247
- finisher_kg = birds * finisher_g_per_bird / 1000
248
 
249
- exact_bags = total_feed_kg / bag_size
250
- whole_bags = math.ceil(exact_bags)
251
 
252
- starter_exact_bags = starter_kg / bag_size
253
- finisher_exact_bags = finisher_kg / bag_size
254
 
255
- # Purchase bags are rounded separately by feed type, because farmers
256
- # normally buy whole bags of starter and finisher.
257
- starter_buy = math.ceil(starter_exact_bags) if starter_kg > 0 else 0
258
- finisher_buy = math.ceil(finisher_exact_bags) if finisher_kg > 0 else 0
259
- purchase_bags = starter_buy + finisher_buy
260
- purchase_cost = purchase_bags * price_per_bag
261
 
262
- # The feed quantity itself is exact benchmark estimate; only the
263
- # purchasable whole-bag quantity is rounded up.
264
- expected_flock_weight_kg = birds * weight_g / 1000
265
 
266
- result = f"""
267
- # πŸ” Your Feed Requirement
 
 
 
 
 
268
 
269
- ## To raise **{birds:,} {breed} birds** to **{age_label(weeks, days)}**
 
 
 
 
270
 
271
- ### 🎯 Quick answer
 
 
 
 
272
 
273
- **You will require an estimated {exact_bags:.2f} bags of {bag_size:g} kg feed.**
 
 
 
 
274
 
275
- Because feed is sold in whole bags, **buy approximately {purchase_bags} bags**:
276
 
277
- **{starter_buy} Starter + {finisher_buy} Finisher**
 
 
 
 
278
 
279
- ### πŸ’° Estimated feed cost
280
 
281
- **Approximately {money(purchase_cost, symbol)}**
 
 
 
 
282
 
283
- This is the estimated cost of **feed alone**, using **{money(price_per_bag, symbol)} per {bag_size:g}-kg bag**.
284
 
285
- ### 🌾 Feed breakdown
286
 
287
- | Feed | Estimated quantity | Exact bag equivalent | Whole bags to buy |
288
- |---|---:|---:|---:|
289
- | 🌱 Starter | **{starter_kg:.1f} kg** | {starter_exact_bags:.2f} | **{starter_buy}** |
290
- | 🌽 Finisher | **{finisher_kg:.1f} kg** | {finisher_exact_bags:.2f} | **{finisher_buy}** |
291
- | **TOTAL** | **{total_feed_kg:.1f} kg** | **{exact_bags:.2f}** | **{purchase_bags}** |
292
 
293
- ### πŸ” Expected benchmark weight
294
 
295
- **{weight_g/1000:.2f} kg per bird**
296
 
297
- Expected live weight of the flock:
 
298
 
299
- **{expected_flock_weight_kg:.1f} kg**
300
 
301
- ### πŸ“Š Breed benchmark
302
 
303
- - Breed: **{breed}**
304
- - Age: **{total_days} days**
305
- - Cumulative benchmark feed: **{cumulative_g/1000:.3f} kg/bird**
306
- - No artificial 20% allowance has been added.
307
- - The bag quantity is rounded **up only because bags are purchased whole**.
308
 
309
- > **Important:** These are manufacturer performance objectives used as a benchmark. Actual farm consumption and growth can differ with genetics, sex, mortality, feed quality, temperature, health and management.
310
- """
 
 
311
 
312
- return gr.update(value=result), gr.update(visible=True)
313
 
314
- def ask_question(email, question):
315
- if not email or not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email.strip()):
316
- return "Please enter your email above first so we can attach the question to your farmer record."
317
- if save_question(email, question):
318
- return "βœ… Question saved. We will use farmer questions to guide future upgrades."
319
- return "Please type a question first."
320
 
321
- # ---------------------------------------------------------------------
322
- # UI
323
- # ---------------------------------------------------------------------
 
324
 
325
  CSS = """
326
- body { background: #f7f7f7; }
327
- .gradio-container { max-width: 1250px !important; }
328
- .hero {
329
- padding: 22px 26px; border-radius: 16px; background: white;
330
- border: 1px solid #e6e6e6; margin-bottom: 18px;
331
- }
332
- .answer {
333
- background: white; border-radius: 16px; padding: 20px;
334
- border: 1px solid #e6e6e6;
335
- }
336
  """
337
 
338
- with gr.Blocks(title=APP_NAME) as demo:
 
 
 
 
 
 
339
  gr.HTML("""
340
- <div class="hero">
341
- <h1>πŸ” PoultryFeedCalc</h1>
342
- <h3>Simple broiler feed calculator for farmers</h3>
343
- <p>Select the breed, number of birds, age, bag size and price.
344
- <b>No calculations required.</b></p>
345
  </div>
346
  """)
347
 
348
- with gr.Row():
349
- with gr.Column(scale=1):
350
- gr.Markdown("## πŸ“§ Before you calculate")
351
- gr.Markdown("Enter your email so we can send PoultryFeedCalc updates and improvements. Your email is used for PoultryFeedCalc communications.")
352
- email = gr.Textbox(
353
- label="Email address *",
354
- placeholder="farmer@example.com",
355
- type="email",
356
- )
357
 
358
- country_status = gr.Markdown("Detecting country and currency…")
359
- currency_display = gr.Textbox(label="Detected currency", interactive=False)
360
 
361
- gr.Markdown("## πŸ” Farm inputs")
362
- breed = gr.Dropdown(
363
- choices=list(BREEDS.keys()),
364
- value="Ross 308 AP",
365
- label="Broiler breed",
366
- )
367
- birds = gr.Dropdown(
368
- choices=[25, 50, 75, 100, 150, 200, 500, 1000],
369
- value=50,
370
- allow_custom_value=True,
371
- label="Number of birds",
372
- )
373
- with gr.Row():
374
- weeks = gr.Dropdown(
375
- choices=list(range(0, 9)),
376
- value=6,
377
- label="Age β€” Weeks",
378
  )
379
- days = gr.Dropdown(
380
- choices=list(range(0, 7)),
381
- value=0,
382
- label="Age β€” Days",
 
 
383
  )
384
- bag_size = gr.Dropdown(
385
- choices=[10, 20, 25, 50],
386
- value=25,
387
- label="Feed bag size (kg)",
388
- )
389
- price = gr.Number(
390
- value=24000,
391
- label="Price per bag",
392
- minimum=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  )
394
 
395
  calculate_btn = gr.Button(
396
- "πŸ” Calculate Feed Requirements",
397
  variant="primary",
398
  size="lg",
399
  )
400
 
401
- with gr.Column(scale=1):
 
 
 
 
402
  gr.Markdown("## 🎯 Quick Answer")
403
- output = gr.Markdown(
404
- "Enter your email and farm details, then click **Calculate Feed Requirements**.",
405
- elem_classes=["answer"],
 
 
 
 
 
 
 
406
  )
407
 
 
408
  gr.Markdown("---")
409
- gr.Markdown("## ❓ Ask a question")
410
- gr.Markdown("**What would you like to know about raising your birds?**")
411
- gr.Markdown("Type your question. Questions are saved to guide future app upgrades and answers.")
412
 
413
  with gr.Row():
414
- question = gr.Textbox(
415
- label="Your question",
416
- placeholder="Example: How much water will 100 broilers drink at 5 weeks?",
417
- lines=3,
418
- scale=4,
419
- )
420
- ask_btn = gr.Button("πŸ’Ύ Save Question", scale=1)
 
 
 
 
421
 
422
- question_status = gr.Markdown()
 
423
 
 
424
  gr.Markdown("---")
425
- gr.Markdown("## πŸ” Common broiler breeds in Nigeria")
426
  gr.Markdown("""
427
- | Breed | What farmers commonly look for |
428
- |---|---|
429
- | **Ross 308 AP** | Fast growth, strong meat-production performance |
430
- | **Cobb 500** | Strong growth and feed-efficiency performance |
431
- | **Arbor Acres Plus** | Balanced growth, feed conversion and livability |
 
 
432
 
433
- **Tip:** Ask the hatchery what breed you are buying before purchasing chicks.
434
- """)
435
 
 
436
  gr.Markdown("---")
437
- gr.Markdown("### πŸ“š Benchmark note")
438
- gr.Markdown(
439
- "The calculator uses manufacturer **As-Hatched** performance objectives. "
440
- "As-Hatched means the benchmark represents the mixed-sex flock objective, "
441
- "rather than male-only or female-only performance."
442
- )
443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
  calculate_btn.click(
445
- calculate,
446
- inputs=[email, breed, birds, weeks, days, bag_size, price],
447
- outputs=[output, output],
448
  )
449
 
450
- # Save question automatically when the farmer asks/saves it.
451
  ask_btn.click(
452
- ask_question,
453
- inputs=[email, question],
454
- outputs=[question_status],
455
  )
456
 
457
- # Detect country/currency when the app loads.
458
- demo.load(
459
- update_currency,
460
- inputs=[],
461
- outputs=[currency_display, price, country_status],
462
- )
463
 
464
  if __name__ == "__main__":
465
  port = int(os.environ.get("PORT", "7860"))
466
- demo.launch(
467
- server_name="0.0.0.0",
468
- server_port=port,
469
- show_error=True,
470
- )
471
- '''
472
-
473
- path = Path("/mnt/data/app.py")
474
- path.write_text(app_code, encoding="utf-8")
475
- compile(app_code, str(path), "exec")
476
-
477
- print(f"Created: {path}")
478
- print("Syntax check: OK")
479
- print("Important: replace the existing app.py with this file; do not keep the old patching script.")
 
 
 
 
1
  import os
 
2
  import math
3
  import re
4
+ import sqlite3
5
+ from datetime import datetime
6
  from pathlib import Path
7
 
8
  import gradio as gr
9
 
10
+
11
+ # ============================================================
12
+ # APP CONFIG
13
+ # ============================================================
14
+
15
+ APP_NAME = "Poultry Feed Calculator"
16
+ DB_PATH = os.environ.get("DATABASE_PATH", "poultry_calculator.db")
17
+
18
+ STARTER_END_DAY = 21
19
+
20
+ # ============================================================
21
+ # VERIFIED BREED DATA - From Official PDFs
22
+ # ============================================================
23
+
24
+ # Body Weight (kg) at key days - As-Hatched Performance
25
+ BREED_WEIGHT_DATA = {
26
+ "Ross 308": {
27
+ 0: 0.044, 7: 0.213, 14: 0.533, 21: 1.012,
28
+ 28: 1.616, 35: 2.296, 42: 2.998, 49: 3.681, 56: 4.318,
29
+ },
30
+ "Cobb 500": {
31
+ 0: 0.042, 7: 0.177, 14: 0.459, 21: 0.891,
32
+ 28: 1.436, 35: 2.067, 42: 2.732, 49: 3.369, 56: 3.958,
33
+ },
34
+ "Arbor Acres": {
35
+ 0: 0.044, 7: 0.209, 14: 0.527, 21: 1.006,
36
+ 28: 1.611, 35: 2.287, 42: 2.964, 49: 3.662, 56: 4.318,
37
+ }
38
+ }
39
+
40
+ # Cumulative Feed (kg) at key days - As-Hatched Performance
41
+ BREED_FEED_DATA = {
42
+ "Ross 308": {
43
+ 0: 0.000, 7: 0.166, 14: 0.535, 21: 1.155,
44
+ 28: 2.051, 35: 3.211, 42: 4.586, 49: 6.115, 56: 7.733,
45
+ },
46
+ "Cobb 500": {
47
+ 0: 0.000, 7: 0.150, 14: 0.465, 21: 1.053,
48
+ 28: 1.963, 35: 3.216, 42: 4.659, 49: 6.185, 56: 7.772,
49
+ },
50
+ "Arbor Acres": {
51
+ 0: 0.000, 7: 0.207, 14: 0.638, 21: 1.163,
52
+ 28: 2.069, 35: 3.237, 42: 4.625, 49: 6.111, 56: 7.647,
53
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
 
56
+ # Breed descriptions and availability
57
+ BREED_INFO = {
58
+ "Ross 308": {
59
+ "description": "Big chest, thick legs, very fast growth. Excellent for meat production.",
60
+ "available_at": "Agrited, Sayed, Valentine",
61
+ "color": "#16a34a"
62
+ },
63
+ "Cobb 500": {
64
+ "description": "Good early growth, strong legs, solid feed conversion.",
65
+ "available_at": "Chikun, Zartech",
66
+ "color": "#2563eb"
67
+ },
68
+ "Arbor Acres": {
69
+ "description": "Balanced growth, hardy and adaptable. Great survival rate.",
70
+ "available_at": "Supreme, CHI, GS, Vertex, Fidan, Cascada, Orobor, Sunchi, Farm Support, Ajila",
71
+ "color": "#d97706"
72
+ }
73
  }
74
 
75
+
76
+ def get_breed_weight_data(breed):
77
+ return BREED_WEIGHT_DATA.get(breed, BREED_WEIGHT_DATA["Ross 308"])
78
+
79
+
80
+ def get_breed_feed_data(breed):
81
+ return BREED_FEED_DATA.get(breed, BREED_FEED_DATA["Ross 308"])
82
+
83
+
84
+ def interpolate_weight(day, breed):
85
+ """Interpolate body weight between known checkpoints."""
86
+ weight_data = get_breed_weight_data(breed)
87
+
88
+ if day <= 0:
89
+ return weight_data[0]
90
+ if day >= 56:
91
+ return weight_data[56]
92
+
93
+ keys = sorted(weight_data.keys())
94
+ for i in range(len(keys) - 1):
95
+ if keys[i] <= day <= keys[i + 1]:
96
+ ratio = (day - keys[i]) / (keys[i + 1] - keys[i])
97
+ return weight_data[keys[i]] + (weight_data[keys[i + 1]] - weight_data[keys[i]]) * ratio
98
+
99
+ return weight_data[56]
100
+
101
+
102
+ def interpolate_feed(day, breed):
103
+ """Interpolate cumulative feed between known checkpoints."""
104
+ feed_data = get_breed_feed_data(breed)
105
+
106
+ if day <= 0:
107
+ return 0.0
108
+ if day >= 56:
109
+ return feed_data[56]
110
+
111
+ keys = sorted(feed_data.keys())
112
+ for i in range(len(keys) - 1):
113
+ if keys[i] <= day <= keys[i + 1]:
114
+ ratio = (day - keys[i]) / (keys[i + 1] - keys[i])
115
+ return feed_data[keys[i]] + (feed_data[keys[i + 1]] - feed_data[keys[i]]) * ratio
116
+
117
+ return feed_data[56]
118
+
119
+
120
+ # ============================================================
121
+ # CURRENCY
122
+ # ============================================================
123
+
124
+ CURRENCIES = {
125
+ "NG": ("Nigeria", "₦", "NGN"),
126
+ "GH": ("Ghana", "β‚΅", "GHS"),
127
+ "KE": ("Kenya", "KSh", "KES"),
128
+ "UG": ("Uganda", "USh", "UGX"),
129
+ "TZ": ("Tanzania", "TSh", "TZS"),
130
+ "ZA": ("South Africa", "R", "ZAR"),
131
+ "ZM": ("Zambia", "ZK", "ZMW"),
132
+ "ZW": ("Zimbabwe", "ZiG", "ZWG"),
133
+ "CM": ("Cameroon", "FCFA", "XAF"),
134
+ "CI": ("CΓ΄te d'Ivoire", "CFA", "XOF"),
135
+ "SN": ("Senegal", "CFA", "XOF"),
136
+ "US": ("United States", "$", "USD"),
137
+ "GB": ("United Kingdom", "Β£", "GBP"),
138
+ "CA": ("Canada", "C$", "CAD"),
139
+ "AU": ("Australia", "A$", "AUD"),
140
+ }
141
+
142
+
143
+ def detect_country():
144
+ candidates = [
145
+ os.environ.get("COUNTRY_CODE"),
146
+ os.environ.get("CF-IPCOUNTRY"),
147
+ os.environ.get("GEOIP_COUNTRY"),
148
+ ]
149
+
150
+ for value in candidates:
151
+ if value:
152
+ value = value.strip().upper()
153
+ if value in CURRENCIES:
154
+ return value
155
+
156
  return "NG"
157
 
158
+
159
+ def currency_for_country(country_code):
160
+ data = CURRENCIES.get(country_code, CURRENCIES["NG"])
161
+ return data[1]
162
+
163
+
164
+ # ============================================================
165
+ # DATABASE
166
+ # ============================================================
167
+
168
+ def init_db():
169
+ conn = sqlite3.connect(DB_PATH)
170
+ cur = conn.cursor()
171
+
172
+ cur.execute("""
173
+ CREATE TABLE IF NOT EXISTS leads (
174
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
175
+ email TEXT UNIQUE,
176
+ country TEXT,
177
+ currency TEXT,
178
+ breed TEXT,
179
+ created_at TEXT
180
+ )
181
+ """)
182
+
183
+ cur.execute("""
184
+ CREATE TABLE IF NOT EXISTS farmer_questions (
185
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
186
+ email TEXT,
187
+ question TEXT,
188
+ breed TEXT,
189
+ created_at TEXT
190
+ )
191
+ """)
192
+
193
+ cur.execute("""
194
+ CREATE TABLE IF NOT EXISTS calculations (
195
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
196
+ email TEXT,
197
+ country TEXT,
198
+ currency TEXT,
199
+ breed TEXT,
200
+ birds INTEGER,
201
+ weeks INTEGER,
202
+ days INTEGER,
203
+ total_days INTEGER,
204
+ bag_size REAL,
205
+ price_per_bag REAL,
206
+ total_feed_kg REAL,
207
+ starter_kg REAL,
208
+ finisher_kg REAL,
209
+ starter_bags REAL,
210
+ finisher_bags REAL,
211
+ total_bags REAL,
212
+ rounded_bags INTEGER,
213
+ total_cost REAL,
214
+ created_at TEXT
215
+ )
216
+ """)
217
+
218
+ conn.commit()
219
+ conn.close()
220
+
221
+
222
+ init_db()
223
+
224
+
225
+ # ============================================================
226
+ # DATABASE HELPERS
227
+ # ============================================================
228
+
229
+ def valid_email(email):
230
+ if not email:
231
  return False
232
+ email = email.strip()
233
+ pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
234
+ return bool(re.match(pattern, email))
235
+
236
+
237
+ def save_lead(email, country, currency, breed):
238
+ if not valid_email(email):
239
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
+ conn = sqlite3.connect(DB_PATH)
242
+ cur = conn.cursor()
243
+
244
+ cur.execute("""
245
+ INSERT OR IGNORE INTO leads (email, country, currency, breed, created_at)
246
+ VALUES (?, ?, ?, ?, ?)
247
+ """, (email.strip().lower(), country, currency, breed, datetime.utcnow().isoformat()))
248
+
249
+ conn.commit()
250
+ conn.close()
251
+
252
+
253
+ def save_question(email, question, breed):
254
+ if not question or not question.strip():
255
+ return
256
+
257
+ conn = sqlite3.connect(DB_PATH)
258
+ cur = conn.cursor()
259
+
260
+ cur.execute("""
261
+ INSERT INTO farmer_questions (email, question, breed, created_at)
262
+ VALUES (?, ?, ?, ?)
263
+ """, (email.strip().lower() if email else "", question.strip(), breed, datetime.utcnow().isoformat()))
264
+
265
+ conn.commit()
266
+ conn.close()
267
+
268
+
269
+ def save_calculation(email, country, currency, breed, birds, weeks, days, total_days,
270
+ bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
271
+ starter_bags, finisher_bags, total_bags, rounded_bags, total_cost):
272
+ conn = sqlite3.connect(DB_PATH)
273
+ cur = conn.cursor()
274
+
275
+ cur.execute("""
276
+ INSERT INTO calculations (
277
+ email, country, currency, breed, birds, weeks, days, total_days,
278
+ bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
279
+ starter_bags, finisher_bags, total_bags, rounded_bags, total_cost, created_at
280
  )
281
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
282
+ """, (email.strip().lower() if email else "", country, currency, breed, birds, weeks, days, total_days,
283
+ bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
284
+ starter_bags, finisher_bags, total_bags, rounded_bags, total_cost,
285
+ datetime.utcnow().isoformat()))
286
+
287
+ conn.commit()
288
+ conn.close()
289
+
290
 
291
+ # ============================================================
292
+ # FEED CALCULATION
293
+ # ============================================================
294
+
295
+ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_code, breed):
296
+ # Validation
297
  try:
298
  birds = int(birds)
299
  weeks = int(weeks)
 
301
  bag_size = float(bag_size)
302
  price_per_bag = float(price_per_bag)
303
  except Exception:
304
+ return "⚠️ Please enter valid numbers."
305
+
306
+ if birds <= 0:
307
+ return "⚠️ Number of birds must be greater than zero."
308
+ if weeks < 0:
309
+ return "⚠️ Weeks cannot be negative."
310
+ if days < 0 or days > 6:
311
+ return "⚠️ Days must be between 0 and 6."
312
+ if bag_size <= 0:
313
+ return "⚠️ Feed bag size must be greater than zero."
314
+ if price_per_bag < 0:
315
+ return "⚠️ Price per bag cannot be negative."
316
+
317
+ if not valid_email(email):
318
+ return "πŸ“§ **Email required**\n\nPlease enter your email address before calculating."
319
+
320
+ # Country / Currency
321
+ country_code = country_code or "NG"
322
+ if country_code not in CURRENCIES:
323
+ country_code = "NG"
324
+ currency = currency_for_country(country_code)
325
+
326
+ # Save lead with breed
327
+ save_lead(email, country_code, currency, breed)
328
+
329
+ # Total days
330
+ total_days = (weeks * 7) + days
331
+
332
+ # Total feed
333
+ total_feed_per_bird = interpolate_feed(total_days, breed)
334
+ total_feed_kg = birds * total_feed_per_bird
335
+
336
+ # Starter / Finisher
337
+ starter_days = min(total_days, STARTER_END_DAY)
338
+ starter_per_bird = interpolate_feed(starter_days, breed)
339
+ starter_kg = birds * starter_per_bird
340
+ finisher_kg = max(total_feed_kg - starter_kg, 0)
341
+
342
+ # Bags
343
+ starter_bags = starter_kg / bag_size
344
+ finisher_bags = finisher_kg / bag_size
345
+ total_bags = total_feed_kg / bag_size
346
+ rounded_bags = math.ceil(total_bags)
347
+ total_cost = rounded_bags * price_per_bag
348
+
349
+ # Expected performance
350
+ expected_weight = interpolate_weight(total_days, breed)
351
+ flock_weight = expected_weight * birds
352
+
353
+ # Save calculation
354
+ save_calculation(email, country_code, currency, breed, birds, weeks, days, total_days,
355
+ bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
356
+ starter_bags, finisher_bags, total_bags, rounded_bags, total_cost)
357
+
358
+ # Breed info
359
+ breed_info = BREED_INFO.get(breed, BREED_INFO["Ross 308"])
360
+ breed_color = breed_info["color"]
361
+
362
+ # Output HTML
363
+ starter_bags_display = f"{starter_bags:.1f}"
364
+ finisher_bags_display = f"{finisher_bags:.1f}"
365
+
366
+ age_text = f"{weeks} week{'s' if weeks != 1 else ''}"
367
+ if days:
368
+ age_text += f" + {days} day{'s' if days != 1 else ''}"
369
+
370
+ html = f"""
371
+ <div style="font-size: 18px; line-height: 1.6;">
372
+
373
+ <div style="background: #f0fdf4; padding: 16px 20px; border-radius: 12px; border-left: 5px solid #22c55e; margin-bottom: 20px;">
374
+ <div style="font-size: 14px; color: #16a34a; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">🎯 Quick Answer</div>
375
+ <div style="font-size: 22px; font-weight: 700; color: #166534;">
376
+ {rounded_bags} bags of {bag_size:g} kg feed
377
+ </div>
378
+ <div style="color: #4b5563; margin-top: 4px;">
379
+ To raise <strong>{birds:,} birds</strong> for <strong>{age_text} ({total_days} days)</strong>
380
+ </div>
381
+ <div style="margin-top: 6px; font-size: 14px;">
382
+ <span style="background: {breed_color}; color: white; padding: 2px 10px; border-radius: 12px; font-weight: 600;">{breed}</span>
383
+ </div>
384
+ </div>
385
 
386
+ <div style="margin-bottom: 16px;">
387
+ <div style="font-size: 14px; color: #6b7280; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">🌾 Feed Breakdown</div>
388
+ <table style="width: 100%; border-collapse: collapse; margin-top: 6px;">
389
+ <tr style="border-bottom: 1px solid #e5e7eb;">
390
+ <td style="padding: 8px 4px;"><strong>🌱 Starter</strong></td>
391
+ <td style="padding: 8px 4px; text-align: right;">{starter_kg:,.1f} kg</td>
392
+ <td style="padding: 8px 4px; text-align: right; font-weight: 600;">{starter_bags_display} bags</td>
393
+ </tr>
394
+ <tr style="border-bottom: 1px solid #e5e7eb;">
395
+ <td style="padding: 8px 4px;"><strong>🌽 Finisher</strong></td>
396
+ <td style="padding: 8px 4px; text-align: right;">{finisher_kg:,.1f} kg</td>
397
+ <td style="padding: 8px 4px; text-align: right; font-weight: 600;">{finisher_bags_display} bags</td>
398
+ </tr>
399
+ <tr>
400
+ <td style="padding: 8px 4px; font-weight: 700;">TOTAL</td>
401
+ <td style="padding: 8px 4px; text-align: right; font-weight: 700;">{total_feed_kg:,.1f} kg</td>
402
+ <td style="padding: 8px 4px; text-align: right; font-weight: 700;">{total_bags:.1f}</td>
403
+ </tr>
404
+ </table>
405
+ </div>
406
 
407
+ <div style="margin-bottom: 16px;">
408
+ <div style="font-size: 14px; color: #6b7280; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">πŸ’° Feed Cost</div>
409
+ <div style="font-size: 28px; font-weight: 800; color: #1e40af;">
410
+ {currency}{total_cost:,.0f}
411
+ </div>
412
+ <div style="color: #6b7280; font-size: 14px;">
413
+ {rounded_bags} bags Γ— {currency}{price_per_bag:,.0f} per bag
414
+ </div>
415
+ </div>
416
+
417
+ <div style="border-top: 1px solid #e5e7eb; padding-top: 14px;">
418
+ <div style="font-size: 14px; color: #6b7280; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">πŸ“Š Expected Performance</div>
419
+ <table style="width: 100%; border-collapse: collapse; margin-top: 6px;">
420
+ <tr style="border-bottom: 1px solid #e5e7eb;">
421
+ <td style="padding: 6px 4px;">Body weight / bird</td>
422
+ <td style="padding: 6px 4px; text-align: right; font-weight: 600;">{expected_weight:.3f} kg</td>
423
+ </tr>
424
+ <tr>
425
+ <td style="padding: 6px 4px;">Flock live weight</td>
426
+ <td style="padding: 6px 4px; text-align: right; font-weight: 600;">{flock_weight:,.1f} kg</td>
427
+ </tr>
428
+ </table>
429
+ </div>
430
+
431
+ <div style="margin-top: 14px; font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 10px;">
432
+ Estimate based on {breed} benchmark. Actual results may vary.
433
+ </div>
434
+ </div>
435
+ """
436
 
437
+ return html
 
438
 
 
 
 
439
 
440
+ # ============================================================
441
+ # QUESTION / ANSWER
442
+ # ============================================================
 
 
443
 
444
+ def answer_farmer_question(question, email, breed):
445
+ if not question or not question.strip():
446
+ return "Please type or speak your question first."
447
 
448
+ save_question(email or "", question, breed)
 
449
 
450
+ q = question.lower().strip()
 
451
 
452
+ if "bag" in q and ("feed" in q or "birds" in q):
453
+ answer = """
454
+ ### πŸ” Feed-bag questions
 
 
 
455
 
456
+ For an exact feed estimate, use the calculator above.
 
 
457
 
458
+ Enter:
459
+ 1. Number of birds
460
+ 2. Age in weeks + days
461
+ 3. Feed bag size
462
+ 4. Price per bag
463
+ 5. Your email
464
+ 6. Breed
465
 
466
+ The calculator will give you the estimated total bags, starter/finisher breakdown and feed cost.
467
+ """
468
+ elif "breed" in q or "ross" in q or "cobb" in q or "arbor" in q:
469
+ answer = """
470
+ ### πŸ” Common Broiler Breeds in Nigeria
471
 
472
+ | Breed | Characteristics | Available At |
473
+ |-------|-----------------|--------------|
474
+ | **Ross 308** | Big chest, thick legs, very fast growth | Agrited, Sayed, Valentine |
475
+ | **Cobb 500** | Good early growth, strong legs | Chikun, Zartech |
476
+ | **Arbor Acres** | Balanced growth, hardy, adaptable | Supreme, CHI, GS, Vertex, Fidan, Cascada, Orobor, Sunchi, Farm Support, Ajila |
477
 
478
+ πŸ’‘ **Tip:** Before buying chicks, ask about the breed and hatchery. Not all broilers are the same!
479
+ """
480
+ elif "starter" in q:
481
+ answer = f"""
482
+ ### 🌾 Starter feed
483
 
484
+ Starter feed is used during the early growth period (Day 0–{STARTER_END_DAY}).
485
 
486
+ The calculator separates the estimated feed requirement into **Starter** and **Finisher** based on the selected age.
487
+ """
488
+ elif "finisher" in q:
489
+ answer = f"""
490
+ ### 🌾 Finisher feed
491
 
492
+ Finisher feed is used after day {STARTER_END_DAY}.
493
 
494
+ Your calculator automatically estimates the finisher requirement from the selected number of birds and total age.
495
+ """
496
+ elif "cost" in q or "price" in q:
497
+ answer = """
498
+ ### πŸ’° Feed cost
499
 
500
+ Enter the current price of one feed bag in the calculator.
501
 
502
+ The app calculates: **Number of bags Γ— price per bag = estimated feed cost**
503
 
504
+ The result is for **feed alone**.
505
+ """
506
+ else:
507
+ answer = f"""
508
+ ### πŸ’‘ Question received
509
 
510
+ **β€œ{question.strip()}”**
511
 
512
+ Your question has been saved.
513
 
514
+ We can use the questions farmers submit to decide which answers, calculators and features should be added to the app next.
515
+ """
516
 
517
+ return answer
518
 
 
519
 
520
+ # ============================================================
521
+ # COUNTRY / CURRENCY UI
522
+ # ============================================================
 
 
523
 
524
+ def get_country_info():
525
+ country = detect_country()
526
+ currency = currency_for_country(country)
527
+ return country, currency
528
 
 
529
 
530
+ DEFAULT_COUNTRY, DEFAULT_CURRENCY = get_country_info()
 
 
 
 
 
531
 
532
+
533
+ # ============================================================
534
+ # CSS
535
+ # ============================================================
536
 
537
  CSS = """
538
+ body { background: #f6f8f4; }
539
+ .gradio-container { max-width: 1200px !important; margin: auto !important; }
540
+ .main-title { text-align: center; padding: 15px 10px 5px 10px; }
541
+ .main-title h1 { font-size: 34px; margin-bottom: 4px; }
542
+ .main-title p { font-size: 17px; color: #555; }
543
+ .answer-box { background: white; border-radius: 16px; padding: 16px 20px; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.05); min-height: 400px; }
544
+ .email-box { border: 2px solid #d9e7d2; border-radius: 12px; padding: 10px; background: #fbfdf9; }
545
+ button { min-height: 48px !important; }
 
 
546
  """
547
 
548
+
549
+ # ============================================================
550
+ # UI
551
+ # ============================================================
552
+
553
+ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
554
+
555
  gr.HTML("""
556
+ <div class="main-title">
557
+ <h1>πŸ” Poultry Feed Calculator</h1>
558
+ <p>Know exactly how much feed you need before buying.</p>
 
 
559
  </div>
560
  """)
561
 
562
+ # Breed Info Banner
563
+ gr.Markdown("""
564
+ ### πŸ” Select your breed
565
+ **Ross 308** β€” Fastest growth, big chest | **Cobb 500** β€” Good early growth | **Arbor Acres** β€” Hardy & adaptable
566
+ """)
 
 
 
 
567
 
568
+ with gr.Row(equal_height=True):
 
569
 
570
+ # LEFT COLUMN: INPUTS
571
+ with gr.Column(scale=1, min_width=350):
572
+
573
+ with gr.Group():
574
+ gr.Markdown("## πŸ” 1. Breed & Number of birds")
575
+
576
+ breed = gr.Dropdown(
577
+ choices=["Ross 308", "Cobb 500", "Arbor Acres"],
578
+ value="Ross 308",
579
+ label="Breed",
580
+ info="Select your broiler breed for accurate estimates",
 
 
 
 
 
 
581
  )
582
+
583
+ birds = gr.Dropdown(
584
+ choices=[25, 50, 75, 100, 150, 200, 500, 1000],
585
+ value=50,
586
+ label="Number of birds",
587
+ allow_custom_value=True,
588
  )
589
+
590
+ gr.Markdown("## πŸ“… 2. Age")
591
+
592
+ with gr.Row():
593
+ weeks = gr.Dropdown(
594
+ choices=list(range(0, 21)),
595
+ value=6,
596
+ label="Weeks",
597
+ )
598
+ days = gr.Dropdown(
599
+ choices=list(range(0, 7)),
600
+ value=0,
601
+ label="+ Days",
602
+ )
603
+
604
+ gr.Markdown("## 🌾 3. Feed")
605
+
606
+ with gr.Row():
607
+ bag_size = gr.Dropdown(
608
+ choices=[10, 20, 25, 50],
609
+ value=25,
610
+ label="Bag size (kg)",
611
+ )
612
+ price = gr.Number(
613
+ value=24000,
614
+ label=f"Price per bag ({DEFAULT_CURRENCY})",
615
+ minimum=0,
616
+ )
617
+
618
+ gr.Markdown("## πŸ“§ 4. Your email")
619
+
620
+ email = gr.Textbox(
621
+ label="",
622
+ placeholder="farmer@example.com",
623
+ type="email",
624
+ elem_classes=["email-box"],
625
  )
626
 
627
  calculate_btn = gr.Button(
628
+ "πŸ” Calculate",
629
  variant="primary",
630
  size="lg",
631
  )
632
 
633
+ country_state = gr.State(DEFAULT_COUNTRY)
634
+
635
+ # RIGHT COLUMN: RESULTS
636
+ with gr.Column(scale=1, min_width=350):
637
+
638
  gr.Markdown("## 🎯 Quick Answer")
639
+
640
+ result = gr.HTML(
641
+ value="""
642
+ <div style="font-size: 16px; color: #9ca3af; text-align: center; padding: 40px 20px;">
643
+ <div style="font-size: 48px; margin-bottom: 12px;">πŸ”</div>
644
+ <div>Select your breed, enter details and click <strong>Calculate</strong></div>
645
+ <div style="font-size: 14px; margin-top: 8px;">Your feed estimate will appear here</div>
646
+ </div>
647
+ """,
648
+ elem_classes=["answer-box"],
649
  )
650
 
651
+ # QUESTION SECTION
652
  gr.Markdown("---")
 
 
 
653
 
654
  with gr.Row():
655
+ with gr.Column(scale=2):
656
+ gr.Markdown("""
657
+ # ❓ Ask a question
658
+ ### What would you like to know about raising your birds?
659
+ """)
660
+
661
+ question = gr.Textbox(
662
+ label="",
663
+ placeholder="Type or speak your question...",
664
+ lines=3,
665
+ )
666
 
667
+ ask_btn = gr.Button("πŸ’¬ Get Answer", variant="secondary", size="lg")
668
+ question_answer = gr.Markdown("")
669
 
670
+ # BREED REFERENCE
671
  gr.Markdown("---")
672
+
673
  gr.Markdown("""
674
+ ### πŸ” Common Broiler Breeds in Nigeria
675
+
676
+ | Breed | Characteristics | Available At |
677
+ |-------|-----------------|--------------|
678
+ | **Ross 308** | Big chest, thick legs, very fast growth | Agrited, Sayed, Valentine |
679
+ | **Cobb 500** | Good early growth, strong legs | Chikun, Zartech |
680
+ | **Arbor Acres** | Balanced growth, hardy, adaptable | Supreme, CHI, GS, Vertex, Fidan, Cascada, Orobor, Sunchi, Farm Support, Ajila |
681
 
682
+ πŸ’‘ **Tip:** Before buying chicks, ask about the breed and hatchery. Not all broilers are the same!
683
+ """)
684
 
685
+ # BENCHMARK REFERENCE
686
  gr.Markdown("---")
 
 
 
 
 
 
687
 
688
+ with gr.Row():
689
+ with gr.Column(scale=1):
690
+ gr.Markdown("""
691
+ ### πŸ“Š Ross 308 Weekly Benchmark
692
+
693
+ | Days | Body Weight (kg) | Cum Feed (kg) |
694
+ |------|------------------|---------------|
695
+ | 7 | 0.213 | 0.166 |
696
+ | 14 | 0.533 | 0.535 |
697
+ | 21 | 1.012 | 1.155 |
698
+ | 28 | 1.616 | 2.051 |
699
+ | 35 | 2.296 | 3.211 |
700
+ | 42 | 2.998 | 4.586 |
701
+ | 49 | 3.681 | 6.115 |
702
+ | 56 | 4.318 | 7.733 |
703
+ """)
704
+
705
+ with gr.Column(scale=1):
706
+ gr.Markdown("""
707
+ ### πŸ“Œ How it works
708
+
709
+ - **Weeks + Days** β†’ total days
710
+ - **Starter** β†’ Day 0–21
711
+ - **Finisher** β†’ Day 22+
712
+ - **Bags** β†’ rounded up to next whole bag
713
+ - **Breed-specific benchmarks** used for estimates
714
+
715
+ ⚠️ Actual results may vary with management, feed quality, and other conditions.
716
+ """)
717
+
718
+ # EVENTS
719
  calculate_btn.click(
720
+ fn=calculate_feed,
721
+ inputs=[birds, weeks, days, bag_size, price, email, country_state, breed],
722
+ outputs=result,
723
  )
724
 
 
725
  ask_btn.click(
726
+ fn=answer_farmer_question,
727
+ inputs=[question, email, breed],
728
+ outputs=question_answer,
729
  )
730
 
731
+
732
+ # ============================================================
733
+ # START APP
734
+ # ============================================================
 
 
735
 
736
  if __name__ == "__main__":
737
  port = int(os.environ.get("PORT", "7860"))
738
+ demo.launch(server_name="0.0.0.0", server_port=port, root_path="/")