NTEIGBANAM OKE commited on
Commit
c01cb1f
Β·
verified Β·
1 Parent(s): 6187edd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +950 -36
app.py CHANGED
@@ -1,48 +1,962 @@
 
 
 
 
 
1
  from pathlib import Path
2
- p = Path("/mnt/data/app.py")
3
- text = p.read_text()
4
 
5
- # Remove the 20% planning allowance entirely.
6
- text = text.replace('PLANNING_BUFFER = 0.20 # practical 20% allowance for farm variation/wastage\n', 'PLANNING_BUFFER = 0.0 # no artificial allowance; estimate is the benchmark requirement\n')
7
 
8
- # Replace calculations that add the buffer.
9
- text = text.replace('total_feed = benchmark_feed * (1 + PLANNING_BUFFER)', 'total_feed = benchmark_feed')
10
- text = text.replace('starter_kg = starter_per_bird * birds * (1 + PLANNING_BUFFER)', 'starter_kg = starter_per_bird * birds')
11
- text = text.replace('finisher_kg = finisher_per_bird * birds * (1 + PLANNING_BUFFER)', 'finisher_kg = finisher_per_bird * birds')
12
- text = text.replace('total_feed = birds * cumulative * (1 + PLANNING_BUFFER)', 'total_feed = birds * cumulative')
13
- text = text.replace('starter_kg = birds * feed_per_bird(min(total_days, STARTER_END_DAY)) * (1 + PLANNING_BUFFER)', 'starter_kg = birds * feed_per_bird(min(total_days, STARTER_END_DAY))')
14
 
15
- # Remove outdated UI explanation.
16
- text = text.replace(' "- A **20% planning allowance** is added to the benchmark feed estimate before bags are calculated.\\n"\n', '')
17
- text = text.replace(' <li>Planning allowance: <b>{PLANNING_BUFFER*100:.0f}%</b> for farm variation/wastage</li>\n', '')
18
 
19
- # Gradio 6: css belongs on launch, not Blocks.
20
- text = text.replace('with gr.Blocks(css=CSS, title=APP_NAME) as demo:', 'with gr.Blocks(title=APP_NAME) as demo:')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # Replace uvicorn launch section with Gradio 6-compatible launch.
23
- old = '''if __name__ == "__main__":
24
- import uvicorn
25
- port = int(os.environ.get("PORT", "7860"))
26
- uvicorn.run(fastapi_app, host="0.0.0.0", port=port)
27
- '''
28
- new = '''if __name__ == "__main__":
29
  port = int(os.environ.get("PORT", "7860"))
 
30
  demo.launch(
31
  server_name="0.0.0.0",
32
  server_port=port,
33
  css=CSS,
34
  root_path="/",
35
- )
36
- '''
37
- if old not in text:
38
- raise RuntimeError("Expected launch block was not found.")
39
- text = text.replace(old, new)
40
-
41
- # The FastAPI OAuth routes require the mounted FastAPI app. Keep mounting, but
42
- # avoid launching a second ASGI server. Gradio launch is the intended single server.
43
- p.write_text(text)
44
-
45
- # Syntax check
46
- compile(text, str(p), "exec")
47
- print(f"Updated {p}")
48
- print("Syntax check: OK")
 
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
+ # Adjust these benchmark values to your preferred poultry standard.
21
+ #
22
+ # The calculator uses DAYS internally.
23
+ # There is NO artificial 20% planning/wastage allowance.
24
+ # ============================================================
25
+
26
+ STARTER_END_DAY = 28
27
+
28
+ # Daily cumulative feed per bird (kg)
29
+ # Approximate benchmark for broilers.
30
+ FEED_PER_BIRD_BY_DAY = {
31
+ 1: 0.015,
32
+ 2: 0.030,
33
+ 3: 0.045,
34
+ 4: 0.060,
35
+ 5: 0.075,
36
+ 6: 0.090,
37
+ 7: 0.105,
38
+ 8: 0.120,
39
+ 9: 0.135,
40
+ 10: 0.150,
41
+ 11: 0.165,
42
+ 12: 0.180,
43
+ 13: 0.195,
44
+ 14: 0.210,
45
+ 15: 0.225,
46
+ 16: 0.240,
47
+ 17: 0.255,
48
+ 18: 0.270,
49
+ 19: 0.285,
50
+ 20: 0.300,
51
+ 21: 0.315,
52
+ 22: 0.330,
53
+ 23: 0.345,
54
+ 24: 0.360,
55
+ 25: 0.375,
56
+ 26: 0.390,
57
+ 27: 0.405,
58
+ 28: 0.420,
59
+ 29: 0.440,
60
+ 30: 0.460,
61
+ 31: 0.480,
62
+ 32: 0.500,
63
+ 33: 0.520,
64
+ 34: 0.540,
65
+ 35: 0.560,
66
+ 36: 0.580,
67
+ 37: 0.600,
68
+ 38: 0.620,
69
+ 39: 0.640,
70
+ 40: 0.660,
71
+ 41: 0.680,
72
+ 42: 0.700,
73
+ 43: 0.720,
74
+ 44: 0.740,
75
+ 45: 0.760,
76
+ 46: 0.780,
77
+ 47: 0.800,
78
+ 48: 0.820,
79
+ 49: 0.840,
80
+ 50: 0.860,
81
+ 51: 0.880,
82
+ 52: 0.900,
83
+ 53: 0.920,
84
+ 54: 0.940,
85
+ 55: 0.960,
86
+ 56: 0.980,
87
+ 57: 1.000,
88
+ 58: 1.020,
89
+ 59: 1.040,
90
+ 60: 1.060,
91
+ 61: 1.080,
92
+ 62: 1.100,
93
+ 63: 1.120,
94
+ 64: 1.140,
95
+ 65: 1.160,
96
+ 66: 1.180,
97
+ 67: 1.200,
98
+ 68: 1.220,
99
+ 69: 1.240,
100
+ 70: 1.260,
101
+ 71: 1.280,
102
+ 72: 1.300,
103
+ 73: 1.320,
104
+ 74: 1.340,
105
+ 75: 1.360,
106
+ 76: 1.380,
107
+ 77: 1.400,
108
+ 78: 1.420,
109
+ 79: 1.440,
110
+ 80: 1.460,
111
+ 81: 1.480,
112
+ 82: 1.500,
113
+ 83: 1.520,
114
+ 84: 1.540,
115
+ }
116
+
117
+
118
+ # ============================================================
119
+ # CURRENCY
120
+ # ============================================================
121
+
122
+ CURRENCIES = {
123
+ "NG": ("Nigeria", "₦", "NGN"),
124
+ "GH": ("Ghana", "β‚΅", "GHS"),
125
+ "KE": ("Kenya", "KSh", "KES"),
126
+ "UG": ("Uganda", "USh", "UGX"),
127
+ "TZ": ("Tanzania", "TSh", "TZS"),
128
+ "ZA": ("South Africa", "R", "ZAR"),
129
+ "ZM": ("Zambia", "ZK", "ZMW"),
130
+ "ZW": ("Zimbabwe", "ZiG", "ZWG"),
131
+ "CM": ("Cameroon", "FCFA", "XAF"),
132
+ "CI": ("CΓ΄te d'Ivoire", "CFA", "XOF"),
133
+ "SN": ("Senegal", "CFA", "XOF"),
134
+ "US": ("United States", "$", "USD"),
135
+ "GB": ("United Kingdom", "Β£", "GBP"),
136
+ "CA": ("Canada", "C$", "CAD"),
137
+ "AU": ("Australia", "A$", "AUD"),
138
+ }
139
+
140
+
141
+ def detect_country():
142
+ """
143
+ Best-effort country detection from environment.
144
+
145
+ Hosting platforms may expose different variables.
146
+ Nigeria is the default because this calculator is primarily
147
+ designed for Nigerian farmers.
148
+ """
149
+
150
+ candidates = [
151
+ os.environ.get("COUNTRY_CODE"),
152
+ os.environ.get("CF-IPCOUNTRY"),
153
+ os.environ.get("GEOIP_COUNTRY"),
154
+ ]
155
+
156
+ for value in candidates:
157
+ if value:
158
+ value = value.strip().upper()
159
+ if value in CURRENCIES:
160
+ return value
161
+
162
+ return "NG"
163
+
164
+
165
+ def currency_for_country(country_code):
166
+ data = CURRENCIES.get(country_code, CURRENCIES["NG"])
167
+ return data[1]
168
+
169
+
170
+ # ============================================================
171
+ # DATABASE
172
+ # ============================================================
173
+
174
+ def init_db():
175
+ conn = sqlite3.connect(DB_PATH)
176
+
177
+ cur = conn.cursor()
178
+
179
+ cur.execute(
180
+ """
181
+ CREATE TABLE IF NOT EXISTS leads (
182
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
183
+ email TEXT UNIQUE,
184
+ country TEXT,
185
+ currency TEXT,
186
+ created_at TEXT
187
+ )
188
+ """
189
+ )
190
+
191
+ cur.execute(
192
+ """
193
+ CREATE TABLE IF NOT EXISTS farmer_questions (
194
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
195
+ email TEXT,
196
+ question TEXT,
197
+ created_at TEXT
198
+ )
199
+ """
200
+ )
201
+
202
+ cur.execute(
203
+ """
204
+ CREATE TABLE IF NOT EXISTS calculations (
205
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
206
+ email TEXT,
207
+ country TEXT,
208
+ currency TEXT,
209
+ birds INTEGER,
210
+ weeks INTEGER,
211
+ days INTEGER,
212
+ total_days INTEGER,
213
+ bag_size REAL,
214
+ price_per_bag REAL,
215
+ total_feed_kg REAL,
216
+ starter_kg REAL,
217
+ finisher_kg REAL,
218
+ starter_bags REAL,
219
+ finisher_bags REAL,
220
+ total_bags REAL,
221
+ rounded_bags INTEGER,
222
+ total_cost REAL,
223
+ created_at TEXT
224
+ )
225
+ """
226
+ )
227
+
228
+ conn.commit()
229
+ conn.close()
230
+
231
+
232
+ init_db()
233
+
234
+
235
+ # ============================================================
236
+ # DATABASE HELPERS
237
+ # ============================================================
238
+
239
+ def valid_email(email):
240
+ if not email:
241
+ return False
242
+
243
+ email = email.strip()
244
+
245
+ pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
246
+ return bool(re.match(pattern, email))
247
+
248
+
249
+ def save_lead(email, country, currency):
250
+ if not valid_email(email):
251
+ return
252
+
253
+ conn = sqlite3.connect(DB_PATH)
254
+ cur = conn.cursor()
255
+
256
+ cur.execute(
257
+ """
258
+ INSERT OR IGNORE INTO leads
259
+ (email, country, currency, created_at)
260
+ VALUES (?, ?, ?, ?)
261
+ """,
262
+ (
263
+ email.strip().lower(),
264
+ country,
265
+ currency,
266
+ datetime.utcnow().isoformat(),
267
+ ),
268
+ )
269
+
270
+ conn.commit()
271
+ conn.close()
272
+
273
+
274
+ def save_question(email, question):
275
+ if not question or not question.strip():
276
+ return
277
+
278
+ conn = sqlite3.connect(DB_PATH)
279
+ cur = conn.cursor()
280
+
281
+ cur.execute(
282
+ """
283
+ INSERT INTO farmer_questions
284
+ (email, question, created_at)
285
+ VALUES (?, ?, ?)
286
+ """,
287
+ (
288
+ email.strip().lower() if email else "",
289
+ question.strip(),
290
+ datetime.utcnow().isoformat(),
291
+ ),
292
+ )
293
+
294
+ conn.commit()
295
+ conn.close()
296
+
297
+
298
+ def save_calculation(
299
+ email,
300
+ country,
301
+ currency,
302
+ birds,
303
+ weeks,
304
+ days,
305
+ total_days,
306
+ bag_size,
307
+ price_per_bag,
308
+ total_feed_kg,
309
+ starter_kg,
310
+ finisher_kg,
311
+ starter_bags,
312
+ finisher_bags,
313
+ total_bags,
314
+ rounded_bags,
315
+ total_cost,
316
+ ):
317
+ conn = sqlite3.connect(DB_PATH)
318
+ cur = conn.cursor()
319
+
320
+ cur.execute(
321
+ """
322
+ INSERT INTO calculations (
323
+ email,
324
+ country,
325
+ currency,
326
+ birds,
327
+ weeks,
328
+ days,
329
+ total_days,
330
+ bag_size,
331
+ price_per_bag,
332
+ total_feed_kg,
333
+ starter_kg,
334
+ finisher_kg,
335
+ starter_bags,
336
+ finisher_bags,
337
+ total_bags,
338
+ rounded_bags,
339
+ total_cost,
340
+ created_at
341
+ )
342
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
343
+ """,
344
+ (
345
+ email.strip().lower() if email else "",
346
+ country,
347
+ currency,
348
+ birds,
349
+ weeks,
350
+ days,
351
+ total_days,
352
+ bag_size,
353
+ price_per_bag,
354
+ total_feed_kg,
355
+ starter_kg,
356
+ finisher_kg,
357
+ starter_bags,
358
+ finisher_bags,
359
+ total_bags,
360
+ rounded_bags,
361
+ total_cost,
362
+ datetime.utcnow().isoformat(),
363
+ ),
364
+ )
365
+
366
+ conn.commit()
367
+ conn.close()
368
+
369
+
370
+ # ============================================================
371
+ # FEED CALCULATION
372
+ # ============================================================
373
+
374
+ def cumulative_feed_per_bird(total_days):
375
+ """
376
+ Returns benchmark cumulative feed consumption per bird.
377
+
378
+ For days beyond the table, the last known daily increment
379
+ is extended.
380
+ """
381
+
382
+ if total_days <= 0:
383
+ return 0.0
384
+
385
+ if total_days in FEED_PER_BIRD_BY_DAY:
386
+ return FEED_PER_BIRD_BY_DAY[total_days]
387
+
388
+ max_day = max(FEED_PER_BIRD_BY_DAY.keys())
389
+
390
+ if total_days > max_day:
391
+ last = FEED_PER_BIRD_BY_DAY[max_day]
392
+ previous = FEED_PER_BIRD_BY_DAY[max_day - 1]
393
+ daily_increment = last - previous
394
+
395
+ return last + ((total_days - max_day) * daily_increment)
396
+
397
+ # fallback
398
+ closest_day = max(
399
+ day for day in FEED_PER_BIRD_BY_DAY
400
+ if day <= total_days
401
+ )
402
+
403
+ return FEED_PER_BIRD_BY_DAY[closest_day]
404
+
405
+
406
+ def feed_at_day(day):
407
+ return cumulative_feed_per_bird(day)
408
+
409
+
410
+ def calculate_feed(
411
+ birds,
412
+ weeks,
413
+ days,
414
+ bag_size,
415
+ price_per_bag,
416
+ email,
417
+ country_code,
418
+ ):
419
+ # --------------------------------------------------------
420
+ # VALIDATION
421
+ # --------------------------------------------------------
422
+
423
+ try:
424
+ birds = int(birds)
425
+ weeks = int(weeks)
426
+ days = int(days)
427
+ bag_size = float(bag_size)
428
+ price_per_bag = float(price_per_bag)
429
+ except Exception:
430
+ return (
431
+ "⚠️ Please enter valid numbers.",
432
+ "",
433
+ )
434
+
435
+ if birds <= 0:
436
+ return "⚠️ Number of birds must be greater than zero.", ""
437
+
438
+ if weeks < 0:
439
+ return "⚠️ Weeks cannot be negative.", ""
440
+
441
+ if days < 0 or days > 6:
442
+ return "⚠️ Days must be between 0 and 6.", ""
443
+
444
+ if bag_size <= 0:
445
+ return "⚠️ Feed bag size must be greater than zero.", ""
446
+
447
+ if price_per_bag < 0:
448
+ return "⚠️ Price per bag cannot be negative.", ""
449
+
450
+ # --------------------------------------------------------
451
+ # EMAIL IS REQUIRED BEFORE CALCULATION
452
+ # --------------------------------------------------------
453
+
454
+ if not valid_email(email):
455
+ return (
456
+ "πŸ“§ **Email required**\n\n"
457
+ "Please enter your email address before calculating "
458
+ "your feed requirement.",
459
+ "",
460
+ )
461
+
462
+ # --------------------------------------------------------
463
+ # COUNTRY / CURRENCY
464
+ # --------------------------------------------------------
465
+
466
+ country_code = country_code or "NG"
467
+
468
+ if country_code not in CURRENCIES:
469
+ country_code = "NG"
470
+
471
+ currency = currency_for_country(country_code)
472
+
473
+ save_lead(email, country_code, currency)
474
+
475
+ # --------------------------------------------------------
476
+ # TOTAL DAYS
477
+ # --------------------------------------------------------
478
+
479
+ total_days = (weeks * 7) + days
480
+
481
+ # --------------------------------------------------------
482
+ # TOTAL FEED
483
+ # --------------------------------------------------------
484
+
485
+ total_feed_per_bird = cumulative_feed_per_bird(total_days)
486
+
487
+ total_feed_kg = birds * total_feed_per_bird
488
+
489
+ # --------------------------------------------------------
490
+ # STARTER / FINISHER
491
+ # --------------------------------------------------------
492
+
493
+ starter_days = min(total_days, STARTER_END_DAY)
494
+
495
+ starter_per_bird = feed_at_day(starter_days)
496
+
497
+ starter_kg = birds * starter_per_bird
498
+
499
+ finisher_kg = max(total_feed_kg - starter_kg, 0)
500
+
501
+ # --------------------------------------------------------
502
+ # BAGS
503
+ # --------------------------------------------------------
504
+
505
+ starter_bags = starter_kg / bag_size
506
+ finisher_bags = finisher_kg / bag_size
507
+
508
+ total_bags = total_feed_kg / bag_size
509
+
510
+ # Exact estimate, then practical whole bags to purchase.
511
+ #
512
+ # Example:
513
+ # 5.8 bags -> approximately 6 bags
514
+ rounded_bags = math.ceil(total_bags)
515
+
516
+ total_cost = rounded_bags * price_per_bag
517
+
518
+ # --------------------------------------------------------
519
+ # SAVE CALCULATION
520
+ # --------------------------------------------------------
521
+
522
+ save_calculation(
523
+ email=email,
524
+ country=country_code,
525
+ currency=currency,
526
+ birds=birds,
527
+ weeks=weeks,
528
+ days=days,
529
+ total_days=total_days,
530
+ bag_size=bag_size,
531
+ price_per_bag=price_per_bag,
532
+ total_feed_kg=total_feed_kg,
533
+ starter_kg=starter_kg,
534
+ finisher_kg=finisher_kg,
535
+ starter_bags=starter_bags,
536
+ finisher_bags=finisher_bags,
537
+ total_bags=total_bags,
538
+ rounded_bags=rounded_bags,
539
+ total_cost=total_cost,
540
+ )
541
+
542
+ # --------------------------------------------------------
543
+ # OUTPUT
544
+ # --------------------------------------------------------
545
+
546
+ starter_bags_display = f"{starter_bags:.1f}"
547
+ finisher_bags_display = f"{finisher_bags:.1f}"
548
+
549
+ answer = f"""
550
+ # 🎯 Quick Answer
551
+
552
+ ### To raise **{birds:,} birds** for **{total_days} days ({weeks} week{'s' if weeks != 1 else ''}{f' + {days} day' if days else ''})**
553
+
554
+ You will need an estimated:
555
+
556
+ # **{total_bags:.1f} bags of feed**
557
+
558
+ That's approximately:
559
+
560
+ # **{rounded_bags} bags**
561
+
562
+ ### 🌾 Feed breakdown
563
+
564
+ - **Starter:** {starter_bags_display} bags
565
+ - **Finisher:** {finisher_bags_display} bags
566
+ - **Total feed:** **{total_feed_kg:,.1f} kg**
567
+ - **Bag size:** **{bag_size:g} kg**
568
+
569
+ ### πŸ’° Feed cost
570
+
571
+ At **{currency}{price_per_bag:,.0f} per bag**:
572
+
573
+ # **Approximately {currency}{total_cost:,.0f}**
574
+
575
+ This is the estimated cost of **feed alone**.
576
+
577
+ ---
578
+
579
+ ### πŸ“Š Calculation
580
+
581
+ **{birds:,} birds Γ— {total_feed_per_bird:.3f} kg per bird = {total_feed_kg:,.1f} kg feed**
582
+
583
+ **{total_feed_kg:,.1f} kg Γ· {bag_size:g} kg = {total_bags:.2f} bags**
584
+
585
+ The calculator then rounds up to the next whole bag for purchasing:
586
+
587
+ **{total_bags:.2f} β†’ {rounded_bags} bags**
588
+ """
589
+
590
+ return answer, f"Calculation saved for {email.strip().lower()}."
591
+
592
+
593
+ # ============================================================
594
+ # QUESTION / ANSWER
595
+ # ============================================================
596
+
597
+ def answer_farmer_question(question, email):
598
+ if not question or not question.strip():
599
+ return "Please type or speak your question first."
600
+
601
+ # Automatically save whenever Get Answer is clicked.
602
+ save_question(email or "", question)
603
+
604
+ q = question.lower().strip()
605
+
606
+ # --------------------------------------------------------
607
+ # BASIC QUESTION MATCHING
608
+ # --------------------------------------------------------
609
+
610
+ if "bag" in q and ("feed" in q or "birds" in q):
611
+ answer = """
612
+ ### πŸ” Feed-bag questions
613
+
614
+ For an exact feed estimate, use the calculator above.
615
+
616
+ Enter:
617
+
618
+ 1. Number of birds
619
+ 2. Age in weeks + days
620
+ 3. Feed bag size
621
+ 4. Price per bag
622
+ 5. Your email
623
+
624
+ The calculator will give you the estimated total bags, starter/finisher breakdown and feed cost.
625
+ """
626
+
627
+ elif "starter" in q:
628
+ answer = """
629
+ ### 🌾 Starter feed
630
+
631
+ Starter feed is normally used during the early growth period of broilers.
632
+
633
+ The calculator separates the estimated feed requirement into **Starter** and **Finisher** based on the selected age.
634
+ """
635
+
636
+ elif "finisher" in q:
637
+ answer = """
638
+ ### 🌾 Finisher feed
639
+
640
+ Finisher feed is used after the starter phase.
641
+
642
+ Your calculator automatically estimates the finisher requirement from the selected number of birds and total age.
643
+ """
644
+
645
+ elif "cost" in q or "price" in q:
646
+ answer = """
647
+ ### πŸ’° Feed cost
648
+
649
+ Enter the current price of one feed bag in the calculator.
650
+
651
+ The app calculates:
652
+
653
+ **Number of bags Γ— price per bag = estimated feed cost**
654
+
655
+ The result is for **feed alone**.
656
+ """
657
+
658
+ elif "profit" in q:
659
+ answer = """
660
+ ### πŸ“ˆ Profit questions
661
+
662
+ Profit depends on several things, including:
663
+
664
+ - Number of birds sold
665
+ - Selling price
666
+ - Feed cost
667
+ - Chick cost
668
+ - Medication
669
+ - Vaccination
670
+ - Labour
671
+ - Mortality
672
+ - Other farm expenses
673
+
674
+ A future version can use your saved farmer questions to determine which profit features should be added.
675
+ """
676
+
677
+ else:
678
+ answer = f"""
679
+ ### πŸ’‘ Question received
680
+
681
+ **β€œ{question.strip()}”**
682
+
683
+ Your question has been saved.
684
+
685
+ We can use the questions farmers submit to decide which answers, calculators and features should be added to the app next.
686
+ """
687
+
688
+ return answer
689
+
690
+
691
+ # ============================================================
692
+ # COUNTRY / CURRENCY UI
693
+ # ============================================================
694
+
695
+ def get_country_info():
696
+ country = detect_country()
697
+ currency = currency_for_country(country)
698
+
699
+ return country, currency
700
+
701
+
702
+ DEFAULT_COUNTRY, DEFAULT_CURRENCY = get_country_info()
703
+
704
+
705
+ # ============================================================
706
+ # CSS
707
+ # ============================================================
708
+
709
+ CSS = """
710
+ body {
711
+ background: #f6f8f4;
712
+ }
713
+
714
+ .gradio-container {
715
+ max-width: 1050px !important;
716
+ }
717
+
718
+ .main-title {
719
+ text-align: center;
720
+ padding: 15px 10px 5px 10px;
721
+ }
722
+
723
+ .main-title h1 {
724
+ font-size: 34px;
725
+ margin-bottom: 4px;
726
+ }
727
+
728
+ .main-title p {
729
+ font-size: 17px;
730
+ color: #555;
731
+ }
732
+
733
+ .answer-box {
734
+ border-radius: 16px;
735
+ padding: 8px;
736
+ }
737
+
738
+ .email-box {
739
+ border: 2px solid #d9e7d2;
740
+ border-radius: 12px;
741
+ padding: 10px;
742
+ background: #fbfdf9;
743
+ }
744
+
745
+ .big-answer {
746
+ font-size: 19px;
747
+ }
748
+
749
+ .big-answer h1 {
750
+ font-size: 30px !important;
751
+ }
752
+
753
+ .big-answer h2 {
754
+ font-size: 25px !important;
755
+ }
756
+
757
+ .big-answer h3 {
758
+ font-size: 20px !important;
759
+ }
760
+
761
+ button {
762
+ min-height: 48px !important;
763
+ }
764
+ """
765
+
766
+
767
+ # ============================================================
768
+ # UI
769
+ # ============================================================
770
+
771
+ with gr.Blocks(title=APP_NAME) as demo:
772
+
773
+ gr.HTML(
774
+ """
775
+ <div class="main-title">
776
+ <h1>πŸ” Poultry Feed Calculator</h1>
777
+ <p>
778
+ Know exactly how much feed you need before buying.
779
+ </p>
780
+ </div>
781
+ """
782
+ )
783
+
784
+ # --------------------------------------------------------
785
+ # FARM INPUTS
786
+ # --------------------------------------------------------
787
+
788
+ with gr.Group():
789
+
790
+ gr.Markdown("## πŸ” 1. Number of birds")
791
+
792
+ birds = gr.Dropdown(
793
+ choices=[
794
+ 25,
795
+ 50,
796
+ 75,
797
+ 100,
798
+ 150,
799
+ 200,
800
+ 500,
801
+ 1000,
802
+ ],
803
+ value=50,
804
+ label="Number of birds",
805
+ allow_custom_value=True,
806
+ )
807
+
808
+ gr.Markdown("## πŸ“… 2. Age")
809
+
810
+ with gr.Row():
811
+
812
+ weeks = gr.Dropdown(
813
+ choices=list(range(0, 21)),
814
+ value=6,
815
+ label="Weeks",
816
+ info="Select the number of complete weeks.",
817
+ )
818
+
819
+ days = gr.Dropdown(
820
+ choices=list(range(0, 7)),
821
+ value=0,
822
+ label="Days",
823
+ info="Additional days after the complete weeks.",
824
+ )
825
+
826
+ gr.Markdown("## 🌾 3. Feed")
827
+
828
+ with gr.Row():
829
+
830
+ bag_size = gr.Dropdown(
831
+ choices=[
832
+ 10,
833
+ 20,
834
+ 25,
835
+ 50,
836
+ ],
837
+ value=25,
838
+ label="Feed bag size (kg)",
839
+ )
840
+
841
+ price = gr.Number(
842
+ value=24000,
843
+ label=f"Price per bag ({DEFAULT_CURRENCY})",
844
+ minimum=0,
845
+ )
846
+
847
+ # --------------------------------------------------------
848
+ # EMAIL BEFORE CALCULATE
849
+ # --------------------------------------------------------
850
+
851
+ gr.Markdown("## πŸ“§ 4. Your email")
852
+
853
+ gr.Markdown(
854
+ """
855
+ Enter your email before calculating.
856
+
857
+ Your email lets us save your calculation and helps us
858
+ understand what farmers need from the app.
859
+ """
860
+ )
861
+
862
+ email = gr.Textbox(
863
+ label="Email address",
864
+ placeholder="farmer@example.com",
865
+ type="email",
866
+ elem_classes=["email-box"],
867
+ )
868
+
869
+ calculate_btn = gr.Button(
870
+ "πŸ” Calculate Feed Requirements",
871
+ variant="primary",
872
+ size="lg",
873
+ )
874
+
875
+ result = gr.Markdown(
876
+ value="",
877
+ elem_classes=["answer-box", "big-answer"],
878
+ )
879
+
880
+ save_status = gr.Markdown("")
881
+
882
+ # Hidden country state
883
+ country_state = gr.State(DEFAULT_COUNTRY)
884
+
885
+ # --------------------------------------------------------
886
+ # QUESTION BOX
887
+ # --------------------------------------------------------
888
+
889
+ gr.Markdown("---")
890
+
891
+ gr.Markdown(
892
+ """
893
+ # ❓ Ask a question
894
+
895
+ ### What would you like to know about raising your birds?
896
+ """
897
+ )
898
+
899
+ question = gr.Textbox(
900
+ label="",
901
+ placeholder="Type or speak your question...",
902
+ lines=4,
903
+ )
904
+
905
+ ask_btn = gr.Button(
906
+ "πŸ’¬ Get Answer",
907
+ variant="secondary",
908
+ size="lg",
909
+ )
910
+
911
+ question_answer = gr.Markdown(
912
+ "",
913
+ elem_classes=["answer-box"],
914
+ )
915
+
916
+ # --------------------------------------------------------
917
+ # EVENTS
918
+ # --------------------------------------------------------
919
+
920
+ calculate_btn.click(
921
+ fn=calculate_feed,
922
+ inputs=[
923
+ birds,
924
+ weeks,
925
+ days,
926
+ bag_size,
927
+ price,
928
+ email,
929
+ country_state,
930
+ ],
931
+ outputs=[
932
+ result,
933
+ save_status,
934
+ ],
935
+ )
936
+
937
+ ask_btn.click(
938
+ fn=answer_farmer_question,
939
+ inputs=[
940
+ question,
941
+ email,
942
+ ],
943
+ outputs=[
944
+ question_answer,
945
+ ],
946
+ )
947
+
948
+
949
+ # ============================================================
950
+ # START APP
951
+ # ============================================================
952
+
953
+ if __name__ == "__main__":
954
 
 
 
 
 
 
 
 
955
  port = int(os.environ.get("PORT", "7860"))
956
+
957
  demo.launch(
958
  server_name="0.0.0.0",
959
  server_port=port,
960
  css=CSS,
961
  root_path="/",
962
+ )