NTEIGBANAM OKE commited on
Commit
7053e6f
·
verified ·
1 Parent(s): a33ca16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +916 -157
app.py CHANGED
@@ -1,220 +1,979 @@
1
- with gr.Blocks(title="PoultryFeedCalc") as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- gr.Markdown(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  """
5
- # 🐔 PoultryFeedCalc
 
 
 
 
 
 
6
 
7
- ### Simple broiler feed calculator for farmers
8
 
9
- Choose your birds, age, feed bag size and price.
10
- **No calculations required.**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  """
 
 
 
 
 
 
 
 
 
 
12
  )
13
 
14
- # =====================================================
15
- # EMAIL FIRST
16
- # =====================================================
17
 
18
- gr.Markdown("## 📧 Before you calculate")
19
 
20
- email = gr.Textbox(
21
- label="Your email address",
22
- placeholder="Enter your email address",
23
- info="We use your email for PoultryFeedCalc updates and improvements."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  )
25
 
26
- # =====================================================
27
- # TWO COLUMN MAIN AREA
28
- # =====================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- with gr.Row(equal_height=True):
 
31
 
32
- # -------------------------------------------------
33
- # LEFT COLUMN — INPUTS
34
- # -------------------------------------------------
35
 
36
- with gr.Column(scale=1):
 
 
37
 
38
- gr.Markdown("## 🧮 Farm inputs")
 
 
39
 
40
- birds = gr.Dropdown(
41
- choices=[
42
- 25,
43
- 50,
44
- 75,
45
- 100,
46
- 150,
47
- 200,
48
- 500,
49
- 1000,
50
- ],
51
- value=25,
52
- label="🐔 Number of birds",
53
- allow_custom_value=True,
54
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  weeks = gr.Dropdown(
57
- choices=list(range(0, 13)),
58
- value=5,
59
- label="📅 Age — Weeks",
 
60
  )
61
 
62
  days = gr.Dropdown(
63
  choices=list(range(0, 7)),
64
  value=0,
65
- label="📅 Age — Days",
 
66
  )
67
 
 
 
 
 
68
  bag_size = gr.Dropdown(
69
- choices=[10, 20, 25, 50],
 
 
 
 
 
70
  value=25,
71
- label="🌾 Feed bag size (kg)",
72
  )
73
 
74
  price = gr.Number(
75
  value=24000,
76
- label="💰 Price per bag",
77
- precision=0,
78
  )
79
 
80
- calculate_btn = gr.Button(
81
- "🐔 Calculate Feed Requirements",
82
- variant="primary",
83
- size="lg",
84
- )
85
 
86
- # -------------------------------------------------
87
- # RIGHT COLUMN — RESULTS
88
- # -------------------------------------------------
89
 
90
- with gr.Column(scale=1):
 
 
91
 
92
- gr.Markdown("## 🐔 Your feed requirement")
 
 
 
93
 
94
- result = gr.Markdown(
95
- """
96
- ### Enter your farm details
 
 
 
97
 
98
- Your feed requirement will appear here after you calculate.
99
- """
100
- )
 
 
101
 
102
- # =====================================================
103
- # CALCULATION FUNCTION
104
- # =====================================================
105
-
106
- def run_calculation(email_value, birds_value, weeks_value,
107
- days_value, bag_value, price_value):
108
-
109
- # Email is required BEFORE calculation.
110
- if not email_value or "@" not in str(email_value):
111
- return """
112
- ⚠️ **Please enter a valid email address before calculating.**
113
- """
114
-
115
- try:
116
- birds_value = int(birds_value)
117
- weeks_value = int(weeks_value)
118
- days_value = int(days_value)
119
- bag_value = float(bag_value)
120
- price_value = float(price_value)
121
- except Exception:
122
- return "⚠️ Please check your farm inputs."
123
-
124
- if birds_value <= 0:
125
- return "⚠️ Number of birds must be greater than zero."
126
-
127
- if bag_value <= 0:
128
- return "⚠️ Feed bag size must be greater than zero."
129
-
130
- if price_value < 0:
131
- return "⚠️ Feed price cannot be negative."
132
-
133
- data = calculate_feed(
134
- birds_value,
135
- weeks_value,
136
- days_value,
137
- bag_value,
138
- price_value,
139
- )
140
 
141
- days_total = data["days"]
142
 
143
- # -------------------------------------------------
144
- # AGE DISPLAY
145
- # -------------------------------------------------
146
 
147
- if days_value:
148
- age_text = (
149
- f"{weeks_value} weeks + {days_value} days "
150
- f"({days_total} days)"
151
- )
152
- else:
153
- age_text = (
154
- f"{weeks_value} weeks "
155
- f"({days_total} days)"
156
- )
157
 
158
- # -------------------------------------------------
159
- # QUICK ANSWER
160
- # -------------------------------------------------
161
-
162
- quick_answer = (
163
- f"### 🎯 Quick answer\n\n"
164
- f"To raise **{birds_value:,} birds** for **{age_text}**, "
165
- f"you will require an estimated **"
166
- f"{data['purchase_bags']:,} bags of {bag_value:g} kg feed** "
167
- f"(**{data['starter_whole_bags']} Starter + "
168
- f"{data['finisher_whole_bags']} Finisher**).\n\n"
169
- f"This will cost approximately **"
170
- f"₦{data['estimated_cost']:,.0f} on feed alone**."
171
- )
172
 
173
- # -------------------------------------------------
174
- # DETAILED BREAKDOWN
175
- # -------------------------------------------------
176
 
177
- breakdown = f"""
178
- ### 🌾 Feed breakdown
 
179
 
180
- | Feed | Estimated quantity | Exact bag equivalent | Bags to buy |
181
- |---|---:|---:|---:|
182
- | 🌱 Starter | **{data['starter_kg']:,.1f} kg** | {data['starter_exact_bags']:.2f} | **{data['starter_whole_bags']} bags** |
183
- | 🌽 Finisher | **{data['finisher_kg']:,.1f} kg** | {data['finisher_exact_bags']:.2f} | **{data['finisher_whole_bags']} bags** |
184
- | **TOTAL** | **{data['total_feed_kg']:,.1f} kg** | **{data['exact_total_bags']:.2f}** | **{data['purchase_bags']} bags** |
185
 
186
- ### 💰 Estimated feed cost
 
 
 
 
187
 
188
- **₦{data['estimated_cost']:,.0f}**
 
 
 
189
 
190
- Based on **₦{price_value:,.0f} per {bag_value:g}-kg bag**.
 
 
191
 
192
- ### 📌 How the estimate was calculated
193
 
194
- - Total age: **{days_total} days**
195
- - Estimated cumulative feed: **{data['cumulative_per_bird']:.2f} kg/bird**
196
- - Total estimated feed: **{data['total_feed_kg']:,.1f} kg**
197
- - Exact equivalent: **{data['exact_total_bags']:.2f} bags**
198
- - Starter purchased separately: **{data['starter_whole_bags']} bags**
199
- - Finisher purchased separately: **{data['finisher_whole_bags']} bags**
200
- - **Total bags to purchase: {data['purchase_bags']}**
201
- - **No artificial 20% allowance has been added.**
 
 
 
 
 
 
 
 
 
 
202
 
203
- > Actual farm consumption can vary with genetics, sex, mortality,
204
- > feed quality, temperature, management and other farm conditions.
205
- """
 
 
 
 
 
 
 
 
 
 
206
 
207
- return quick_answer + "\n\n" + breakdown
 
 
208
 
209
  calculate_btn.click(
210
- fn=run_calculation,
211
  inputs=[
212
- email,
213
  birds,
214
  weeks,
215
  days,
216
  bag_size,
217
  price,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  ],
219
- outputs=result,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  )
 
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
+ # Feed benchmark.
19
+ # Values are cumulative feed consumption per bird by day.
20
+ # Based on Ross 308 performance objectives.
21
+ #
22
+ # The calculator uses DAYS internally.
23
+ # Starter feed is estimated up to day 21.
24
+ # NO artificial planning/wastage allowance is added.
25
+ # ============================================================
26
+
27
+ STARTER_END_DAY = 21
28
+
29
+ # Daily cumulative feed per bird (kg)
30
+ # Based on Ross 308 as-hatched performance objectives.
31
+ FEED_PER_BIRD_BY_DAY = {
32
+ 1: 0.019, 2: 0.048, 3: 0.079, 4: 0.112, 5: 0.146,
33
+ 6: 0.179, 7: 0.213, 8: 0.249, 9: 0.288, 10: 0.331,
34
+ 11: 0.376, 12: 0.425, 13: 0.477, 14: 0.533, 15: 0.592,
35
+ 16: 0.655, 17: 0.720, 18: 0.789, 19: 0.860, 20: 0.935,
36
+ 21: 1.012, 22: 1.092, 23: 1.174, 24: 1.258, 25: 1.345,
37
+ 26: 1.434, 27: 1.524, 28: 1.616, 29: 1.710, 30: 1.805,
38
+ 31: 1.901, 32: 1.999, 33: 2.097, 34: 2.196, 35: 2.296,
39
+ 36: 2.396, 37: 2.496, 38: 2.597, 39: 2.697, 40: 2.798,
40
+ 41: 2.898, 42: 2.998, 43: 3.097, 44: 3.197, 45: 3.295,
41
+ 46: 3.393, 47: 3.490, 48: 3.586, 49: 3.681, 50: 3.776,
42
+ 51: 3.869, 52: 3.961, 53: 4.051, 54: 4.141, 55: 4.229,
43
+ 56: 4.316,
44
+ }
45
+
46
+ # Expected body weight per bird (kg) at key days
47
+ WEIGHT_BY_DAY = {
48
+ 0: 0.044, 7: 0.213, 14: 0.533, 21: 1.012, 28: 1.616,
49
+ 35: 2.296, 42: 2.998, 49: 3.681, 56: 4.316,
50
+ }
51
+
52
+
53
+ def interpolate_weight(day):
54
+ """Interpolate body weight between known checkpoints."""
55
+ if day <= 0:
56
+ return WEIGHT_BY_DAY[0]
57
+ if day >= 56:
58
+ return WEIGHT_BY_DAY[56]
59
+
60
+ keys = sorted(WEIGHT_BY_DAY.keys())
61
+ for i in range(len(keys) - 1):
62
+ if keys[i] <= day <= keys[i + 1]:
63
+ ratio = (day - keys[i]) / (keys[i + 1] - keys[i])
64
+ return WEIGHT_BY_DAY[keys[i]] + (WEIGHT_BY_DAY[keys[i + 1]] - WEIGHT_BY_DAY[keys[i]]) * ratio
65
+
66
+ return WEIGHT_BY_DAY[56]
67
+
68
+
69
+ # ============================================================
70
+ # CURRENCY
71
+ # ============================================================
72
+
73
+ CURRENCIES = {
74
+ "NG": ("Nigeria", "₦", "NGN"),
75
+ "GH": ("Ghana", "₵", "GHS"),
76
+ "KE": ("Kenya", "KSh", "KES"),
77
+ "UG": ("Uganda", "USh", "UGX"),
78
+ "TZ": ("Tanzania", "TSh", "TZS"),
79
+ "ZA": ("South Africa", "R", "ZAR"),
80
+ "ZM": ("Zambia", "ZK", "ZMW"),
81
+ "ZW": ("Zimbabwe", "ZiG", "ZWG"),
82
+ "CM": ("Cameroon", "FCFA", "XAF"),
83
+ "CI": ("Côte d'Ivoire", "CFA", "XOF"),
84
+ "SN": ("Senegal", "CFA", "XOF"),
85
+ "US": ("United States", "$", "USD"),
86
+ "GB": ("United Kingdom", "£", "GBP"),
87
+ "CA": ("Canada", "C$", "CAD"),
88
+ "AU": ("Australia", "A$", "AUD"),
89
+ }
90
+
91
+
92
+ def detect_country():
93
+ """Best-effort country detection from environment."""
94
+ candidates = [
95
+ os.environ.get("COUNTRY_CODE"),
96
+ os.environ.get("CF-IPCOUNTRY"),
97
+ os.environ.get("GEOIP_COUNTRY"),
98
+ ]
99
+
100
+ for value in candidates:
101
+ if value:
102
+ value = value.strip().upper()
103
+ if value in CURRENCIES:
104
+ return value
105
+
106
+ return "NG"
107
+
108
+
109
+ def currency_for_country(country_code):
110
+ data = CURRENCIES.get(country_code, CURRENCIES["NG"])
111
+ return data[1]
112
+
113
+
114
+ # ============================================================
115
+ # DATABASE
116
+ # ============================================================
117
+
118
+ def init_db():
119
+ conn = sqlite3.connect(DB_PATH)
120
+
121
+ cur = conn.cursor()
122
+
123
+ cur.execute(
124
+ """
125
+ CREATE TABLE IF NOT EXISTS leads (
126
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
127
+ email TEXT UNIQUE,
128
+ country TEXT,
129
+ currency TEXT,
130
+ created_at TEXT
131
+ )
132
+ """
133
+ )
134
 
135
+ cur.execute(
136
+ """
137
+ CREATE TABLE IF NOT EXISTS farmer_questions (
138
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
139
+ email TEXT,
140
+ question TEXT,
141
+ created_at TEXT
142
+ )
143
+ """
144
+ )
145
+
146
+ cur.execute(
147
+ """
148
+ CREATE TABLE IF NOT EXISTS calculations (
149
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
150
+ email TEXT,
151
+ country TEXT,
152
+ currency TEXT,
153
+ birds INTEGER,
154
+ weeks INTEGER,
155
+ days INTEGER,
156
+ total_days INTEGER,
157
+ bag_size REAL,
158
+ price_per_bag REAL,
159
+ total_feed_kg REAL,
160
+ starter_kg REAL,
161
+ finisher_kg REAL,
162
+ starter_bags REAL,
163
+ finisher_bags REAL,
164
+ total_bags REAL,
165
+ rounded_bags INTEGER,
166
+ total_cost REAL,
167
+ created_at TEXT
168
+ )
169
  """
170
+ )
171
+
172
+ conn.commit()
173
+ conn.close()
174
+
175
+
176
+ init_db()
177
 
 
178
 
179
+ # ============================================================
180
+ # DATABASE HELPERS
181
+ # ============================================================
182
+
183
+ def valid_email(email):
184
+ if not email:
185
+ return False
186
+
187
+ email = email.strip()
188
+
189
+ pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
190
+ return bool(re.match(pattern, email))
191
+
192
+
193
+ def save_lead(email, country, currency):
194
+ if not valid_email(email):
195
+ return
196
+
197
+ conn = sqlite3.connect(DB_PATH)
198
+ cur = conn.cursor()
199
+
200
+ cur.execute(
201
  """
202
+ INSERT OR IGNORE INTO leads
203
+ (email, country, currency, created_at)
204
+ VALUES (?, ?, ?, ?)
205
+ """,
206
+ (
207
+ email.strip().lower(),
208
+ country,
209
+ currency,
210
+ datetime.utcnow().isoformat(),
211
+ ),
212
  )
213
 
214
+ conn.commit()
215
+ conn.close()
 
216
 
 
217
 
218
+ def save_question(email, question):
219
+ if not question or not question.strip():
220
+ return
221
+
222
+ conn = sqlite3.connect(DB_PATH)
223
+ cur = conn.cursor()
224
+
225
+ cur.execute(
226
+ """
227
+ INSERT INTO farmer_questions
228
+ (email, question, created_at)
229
+ VALUES (?, ?, ?)
230
+ """,
231
+ (
232
+ email.strip().lower() if email else "",
233
+ question.strip(),
234
+ datetime.utcnow().isoformat(),
235
+ ),
236
  )
237
 
238
+ conn.commit()
239
+ conn.close()
240
+
241
+
242
+ def save_calculation(
243
+ email,
244
+ country,
245
+ currency,
246
+ birds,
247
+ weeks,
248
+ days,
249
+ total_days,
250
+ bag_size,
251
+ price_per_bag,
252
+ total_feed_kg,
253
+ starter_kg,
254
+ finisher_kg,
255
+ starter_bags,
256
+ finisher_bags,
257
+ total_bags,
258
+ rounded_bags,
259
+ total_cost,
260
+ ):
261
+ conn = sqlite3.connect(DB_PATH)
262
+ cur = conn.cursor()
263
+
264
+ cur.execute(
265
+ """
266
+ INSERT INTO calculations (
267
+ email,
268
+ country,
269
+ currency,
270
+ birds,
271
+ weeks,
272
+ days,
273
+ total_days,
274
+ bag_size,
275
+ price_per_bag,
276
+ total_feed_kg,
277
+ starter_kg,
278
+ finisher_kg,
279
+ starter_bags,
280
+ finisher_bags,
281
+ total_bags,
282
+ rounded_bags,
283
+ total_cost,
284
+ created_at
285
+ )
286
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
287
+ """,
288
+ (
289
+ email.strip().lower() if email else "",
290
+ country,
291
+ currency,
292
+ birds,
293
+ weeks,
294
+ days,
295
+ total_days,
296
+ bag_size,
297
+ price_per_bag,
298
+ total_feed_kg,
299
+ starter_kg,
300
+ finisher_kg,
301
+ starter_bags,
302
+ finisher_bags,
303
+ total_bags,
304
+ rounded_bags,
305
+ total_cost,
306
+ datetime.utcnow().isoformat(),
307
+ ),
308
+ )
309
 
310
+ conn.commit()
311
+ conn.close()
312
 
 
 
 
313
 
314
+ # ============================================================
315
+ # FEED CALCULATION
316
+ # ============================================================
317
 
318
+ def cumulative_feed_per_bird(total_days):
319
+ """
320
+ Returns benchmark cumulative feed consumption per bird.
321
 
322
+ For days beyond the table, the last known daily increment
323
+ is extended.
324
+ """
325
+
326
+ if total_days <= 0:
327
+ return 0.0
328
+
329
+ if total_days in FEED_PER_BIRD_BY_DAY:
330
+ return FEED_PER_BIRD_BY_DAY[total_days]
331
+
332
+ max_day = max(FEED_PER_BIRD_BY_DAY.keys())
333
+
334
+ if total_days > max_day:
335
+ last = FEED_PER_BIRD_BY_DAY[max_day]
336
+ previous = FEED_PER_BIRD_BY_DAY[max_day - 1]
337
+ daily_increment = last - previous
338
+
339
+ return last + ((total_days - max_day) * daily_increment)
340
+
341
+ # fallback
342
+ closest_day = max(
343
+ day for day in FEED_PER_BIRD_BY_DAY
344
+ if day <= total_days
345
+ )
346
+
347
+ return FEED_PER_BIRD_BY_DAY[closest_day]
348
+
349
+
350
+ def feed_at_day(day):
351
+ return cumulative_feed_per_bird(day)
352
+
353
+
354
+ def calculate_feed(
355
+ birds,
356
+ weeks,
357
+ days,
358
+ bag_size,
359
+ price_per_bag,
360
+ email,
361
+ country_code,
362
+ ):
363
+ # --------------------------------------------------------
364
+ # VALIDATION
365
+ # --------------------------------------------------------
366
+
367
+ try:
368
+ birds = int(birds)
369
+ weeks = int(weeks)
370
+ days = int(days)
371
+ bag_size = float(bag_size)
372
+ price_per_bag = float(price_per_bag)
373
+ except Exception:
374
+ return (
375
+ "⚠️ Please enter valid numbers.",
376
+ "",
377
+ )
378
+
379
+ if birds <= 0:
380
+ return "⚠️ Number of birds must be greater than zero.", ""
381
+
382
+ if weeks < 0:
383
+ return "⚠️ Weeks cannot be negative.", ""
384
+
385
+ if days < 0 or days > 6:
386
+ return "⚠️ Days must be between 0 and 6.", ""
387
+
388
+ if bag_size <= 0:
389
+ return "⚠️ Feed bag size must be greater than zero.", ""
390
+
391
+ if price_per_bag < 0:
392
+ return "⚠️ Price per bag cannot be negative.", ""
393
+
394
+ # --------------------------------------------------------
395
+ # EMAIL IS REQUIRED BEFORE CALCULATION
396
+ # --------------------------------------------------------
397
+
398
+ if not valid_email(email):
399
+ return (
400
+ "📧 **Email required**\n\n"
401
+ "Please enter your email address before calculating "
402
+ "your feed requirement.",
403
+ "",
404
+ )
405
+
406
+ # --------------------------------------------------------
407
+ # COUNTRY / CURRENCY
408
+ # --------------------------------------------------------
409
+
410
+ country_code = country_code or "NG"
411
+
412
+ if country_code not in CURRENCIES:
413
+ country_code = "NG"
414
+
415
+ currency = currency_for_country(country_code)
416
+
417
+ save_lead(email, country_code, currency)
418
+
419
+ # --------------------------------------------------------
420
+ # TOTAL DAYS
421
+ # --------------------------------------------------------
422
+
423
+ total_days = (weeks * 7) + days
424
+
425
+ # --------------------------------------------------------
426
+ # TOTAL FEED
427
+ # --------------------------------------------------------
428
+
429
+ total_feed_per_bird = cumulative_feed_per_bird(total_days)
430
+
431
+ total_feed_kg = birds * total_feed_per_bird
432
+
433
+ # --------------------------------------------------------
434
+ # STARTER / FINISHER
435
+ # --------------------------------------------------------
436
+
437
+ starter_days = min(total_days, STARTER_END_DAY)
438
+
439
+ starter_per_bird = feed_at_day(starter_days)
440
+
441
+ starter_kg = birds * starter_per_bird
442
+
443
+ finisher_kg = max(total_feed_kg - starter_kg, 0)
444
+
445
+ # --------------------------------------------------------
446
+ # BAGS
447
+ # --------------------------------------------------------
448
+
449
+ starter_bags = starter_kg / bag_size
450
+ finisher_bags = finisher_kg / bag_size
451
+
452
+ total_bags = total_feed_kg / bag_size
453
+
454
+ # Exact estimate, then practical whole bags to purchase.
455
+ # Example: 5.8 bags -> approximately 6 bags
456
+ rounded_bags = math.ceil(total_bags)
457
+
458
+ total_cost = rounded_bags * price_per_bag
459
+
460
+ # --------------------------------------------------------
461
+ # EXPECTED PERFORMANCE
462
+ # --------------------------------------------------------
463
+
464
+ expected_weight = interpolate_weight(total_days)
465
+ flock_weight = expected_weight * birds
466
+
467
+ # --------------------------------------------------------
468
+ # SAVE CALCULATION
469
+ # --------------------------------------------------------
470
+
471
+ save_calculation(
472
+ email=email,
473
+ country=country_code,
474
+ currency=currency,
475
+ birds=birds,
476
+ weeks=weeks,
477
+ days=days,
478
+ total_days=total_days,
479
+ bag_size=bag_size,
480
+ price_per_bag=price_per_bag,
481
+ total_feed_kg=total_feed_kg,
482
+ starter_kg=starter_kg,
483
+ finisher_kg=finisher_kg,
484
+ starter_bags=starter_bags,
485
+ finisher_bags=finisher_bags,
486
+ total_bags=total_bags,
487
+ rounded_bags=rounded_bags,
488
+ total_cost=total_cost,
489
+ )
490
+
491
+ # --------------------------------------------------------
492
+ # OUTPUT
493
+ # --------------------------------------------------------
494
+
495
+ starter_bags_display = f"{starter_bags:.1f}"
496
+ finisher_bags_display = f"{finisher_bags:.1f}"
497
+
498
+ age_text = f"{weeks} week{'s' if weeks != 1 else ''}"
499
+ if days:
500
+ age_text += f" + {days} day{'s' if days != 1 else ''}"
501
+
502
+ answer = f"""
503
+ ## 🎯 Quick Answer
504
+
505
+ ### To raise **{birds:,} birds** for **{age_text} ({total_days} days)**
506
+
507
+ You will need an estimated:
508
+
509
+ # **{total_bags:.1f} bags of feed**
510
+
511
+ That's approximately:
512
+
513
+ # **{rounded_bags} bags**
514
+
515
+ ---
516
+
517
+ ### 🌾 Feed breakdown
518
+
519
+ | Feed | Quantity | Bags |
520
+ |---|---:|---:|
521
+ | 🌱 Starter (Day 0–{STARTER_END_DAY}) | **{starter_kg:,.1f} kg** | **{starter_bags_display}** |
522
+ | 🌽 Finisher (Day {STARTER_END_DAY+1}–{total_days}) | **{finisher_kg:,.1f} kg** | **{finisher_bags_display}** |
523
+ | **TOTAL** | **{total_feed_kg:,.1f} kg** | **{total_bags:.1f}** |
524
+
525
+ ---
526
+
527
+ ### 💰 Feed cost
528
+
529
+ At **{currency}{price_per_bag:,.0f} per bag**:
530
+
531
+ # **Approximately {currency}{total_cost:,.0f}**
532
+
533
+ This is the estimated cost of **feed alone**.
534
+
535
+ ---
536
+
537
+ ### 📊 Expected Performance
538
+
539
+ | Metric | Value |
540
+ |---|---:|
541
+ | Expected body weight per bird | **{expected_weight:.3f} kg** |
542
+ | Expected flock live weight | **{flock_weight:,.1f} kg** |
543
+ | Cumulative feed per bird | **{total_feed_per_bird:.3f} kg** |
544
+
545
+ ---
546
+
547
+ ### 📝 Calculation
548
+
549
+ **{birds:,} birds × {total_feed_per_bird:.3f} kg per bird = {total_feed_kg:,.1f} kg feed**
550
+
551
+ **{total_feed_kg:,.1f} kg ÷ {bag_size:g} kg = {total_bags:.2f} bags**
552
+
553
+ The calculator then rounds up to the next whole bag for purchasing:
554
+
555
+ **{total_bags:.2f} → {rounded_bags} bags**
556
+ """
557
+
558
+ return answer, f"✅ Calculation saved for {email.strip().lower()}."
559
+
560
+
561
+ # ============================================================
562
+ # QUESTION / ANSWER
563
+ # ============================================================
564
+
565
+ def answer_farmer_question(question, email):
566
+ if not question or not question.strip():
567
+ return "Please type or speak your question first."
568
+
569
+ # Automatically save whenever Get Answer is clicked.
570
+ save_question(email or "", question)
571
+
572
+ q = question.lower().strip()
573
+
574
+ # --------------------------------------------------------
575
+ # BASIC QUESTION MATCHING
576
+ # --------------------------------------------------------
577
+
578
+ if "bag" in q and ("feed" in q or "birds" in q):
579
+ answer = """
580
+ ### 🐔 Feed-bag questions
581
+
582
+ For an exact feed estimate, use the calculator above.
583
+
584
+ Enter:
585
+
586
+ 1. Number of birds
587
+ 2. Age in weeks + days
588
+ 3. Feed bag size
589
+ 4. Price per bag
590
+ 5. Your email
591
+
592
+ The calculator will give you the estimated total bags, starter/finisher breakdown and feed cost.
593
+ """
594
+
595
+ elif "starter" in q:
596
+ answer = f"""
597
+ ### 🌾 Starter feed
598
+
599
+ Starter feed is used during the early growth period (Day 0–{STARTER_END_DAY}).
600
+
601
+ The calculator separates the estimated feed requirement into **Starter** and **Finisher** based on the selected age.
602
+ """
603
+
604
+ elif "finisher" in q:
605
+ answer = f"""
606
+ ### 🌾 Finisher feed
607
+
608
+ Finisher feed is used after day {STARTER_END_DAY}.
609
+
610
+ Your calculator automatically estimates the finisher requirement from the selected number of birds and total age.
611
+ """
612
+
613
+ elif "cost" in q or "price" in q:
614
+ answer = """
615
+ ### 💰 Feed cost
616
+
617
+ Enter the current price of one feed bag in the calculator.
618
+
619
+ The app calculates:
620
+
621
+ **Number of bags × price per bag = estimated feed cost**
622
+
623
+ The result is for **feed alone**.
624
+ """
625
+
626
+ elif "weight" in q or "size" in q:
627
+ answer = """
628
+ ### 📊 Expected weight
629
+
630
+ The calculator shows:
631
+ - Expected body weight per bird
632
+ - Expected flock live weight
633
+
634
+ These are based on Ross 308 performance benchmarks.
635
+ """
636
+
637
+ elif "profit" in q:
638
+ answer = """
639
+ ### 📈 Profit questions
640
+
641
+ Profit depends on several things, including:
642
+
643
+ - Number of birds sold
644
+ - Selling price
645
+ - Feed cost
646
+ - Chick cost
647
+ - Medication
648
+ - Vaccination
649
+ - Labour
650
+ - Mortality
651
+ - Other farm expenses
652
+
653
+ A future version can use your saved farmer questions to determine which profit features should be added.
654
+ """
655
+
656
+ else:
657
+ answer = f"""
658
+ ### 💡 Question received
659
+
660
+ **“{question.strip()}”**
661
+
662
+ Your question has been saved.
663
+
664
+ We can use the questions farmers submit to decide which answers, calculators and features should be added to the app next.
665
+ """
666
+
667
+ return answer
668
+
669
+
670
+ # ============================================================
671
+ # COUNTRY / CURRENCY UI
672
+ # ============================================================
673
+
674
+ def get_country_info():
675
+ country = detect_country()
676
+ currency = currency_for_country(country)
677
+
678
+ return country, currency
679
+
680
+
681
+ DEFAULT_COUNTRY, DEFAULT_CURRENCY = get_country_info()
682
+
683
+
684
+ # ============================================================
685
+ # CSS
686
+ # ============================================================
687
+
688
+ CSS = """
689
+ body {
690
+ background: #f6f8f4;
691
+ }
692
+
693
+ .gradio-container {
694
+ max-width: 1050px !important;
695
+ }
696
+
697
+ .main-title {
698
+ text-align: center;
699
+ padding: 15px 10px 5px 10px;
700
+ }
701
+
702
+ .main-title h1 {
703
+ font-size: 34px;
704
+ margin-bottom: 4px;
705
+ }
706
+
707
+ .main-title p {
708
+ font-size: 17px;
709
+ color: #555;
710
+ }
711
+
712
+ .answer-box {
713
+ border-radius: 16px;
714
+ padding: 8px;
715
+ }
716
+
717
+ .email-box {
718
+ border: 2px solid #d9e7d2;
719
+ border-radius: 12px;
720
+ padding: 10px;
721
+ background: #fbfdf9;
722
+ }
723
+
724
+ .big-answer {
725
+ font-size: 19px;
726
+ }
727
+
728
+ .big-answer h1 {
729
+ font-size: 30px !important;
730
+ }
731
+
732
+ .big-answer h2 {
733
+ font-size: 25px !important;
734
+ }
735
+
736
+ .big-answer h3 {
737
+ font-size: 20px !important;
738
+ }
739
+
740
+ button {
741
+ min-height: 48px !important;
742
+ }
743
+ """
744
+
745
+
746
+ # ============================================================
747
+ # UI
748
+ # ============================================================
749
+
750
+ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
751
+
752
+ gr.HTML(
753
+ """
754
+ <div class="main-title">
755
+ <h1>🐔 Poultry Feed Calculator</h1>
756
+ <p>
757
+ Know exactly how much feed you need before buying.
758
+ </p>
759
+ </div>
760
+ """
761
+ )
762
+
763
+ # --------------------------------------------------------
764
+ # FARM INPUTS
765
+ # --------------------------------------------------------
766
+
767
+ with gr.Group():
768
+
769
+ gr.Markdown("## 🐔 1. Number of birds")
770
+
771
+ birds = gr.Dropdown(
772
+ choices=[
773
+ 25,
774
+ 50,
775
+ 75,
776
+ 100,
777
+ 150,
778
+ 200,
779
+ 500,
780
+ 1000,
781
+ ],
782
+ value=50,
783
+ label="Number of birds",
784
+ allow_custom_value=True,
785
+ )
786
+
787
+ gr.Markdown("## 📅 2. Age")
788
+
789
+ with gr.Row():
790
 
791
  weeks = gr.Dropdown(
792
+ choices=list(range(0, 21)),
793
+ value=6,
794
+ label="Weeks",
795
+ info="Select the number of complete weeks.",
796
  )
797
 
798
  days = gr.Dropdown(
799
  choices=list(range(0, 7)),
800
  value=0,
801
+ label="Days",
802
+ info="Additional days after the complete weeks.",
803
  )
804
 
805
+ gr.Markdown("## 🌾 3. Feed")
806
+
807
+ with gr.Row():
808
+
809
  bag_size = gr.Dropdown(
810
+ choices=[
811
+ 10,
812
+ 20,
813
+ 25,
814
+ 50,
815
+ ],
816
  value=25,
817
+ label="Feed bag size (kg)",
818
  )
819
 
820
  price = gr.Number(
821
  value=24000,
822
+ label=f"Price per bag ({DEFAULT_CURRENCY})",
823
+ minimum=0,
824
  )
825
 
826
+ # --------------------------------------------------------
827
+ # EMAIL BEFORE CALCULATE
828
+ # --------------------------------------------------------
 
 
829
 
830
+ gr.Markdown("## 📧 4. Your email")
 
 
831
 
832
+ gr.Markdown(
833
+ """
834
+ Enter your email before calculating.
835
 
836
+ Your email lets us save your calculation and helps us
837
+ understand what farmers need from the app.
838
+ """
839
+ )
840
 
841
+ email = gr.Textbox(
842
+ label="Email address",
843
+ placeholder="farmer@example.com",
844
+ type="email",
845
+ elem_classes=["email-box"],
846
+ )
847
 
848
+ calculate_btn = gr.Button(
849
+ "🐔 Calculate Feed Requirements",
850
+ variant="primary",
851
+ size="lg",
852
+ )
853
 
854
+ result = gr.Markdown(
855
+ value="",
856
+ elem_classes=["answer-box", "big-answer"],
857
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
 
859
+ save_status = gr.Markdown("")
860
 
861
+ # Hidden country state
862
+ country_state = gr.State(DEFAULT_COUNTRY)
 
863
 
864
+ # --------------------------------------------------------
865
+ # QUESTION BOX
866
+ # --------------------------------------------------------
 
 
 
 
 
 
 
867
 
868
+ gr.Markdown("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
869
 
870
+ gr.Markdown(
871
+ """
872
+ # ❓ Ask a question
873
 
874
+ ### What would you like to know about raising your birds?
875
+ """
876
+ )
877
 
878
+ question = gr.Textbox(
879
+ label="",
880
+ placeholder="Type or speak your question...",
881
+ lines=4,
882
+ )
883
 
884
+ ask_btn = gr.Button(
885
+ "💬 Get Answer",
886
+ variant="secondary",
887
+ size="lg",
888
+ )
889
 
890
+ question_answer = gr.Markdown(
891
+ "",
892
+ elem_classes=["answer-box"],
893
+ )
894
 
895
+ # --------------------------------------------------------
896
+ # BENCHMARK REFERENCE
897
+ # --------------------------------------------------------
898
 
899
+ gr.Markdown("---")
900
 
901
+ gr.Markdown(
902
+ """
903
+ ### 📊 Ross 308 Weekly Benchmark (As-Hatched)
904
+
905
+ | Days | Body Weight (kg) | Cumulative Feed (kg) |
906
+ |------|------------------|----------------------|
907
+ | 7 | 0.213 | 0.213 |
908
+ | 14 | 0.533 | 0.533 |
909
+ | 21 | 1.012 | 1.012 |
910
+ | 28 | 1.616 | 1.616 |
911
+ | 35 | 2.296 | 2.296 |
912
+ | 42 | 2.998 | 2.998 |
913
+ | 49 | 3.681 | 3.681 |
914
+ | 56 | 4.316 | 4.316 |
915
+
916
+ *Source: Aviagen Ross 308 Performance Objectives (2022)*
917
+ """
918
+ )
919
 
920
+ gr.Markdown(
921
+ """
922
+ ### 📌 How the estimate works
923
+
924
+ - Age is calculated in **total days** from Weeks + Days.
925
+ - Starter is counted through **day 21**; Finisher is after day 21.
926
+ - Total bags are calculated from **feed ÷ bag size** and **rounded up**.
927
+ - Ross 308 performance objectives are used as the benchmark.
928
+
929
+ ⚠️ Actual farm consumption can vary with genetics, sex, mortality,
930
+ feed quality, temperature, management and other conditions.
931
+ """
932
+ )
933
 
934
+ # --------------------------------------------------------
935
+ # EVENTS
936
+ # --------------------------------------------------------
937
 
938
  calculate_btn.click(
939
+ fn=calculate_feed,
940
  inputs=[
 
941
  birds,
942
  weeks,
943
  days,
944
  bag_size,
945
  price,
946
+ email,
947
+ country_state,
948
+ ],
949
+ outputs=[
950
+ result,
951
+ save_status,
952
+ ],
953
+ )
954
+
955
+ ask_btn.click(
956
+ fn=answer_farmer_question,
957
+ inputs=[
958
+ question,
959
+ email,
960
  ],
961
+ outputs=[
962
+ question_answer,
963
+ ],
964
+ )
965
+
966
+
967
+ # ============================================================
968
+ # START APP
969
+ # ============================================================
970
+
971
+ if __name__ == "__main__":
972
+
973
+ port = int(os.environ.get("PORT", "7860"))
974
+
975
+ demo.launch(
976
+ server_name="0.0.0.0",
977
+ server_port=port,
978
+ root_path="/",
979
  )