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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -706
app.py CHANGED
@@ -1,714 +1,48 @@
1
- import os
2
- import re
3
- import sqlite3
4
- import math
5
- import json
6
- import urllib.request
7
- from datetime import datetime, timezone
8
  from pathlib import Path
9
- from typing import Optional
 
10
 
11
- import gradio as gr
12
- from fastapi import FastAPI, Request
13
- from fastapi.responses import RedirectResponse
14
- from starlette.config import Config
15
- from starlette.middleware.sessions import SessionMiddleware
16
- from authlib.integrations.starlette_client import OAuth, OAuthError
17
 
18
- # -----------------------------
19
- # Configuration
20
- # -----------------------------
21
- APP_NAME = "PoultryFeedCalc"
22
- DB_PATH = Path(os.getenv("LEADS_DB", "/tmp/poultryfeedcalc.db"))
23
- DB_PATH.parent.mkdir(parents=True, exist_ok=True)
24
 
25
- # Feed-stage assumption used by this calculator:
26
- # Starter through day 21; Finisher after day 21.
27
- STARTER_END_DAY = 21
28
 
29
- # Ross 308 as-hatched performance objective cumulative feed intake (kg/bird)
30
- # from Aviagen's 2022 performance objectives. Daily values are used so
31
- # Weeks + Days are calculated in exact total days rather than only at week
32
- # checkpoints. Values below cover day 0-56 and are interpolated for any
33
- # in-between day if needed.
34
- ROSS_CUM_FEED_KG = {
35
- 0: 0.000, 1: 0.012, 2: 0.028, 3: 0.048, 4: 0.072, 5: 0.100,
36
- 6: 0.131, 7: 0.166, 8: 0.206, 9: 0.249, 10: 0.297,
37
- 11: 0.349, 12: 0.406, 13: 0.468, 14: 0.535, 15: 0.608,
38
- 16: 0.685, 17: 0.768, 18: 0.856, 19: 0.950, 20: 1.050,
39
- 21: 1.155, 22: 1.266, 23: 1.383, 24: 1.505, 25: 1.633,
40
- 26: 1.767, 27: 1.907, 28: 2.047, 29: 2.202, 30: 2.357,
41
- 31: 2.518, 32: 2.684, 33: 2.855, 34: 3.031, 35: 3.390,
42
- 36: 3.390, 37: 3.690, 38: 3.930, 39: 4.180, 40: 4.430,
43
- 41: 4.660, 42: 4.890, 43: 5.100, 44: 5.310, 45: 5.520,
44
- 46: 5.444, 47: 5.665, 48: 5.889, 49: 6.116, 50: 6.346,
45
- 51: 6.578, 52: 6.812, 53: 7.049, 54: 7.287, 55: 7.528,
46
- 56: 7.771,
47
- }
48
 
49
- # Approximate expected live body weight (kg/bird) from the same Ross 308
50
- # objective family. Used as a benchmark, not a farm guarantee.
51
- ROSS_WEIGHT_KG = {
52
- 0: 0.044, 7: 0.213, 14: 0.533, 21: 1.012, 28: 1.616,
53
- 35: 2.296, 42: 2.998, 49: 3.668, 56: 4.344,
54
- }
55
-
56
- # Country -> currency code and symbol. This is a display/default mapping,
57
- # not a live FX service.
58
- COUNTRIES = {
59
- "NG": ("NGN", "₦"),
60
- "GH": ("GHS", "GH₵"),
61
- "KE": ("KES", "KSh"),
62
- "UG": ("UGX", "USh"),
63
- "TZ": ("TZS", "TSh"),
64
- "ZA": ("ZAR", "R"),
65
- "ZM": ("ZMW", "ZK"),
66
- "ZW": ("ZWL", "Z$"),
67
- "CM": ("XAF", "FCFA"),
68
- "CI": ("XOF", "CFA"),
69
- "SN": ("XOF", "CFA"),
70
- "BJ": ("XOF", "CFA"),
71
- "BF": ("XOF", "CFA"),
72
- "US": ("USD", "$"),
73
- "CA": ("CAD", "C$"),
74
- "GB": ("GBP", "£"),
75
- "IE": ("EUR", "€"),
76
- "DE": ("EUR", "€"),
77
- "FR": ("EUR", "€"),
78
- "ES": ("EUR", "€"),
79
- "IT": ("EUR", "€"),
80
- "NL": ("EUR", "€"),
81
- "PT": ("EUR", "€"),
82
- "BE": ("EUR", "€"),
83
- "AU": ("AUD", "A$"),
84
- "NZ": ("NZD", "NZ$"),
85
- "IN": ("INR", "₹"),
86
- "PK": ("PKR", "₨"),
87
- "BD": ("BDT", "৳"),
88
- "BR": ("BRL", "R$"),
89
- }
90
-
91
- DEFAULT_PRICE = {
92
- "NGN": 24000,
93
- "GHS": 300,
94
- "KES": 2200,
95
- "UGX": 100000,
96
- "TZS": 30000,
97
- "ZAR": 300,
98
- "ZMW": 350,
99
- "USD": 25,
100
- "GBP": 20,
101
- "EUR": 23,
102
- "INR": 2200,
103
- "PKR": 7000,
104
- "BDT": 2500,
105
- "AUD": 35,
106
- "CAD": 35,
107
- "NZD": 40,
108
- "BRL": 130,
109
- }
110
-
111
- def db_init():
112
- with sqlite3.connect(DB_PATH) as conn:
113
- conn.execute("""
114
- CREATE TABLE IF NOT EXISTS leads (
115
- id INTEGER PRIMARY KEY AUTOINCREMENT,
116
- email TEXT UNIQUE NOT NULL,
117
- country TEXT,
118
- currency TEXT,
119
- source TEXT,
120
- created_at TEXT NOT NULL,
121
- last_seen_at TEXT NOT NULL
122
- )
123
- """)
124
- conn.execute("""
125
- CREATE TABLE IF NOT EXISTS questions (
126
- id INTEGER PRIMARY KEY AUTOINCREMENT,
127
- email TEXT,
128
- question TEXT NOT NULL,
129
- answer TEXT,
130
- created_at TEXT NOT NULL
131
- )
132
- """)
133
- conn.commit()
134
-
135
- db_init()
136
-
137
- def save_lead(email: str, country: str = "", currency: str = "", source: str = "email"):
138
- email = (email or "").strip().lower()
139
- if not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", email):
140
- return False
141
- now = datetime.now(timezone.utc).isoformat()
142
- with sqlite3.connect(DB_PATH) as conn:
143
- conn.execute("""
144
- INSERT INTO leads(email,country,currency,source,created_at,last_seen_at)
145
- VALUES(?,?,?,?,?,?)
146
- ON CONFLICT(email) DO UPDATE SET
147
- country=excluded.country,
148
- currency=excluded.currency,
149
- source=excluded.source,
150
- last_seen_at=excluded.last_seen_at
151
- """, (email, country, currency, source, now, now))
152
- conn.commit()
153
- return True
154
-
155
- def save_question(email: str, question: str, answer: str = ""):
156
- q = (question or "").strip()
157
- if not q:
158
- return
159
- with sqlite3.connect(DB_PATH) as conn:
160
- conn.execute(
161
- "INSERT INTO questions(email,question,answer,created_at) VALUES(?,?,?,?)",
162
- ((email or "").strip().lower(), q, answer or "",
163
- datetime.now(timezone.utc).isoformat())
164
- )
165
- conn.commit()
166
-
167
- def interpolate(table, day):
168
- day = float(day)
169
- keys = sorted(table)
170
- if day <= keys[0]:
171
- return table[keys[0]]
172
- if day >= keys[-1]:
173
- # Linear extension after the last published point.
174
- a, b = keys[-2], keys[-1]
175
- return table[b] + (table[b] - table[a]) * (day - b) / (b - a)
176
- lo = max(k for k in keys if k <= day)
177
- hi = min(k for k in keys if k >= day)
178
- if lo == hi:
179
- return table[lo]
180
- ratio = (day - lo) / (hi - lo)
181
- return table[lo] + (table[hi] - table[lo]) * ratio
182
-
183
- def feed_per_bird(days):
184
- return max(0.0, interpolate(ROSS_CUM_FEED_KG, days))
185
-
186
- def weight_per_bird(days):
187
- return max(0.0, interpolate(ROSS_WEIGHT_KG, days))
188
-
189
- def money(value, symbol):
190
- return f"{symbol}{value:,.0f}"
191
-
192
- def parse_country(request: Optional[gr.Request]):
193
- if not request:
194
- return "NG", "NGN", "₦"
195
-
196
- headers = request.headers or {}
197
-
198
- # First use a country header when the hosting proxy provides one.
199
- country = (
200
- headers.get("x-country-code")
201
- or headers.get("cf-ipcountry")
202
- or headers.get("x-vercel-ip-country")
203
- or headers.get("x-appengine-country")
204
- or ""
205
- ).upper().strip()
206
-
207
- if country in COUNTRIES:
208
- code, sym = COUNTRIES[country]
209
- return country, code, sym
210
-
211
- # Fallback: try the visitor IP with ipapi.co. This is best-effort and
212
- # deliberately has a short timeout so a geo service outage never breaks
213
- # the calculator.
214
- try:
215
- forwarded = headers.get("x-forwarded-for", "")
216
- client_ip = forwarded.split(",")[0].strip() if forwarded else ""
217
- if not client_ip and getattr(request, "client", None):
218
- client_ip = request.client.host
219
- if client_ip and client_ip not in {"127.0.0.1", "::1"}:
220
- with urllib.request.urlopen(
221
- f"https://ipapi.co/{client_ip}/json/",
222
- timeout=2.5
223
- ) as response:
224
- data = json.loads(response.read().decode("utf-8"))
225
- country = str(data.get("country_code", "")).upper()
226
- if country in COUNTRIES:
227
- code, sym = COUNTRIES[country]
228
- return country, code, sym
229
- except Exception:
230
- pass
231
-
232
- # Final fallback for the Nigerian-first MVP.
233
- return "NG", "NGN", "₦"
234
-
235
- def country_on_load(request: gr.Request):
236
- country, currency, symbol = parse_country(request)
237
- return country, currency, symbol, DEFAULT_PRICE.get(currency, 25)
238
-
239
- def user_email_on_load(request: gr.Request):
240
- try:
241
- if request and hasattr(request, "request") and request.request:
242
- pass
243
- except Exception:
244
- pass
245
- return ""
246
-
247
- # -----------------------------
248
- # Google OAuth (optional)
249
- # -----------------------------
250
- GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID", "")
251
- GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET", "")
252
- SESSION_SECRET = os.getenv("SESSION_SECRET", "change-this-secret-in-production")
253
-
254
- fastapi_app = FastAPI()
255
- fastapi_app.add_middleware(SessionMiddleware, secret_key=SESSION_SECRET)
256
-
257
- google_enabled = bool(GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET)
258
- oauth = None
259
-
260
- if google_enabled:
261
- config = Config(environ={
262
- "GOOGLE_CLIENT_ID": GOOGLE_CLIENT_ID,
263
- "GOOGLE_CLIENT_SECRET": GOOGLE_CLIENT_SECRET,
264
- })
265
- oauth = OAuth(config)
266
- oauth.register(
267
- name="google",
268
- server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
269
- client_kwargs={"scope": "openid email profile"},
270
- )
271
-
272
- @fastapi_app.get("/login/google")
273
- async def google_login(request: Request):
274
- if not google_enabled:
275
- return RedirectResponse(url="/?google=not-configured")
276
- redirect_uri = request.url_for("google_auth")
277
- return await oauth.google.authorize_redirect(request, redirect_uri)
278
-
279
- @fastapi_app.get("/auth/google")
280
- async def google_auth(request: Request):
281
- if not google_enabled:
282
- return RedirectResponse(url="/?google=not-configured")
283
- try:
284
- token = await oauth.google.authorize_access_token(request)
285
- userinfo = dict(token).get("userinfo") or await oauth.google.userinfo(token=token)
286
- request.session["user"] = {
287
- "email": userinfo.get("email", ""),
288
- "name": userinfo.get("name", ""),
289
- }
290
- email = userinfo.get("email", "")
291
- if email:
292
- country, currency, _ = parse_country(None)
293
- save_lead(email, country, currency, "google")
294
- return RedirectResponse(url="/")
295
- except OAuthError:
296
- return RedirectResponse(url="/?google=error")
297
-
298
- @fastapi_app.get("/logout")
299
- async def logout(request: Request):
300
- request.session.pop("user", None)
301
- return RedirectResponse(url="/")
302
-
303
- @fastapi_app.get("/health")
304
- def health():
305
- return {"status": "ok", "app": APP_NAME}
306
-
307
- # -----------------------------
308
- # Calculator
309
- # -----------------------------
310
- BIRD_OPTIONS = ["25", "50", "75", "100", "150", "200", "500", "1,000", "Custom"]
311
-
312
- def parse_birds(value):
313
- if value is None:
314
- raise ValueError("Select the number of birds.")
315
- text = str(value).replace(",", "").strip()
316
- if text.lower() == "custom":
317
- raise ValueError("Enter a custom number of birds.")
318
- n = int(text)
319
- if n < 1:
320
- raise ValueError("Number of birds must be at least 1.")
321
- return n
322
-
323
- def calculate_feed(
324
- birds_value, custom_birds, weeks, days_extra, bag_size, price_per_bag,
325
- email, currency_code, currency_symbol, request: gr.Request
326
- ):
327
- # Determine bird count.
328
- try:
329
- birds = parse_birds(custom_birds if str(birds_value).lower() == "custom" else birds_value)
330
- except Exception as e:
331
- return f"⚠️ {e}"
332
-
333
- email = (email or "").strip().lower()
334
-
335
- # If the browser session has Google login, use that email automatically.
336
- # The public Gradio event request may expose the underlying FastAPI session
337
- # only when mounted; this is handled through the hidden/session email state
338
- # populated by the separate route where possible. Manual email remains the
339
- # reliable fallback.
340
- if not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", email):
341
- return "⚠️ Please enter a valid email address before calculating."
342
-
343
- try:
344
- weeks = int(weeks)
345
- days_extra = int(days_extra)
346
- bag_size = float(bag_size)
347
- price = float(price_per_bag)
348
- except Exception:
349
- return "⚠️ Please select valid age, bag size and price values."
350
-
351
- if weeks < 0 or weeks > 16 or days_extra < 0 or days_extra > 6:
352
- return "⚠️ Please enter a valid age."
353
- if bag_size <= 0 or price < 0:
354
- return "⚠️ Feed bag size must be positive and price cannot be negative."
355
-
356
- total_days = weeks * 7 + days_extra
357
- if total_days <= 0:
358
- return "⚠️ Bird age must be at least 1 day."
359
-
360
- # Save the lead automatically when Calculate is clicked.
361
- country, detected_currency, detected_symbol = parse_country(request)
362
- if not currency_code:
363
- currency_code = detected_currency
364
- if not currency_symbol:
365
- currency_symbol = detected_symbol
366
- save_lead(email, country, currency_code, "calculator")
367
-
368
- # Feed calculations (NO planning buffer)
369
- cumulative = feed_per_bird(total_days)
370
- total_feed = cumulative * birds
371
-
372
- starter_per_bird = feed_per_bird(min(total_days, STARTER_END_DAY))
373
- finisher_per_bird = max(0.0, cumulative - starter_per_bird)
374
-
375
- starter_kg = starter_per_bird * birds
376
- finisher_kg = finisher_per_bird * birds
377
-
378
- # Calculate theoretical whole bags by stage and total bags by total feed.
379
- exact_total_bags = total_feed / bag_size
380
- whole_total_bags = math.ceil(exact_total_bags)
381
-
382
- # Stage purchasing recommendation.
383
- starter_bags = math.ceil(starter_kg / bag_size) if starter_kg > 0 else 0
384
- finisher_bags = max(0, whole_total_bags - starter_bags)
385
-
386
- # If the stage split is close to a bag boundary, ensure the total capacity
387
- # covers the total feed.
388
- while (starter_bags + finisher_bags) * bag_size < total_feed:
389
- finisher_bags += 1
390
-
391
- total_cost = whole_total_bags * price
392
- expected_weight = weight_per_bird(total_days)
393
- live_weight = expected_weight * birds
394
-
395
- age_text = f"{weeks} week" + ("" if weeks == 1 else "s")
396
- if days_extra:
397
- age_text += f" + {days_extra} day" + ("" if days_extra == 1 else "s")
398
- age_text += f" ({total_days} days)"
399
-
400
- quick = (
401
- f"### 🎯 Quick answer\n"
402
- f"**To raise {birds:,} birds for {total_days} days ({age_text.replace(' (' + str(total_days) + ' days)', '')}), "
403
- f"you will need an estimated → {whole_total_bags} bags of feed "
404
- f"({starter_bags} Starter + {finisher_bags} Finisher), costing approximately "
405
- f"{money(total_cost, currency_symbol)} on feed alone.**"
406
- )
407
-
408
- html = f"""
409
- <div class="answer-card">
410
- <div class="answer-title">🐔 Your Feed Requirement</div>
411
- <div class="big-answer">
412
- You will require approximately <b>{whole_total_bags} bags of {bag_size:g} kg feed</b>
413
- </div>
414
- <div class="sub-answer">To raise <b>{birds:,} birds</b> for <b>{total_days} days</b>.</div>
415
-
416
- <table class="feed-table">
417
- <thead><tr><th>Feed</th><th>Estimated quantity</th><th>Bags to buy</th></tr></thead>
418
- <tbody>
419
- <tr><td>🌱 Starter</td><td>{starter_kg:,.1f} kg</td><td>{starter_bags} bags</td></tr>
420
- <tr><td>🌾 Finisher</td><td>{finisher_kg:,.1f} kg</td><td>{finisher_bags} bags</td></tr>
421
- <tr class="total"><td><b>TOTAL</b></td><td><b>{total_feed:,.1f} kg</b></td><td><b>{whole_total_bags} bags</b></td></tr>
422
- </tbody>
423
- </table>
424
-
425
- <div class="cost-box">
426
- <div class="cost-title">💰 Estimated feed cost</div>
427
- <div class="cost-value">{money(total_cost, currency_symbol)}</div>
428
- <div>on feed alone.</div>
429
- <div class="small">Based on {money(price, currency_symbol)} per {bag_size:g}-kg bag.</div>
430
- </div>
431
-
432
- <div class="quick-box">
433
- <b>🎯 Quick answer:</b> To raise <b>{birds:,} birds for {total_days} days</b>,
434
- you will need an estimate → <b>{whole_total_bags} bags of feed</b>
435
- ({starter_bags} Starter + {finisher_bags} Finisher), costing approximately
436
- <b>{money(total_cost, currency_symbol)}</b>.
437
- </div>
438
-
439
- <div class="benchmark">
440
- <h3>📊 Ross 308 benchmark at {total_days} days</h3>
441
- <ul>
442
- <li>Expected body weight: <b>{expected_weight:,.2f} kg/bird</b></li>
443
- <li>Expected flock live weight: <b>{live_weight:,.1f} kg</b></li>
444
- <li>Benchmark cumulative feed: <b>{cumulative:,.2f} kg/bird</b></li>
445
- </ul>
446
- </div>
447
-
448
- <div class="note">
449
- <b>Important:</b> This is an estimate based on Ross 308 performance objectives.
450
- Actual farm consumption varies with genetics, sex, mortality, feed quality,
451
- temperature, management and other farm conditions.
452
- </div>
453
- </div>
454
- """
455
- return html
456
-
457
- def ask_question(question, email, birds_value, custom_birds, weeks, days_extra,
458
- bag_size, price, currency_code, currency_symbol, request: gr.Request):
459
- q = (question or "").strip()
460
- if not q:
461
- return "⚠️ Please type or speak your question."
462
-
463
- # Auto-save the question whenever Get Answer is clicked.
464
- if email:
465
- save_lead(email, *parse_country(request)[0:1], currency_code, "question")
466
-
467
- # Try to answer common calculator questions automatically.
468
- lower = q.lower()
469
- bird_match = re.search(r"(\d[\d,]*)\s*(?:birds|broilers|chickens?)", lower)
470
- week_match = re.search(r"(\d+)\s*(?:weeks?|wks?)", lower)
471
- day_match = re.search(r"(\d+)\s*(?:days?|dys?)", lower)
472
- bag_match = re.search(r"(\d+(?:\.\d+)?)\s*(?:bags?|bag)", lower)
473
-
474
- birds = int(bird_match.group(1).replace(",", "")) if bird_match else None
475
- w = int(week_match.group(1)) if week_match else None
476
- d = int(day_match.group(1)) if day_match else 0
477
-
478
- if birds and w is not None:
479
- total_days = w * 7 + d
480
- cumulative = feed_per_bird(total_days)
481
- total_feed = birds * cumulative
482
- try:
483
- bag = float(bag_size)
484
- p = float(price)
485
- except Exception:
486
- bag, p = 25.0, 24000.0
487
- total_bags = math.ceil(total_feed / bag)
488
- starter_kg = birds * feed_per_bird(min(total_days, STARTER_END_DAY))
489
- starter_bags = math.ceil(starter_kg / bag)
490
- finisher_bags = max(0, total_bags - starter_bags)
491
- cost = total_bags * p
492
- answer = (
493
- f"### 🤖 Answer\n"
494
- f"For **{birds:,} birds** at **{total_days} days ({w} weeks"
495
- f"{f' + {d} days' if d else ''})**, the estimate is **{total_feed:,.1f} kg of feed** "
496
- f"or approximately **{total_bags} bags of {bag:g} kg** "
497
- f"(**{starter_bags} Starter + {finisher_bags} Finisher**).\n\n"
498
- f"At the current bag price, that is approximately **{money(cost, currency_symbol)}** on feed alone.\n\n"
499
- f"_This is an estimate based on the Ross 308 benchmark and actual farm use can vary._"
500
- )
501
- elif bag_match and birds:
502
- answer = (
503
- "I can compare the bags you mentioned with the benchmark, but I also need the "
504
- "target age in weeks. Please include it, for example: "
505
- "`Is 3 bags enough for 51 birds at 3 weeks?`"
506
- )
507
- else:
508
- answer = (
509
- "### 🤖 Question saved\n"
510
- "I have saved this question for future PoultryFeedCalc improvements. "
511
- "For a direct feed calculation, include the **number of birds and target age** "
512
- "in weeks/days, for example: `How many bags for 500 broilers for 8 weeks?`"
513
- )
514
-
515
- save_question(email, q, answer)
516
- return answer
517
-
518
- def get_session_email(request: gr.Request):
519
- # Gradio's request wrapper exposes the Starlette request in different
520
- # versions. Try the known shapes without failing the app.
521
- try:
522
- raw = getattr(request, "request", None)
523
- if raw is not None:
524
- user = raw.session.get("user")
525
- if user and user.get("email"):
526
- return user["email"]
527
- except Exception:
528
- pass
529
- return ""
530
-
531
- # -----------------------------
532
- # UI
533
- # -----------------------------
534
- CSS = """
535
- body { background: #f7f8fa; }
536
- .gradio-container { max-width: 1200px !important; }
537
- .hero { padding: 18px 4px 10px; }
538
- .hero h1 { font-size: 38px; margin: 0 0 6px; }
539
- .hero p { font-size: 17px; color: #4b5563; }
540
- .section { border-radius: 14px; }
541
- .answer-card { background: white; border: 1px solid #e5e7eb; border-radius: 16px; padding: 24px; box-shadow: 0 4px 18px rgba(0,0,0,.05); }
542
- .answer-title { font-size: 28px; font-weight: 800; margin-bottom: 12px; }
543
- .big-answer { font-size: 24px; line-height: 1.35; margin-bottom: 8px; }
544
- .sub-answer { font-size: 17px; margin-bottom: 18px; }
545
- .feed-table { width: 100%; border-collapse: collapse; margin: 12px 0 20px; }
546
- .feed-table th, .feed-table td { border: 1px solid #d1d5db; padding: 11px; text-align: left; }
547
- .feed-table th { background: #f3f4f6; }
548
- .feed-table .total { background: #fafafa; }
549
- .cost-box { margin: 18px 0; }
550
- .cost-title { font-size: 20px; font-weight: 800; }
551
- .cost-value { font-size: 30px; font-weight: 900; margin-top: 4px; }
552
- .small { color: #6b7280; margin-top: 6px; }
553
- .quick-box { border-left: 5px solid #f97316; background: #fff7ed; padding: 14px; margin: 20px 0; font-size: 18px; line-height: 1.5; }
554
- .benchmark { margin-top: 20px; }
555
- .note { margin-top: 18px; color: #6b7280; font-size: 13px; line-height: 1.5; }
556
- .email-box { background: #eef2ff; border-radius: 14px; padding: 16px; }
557
- """
558
-
559
- with gr.Blocks(css=CSS, title=APP_NAME) as demo:
560
- gr.HTML("""
561
- <div class="hero">
562
- <h1>🐔 PoultryFeedCalc</h1>
563
- <p>Simple broiler feed calculator for farmers — no calculations required.</p>
564
- <p><b>Choose your birds, age, bag size and price.</b> The app calculates feed, Starter/Finisher bags and estimated feed cost.</p>
565
- </div>
566
- """)
567
-
568
- # Hidden country/currency values populated on page load.
569
- detected_country = gr.State("NG")
570
- detected_currency = gr.State("NGN")
571
- currency_symbol = gr.State("₦")
572
-
573
- with gr.Group(elem_classes=["email-box"]):
574
- gr.Markdown("### 🔐 Before you calculate")
575
- gr.Markdown("Enter your email so we can send you future PoultryFeedCalc updates and improvements.")
576
- email = gr.Textbox(
577
- label="Email address",
578
- placeholder="farmer@example.com",
579
- type="email",
580
- info="Required before calculating. If Google sign-in is enabled, your Google email can be used automatically."
581
- )
582
- if google_enabled:
583
- gr.Markdown("**Already have Google?**")
584
- gr.Button("🇬 Sign in with Google", link="/login/google", variant="secondary")
585
- else:
586
- gr.Markdown(
587
- "Google sign-in is optional. Add `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` "
588
- "to your Space secrets to enable it."
589
- )
590
-
591
- with gr.Row():
592
- with gr.Column(scale=1):
593
- gr.Markdown("## 🧮 Farm inputs")
594
-
595
- birds = gr.Dropdown(
596
- choices=BIRD_OPTIONS,
597
- value="25",
598
- label="🐔 Number of birds",
599
- info="Select a common flock size or choose Custom."
600
- )
601
- custom_birds = gr.Number(
602
- label="Custom number of birds",
603
- value=None,
604
- precision=0,
605
- minimum=1,
606
- visible=False
607
- )
608
- birds.change(
609
- lambda x: gr.update(visible=str(x).lower() == "custom"),
610
- inputs=birds,
611
- outputs=custom_birds
612
- )
613
-
614
- weeks = gr.Dropdown(
615
- choices=list(range(0, 17)),
616
- value=5,
617
- label="📅 Age — Weeks"
618
- )
619
- days_extra = gr.Dropdown(
620
- choices=list(range(0, 7)),
621
- value=0,
622
- label="📅 Age — Days",
623
- info="Weeks + Days are converted to total days."
624
- )
625
- bag_size = gr.Dropdown(
626
- choices=[10, 20, 25, 50],
627
- value=25,
628
- label="🌾 Feed bag size (kg)"
629
- )
630
- price = gr.Number(
631
- value=24000,
632
- precision=0,
633
- label="💰 Price per bag",
634
- info="Price is shown in your detected local currency."
635
- )
636
-
637
- calculate_btn = gr.Button(
638
- "🐔 Calculate Feed Requirement",
639
- variant="primary",
640
- size="lg"
641
- )
642
-
643
- with gr.Column(scale=1):
644
- gr.Markdown("## 🐔 Your feed requirement")
645
- result = gr.HTML(
646
- "<div class='answer-card'><b>Enter your email, choose your farm inputs, then click Calculate.</b></div>"
647
- )
648
-
649
- gr.Markdown("---")
650
- with gr.Group():
651
- gr.Markdown("## ❓ Ask a question")
652
- gr.Markdown("### What would you like to know about raising your birds?")
653
- gr.Markdown("Type your question. You can also use your browser/device microphone if supported by the browser.")
654
- question = gr.Textbox(
655
- label="Your question",
656
- placeholder="e.g. How many bags of feed for 500 broilers for 8 weeks?",
657
- lines=3
658
- )
659
- ask_btn = gr.Button("🤖 Get Answer", variant="primary", size="lg")
660
- question_answer = gr.Markdown()
661
-
662
- gr.Markdown("---")
663
- gr.Markdown(
664
- "### 📌 How the estimate works\n"
665
- "- Age is calculated in **total days** from Weeks + Days.\n"
666
- "- Starter is counted through **day 21**; Finisher is after day 21.\n"
667
- "- The total number of bags is calculated from **feed ÷ bag size and rounded up**.\n"
668
- "- The total bag count is the purchase recommendation; Starter + Finisher bag counts are allocated so they do not double-count bags.\n"
669
- "- Ross 308 performance objectives are used as the numerical benchmark. Actual farm consumption can vary."
670
- )
671
-
672
- # Load country/currency and Google session email.
673
- demo.load(
674
- country_on_load,
675
- inputs=None,
676
- outputs=[detected_country, detected_currency, currency_symbol, price]
677
- )
678
- demo.load(
679
- get_session_email,
680
- inputs=None,
681
- outputs=email
682
- )
683
-
684
- calculate_btn.click(
685
- calculate_feed,
686
- inputs=[
687
- birds, custom_birds, weeks, days_extra, bag_size, price,
688
- email, detected_currency, currency_symbol
689
- ],
690
- outputs=result
691
- )
692
-
693
- ask_btn.click(
694
- ask_question,
695
- inputs=[
696
- question, email, birds, custom_birds, weeks, days_extra,
697
- bag_size, price, detected_currency, currency_symbol
698
- ],
699
- outputs=question_answer
700
- )
701
-
702
- # Mount once; do not call demo.launch() as well.
703
- fastapi_app = gr.mount_gradio_app(
704
- fastapi_app,
705
- demo,
706
- path="/",
707
- root_path="/",
708
- footer_links=[]
709
- )
710
-
711
- if __name__ == "__main__":
712
  import uvicorn
713
  port = int(os.environ.get("PORT", "7860"))
714
- uvicorn.run(fastapi_app, host="0.0.0.0", port=port)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")