Spaces:
Paused

NTEIGBANAM OKE commited on
Commit
8062816
·
verified ·
1 Parent(s): f3869af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1691 -161
app.py CHANGED
@@ -1,210 +1,1740 @@
1
- # Updated PoultryFeedCalc MVP
2
- # Features: simple selections, age in weeks + days, day-based interpolation,
3
- # starter/finisher split, whole-bag cost estimate, and farmer question collection.
4
-
5
- import math
6
  import os
7
- from datetime import datetime
 
 
 
 
 
8
  import pandas as pd
9
  import gradio as gr
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  ROSS_WEEKLY = pd.DataFrame([
12
- {"Week":0,"Day":0,"Body Weight (kg/bird)":0.044,"Daily Intake (g/bird/day)":None,"Cumulative Feed (kg/bird)":0.000,"FCR":None},
13
- {"Week":1,"Day":7,"Body Weight (kg/bird)":0.213,"Daily Intake (g/bird/day)":35,"Cumulative Feed (kg/bird)":0.166,"FCR":0.780},
14
- {"Week":2,"Day":14,"Body Weight (kg/bird)":0.533,"Daily Intake (g/bird/day)":67,"Cumulative Feed (kg/bird)":0.535,"FCR":1.005},
15
- {"Week":3,"Day":21,"Body Weight (kg/bird)":1.046,"Daily Intake (g/bird/day)":111,"Cumulative Feed (kg/bird)":1.193,"FCR":1.141},
16
- {"Week":4,"Day":28,"Body Weight (kg/bird)":1.697,"Daily Intake (g/bird/day)":155,"Cumulative Feed (kg/bird)":2.147,"FCR":1.266},
17
- {"Week":5,"Day":35,"Body Weight (kg/bird)":2.441,"Daily Intake (g/bird/day)":195,"Cumulative Feed (kg/bird)":3.394,"FCR":1.390},
18
- {"Week":6,"Day":42,"Body Weight (kg/bird)":3.222,"Daily Intake (g/bird/day)":226,"Cumulative Feed (kg/bird)":4.886,"FCR":1.517},
19
- {"Week":7,"Day":49,"Body Weight (kg/bird)":3.991,"Daily Intake (g/bird/day)":247,"Cumulative Feed (kg/bird)":6.556,"FCR":1.643},
20
- {"Week":8,"Day":56,"Body Weight (kg/bird)":4.714,"Daily Intake (g/bird/day)":258,"Cumulative Feed (kg/bird)":8.332,"FCR":1.768},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  ])
22
 
23
 
24
- def num(value, default):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
- return float(value)
27
  except Exception:
28
- return float(default)
29
-
30
-
31
- def interpolate_at_day(day):
32
- day = max(0, min(56, int(day)))
33
- out = {}
34
- for col, key in [
35
- ("Body Weight (kg/bird)", "body_weight"),
36
- ("Cumulative Feed (kg/bird)", "cumulative_feed"),
37
- ("Daily Intake (g/bird/day)", "daily_intake"),
38
- ("FCR", "fcr"),
39
- ]:
40
- values = ROSS_WEEKLY[col].astype(float).interpolate().bfill().ffill()
41
- out[key] = float(__import__("numpy").interp(day, ROSS_WEEKLY["Day"], values))
42
- return out
43
-
44
-
45
- def calculate(birds, weeks, days, bag_size, bag_price):
46
- birds = max(1, int(num(birds, 100)))
47
- weeks = max(0, min(8, int(num(weeks, 6))))
48
- days = max(0, min(6, int(num(days, 0))))
49
- bag_size = max(1, num(bag_size, 25))
50
- bag_price = max(0, num(bag_price, 24000))
51
-
52
- total_days = min(56, weeks * 7 + days)
53
- age_w, age_d = divmod(total_days, 7)
54
- age_text = f"{age_w} week{'s' if age_w != 1 else ''}"
55
- if age_d:
56
- age_text += f" + {age_d} day{'s' if age_d != 1 else ''}"
57
-
58
- b = interpolate_at_day(total_days)
59
- total_feed = birds * b["cumulative_feed"]
60
- exact_bags = total_feed / bag_size
61
- bags_to_buy = math.ceil(exact_bags)
62
- total_cost = bags_to_buy * bag_price
63
-
64
- # Starter through day 21; finisher after day 21.
65
- starter_per_bird = min(b["cumulative_feed"], 1.193)
66
- finisher_per_bird = max(0, b["cumulative_feed"] - 1.193)
67
- starter_kg = birds * starter_per_bird
68
- finisher_kg = birds * finisher_per_bird
69
- starter_bags = math.ceil(starter_kg / bag_size) if starter_kg else 0
70
- finisher_bags = math.ceil(finisher_kg / bag_size) if finisher_kg else 0
71
- phase_cost = (starter_bags + finisher_bags) * bag_price
72
-
73
- summary = f"""# 🐔 Your feed requirement
74
-
75
- ### You will require approximately **{bags_to_buy} bags of {bag_size:g} kg feed**
76
- to raise **{birds:,} birds to {age_text} ({total_days} days)**.
77
-
78
- | Feed | Quantity | Whole bags to buy |
79
- |---|---:|---:|
80
- | 🌱 Starter | **{starter_kg:,.1f} kg** | **{starter_bags} bags** |
81
- | 🌾 Finisher | **{finisher_kg:,.1f} kg** | **{finisher_bags} bags** |
82
- | **Total** | **{total_feed:,.1f} kg** | **{bags_to_buy} bags** |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  ### 💰 Estimated feed cost
85
- **₦{phase_cost:,.0f}** on feed alone.
86
 
87
- *Based on ₦{bag_price:,.0f} per {bag_size:g}-kg bag.*
88
 
89
- > **Quick answer:** {birds:,} birds × {total_days} days → **{bags_to_buy} bags** ({starter_bags} Starter + {finisher_bags} Finisher), costing approximately **₦{phase_cost:,.0f}**.
90
 
91
- ### 📊 Ross benchmark at {total_days} days
92
- - Expected body weight: **{b['body_weight']:.2f} kg/bird**
93
- - Expected flock live weight: **{birds*b['body_weight']:,.1f} kg**
94
- - Cumulative feed: **{b['cumulative_feed']:.2f} kg/bird**
95
- - Approx. daily intake: **{b['daily_intake']:.0f} g/bird/day**
96
- - Benchmark FCR: **{b['fcr']:.3f}**
 
 
 
 
 
97
  """
98
 
99
- explanation = f"""## 📌 How the estimate works
 
 
100
 
101
- The calculator converts **Weeks + Days into total days**. For example, 6 weeks + 3 days = **45 days**.
 
 
 
 
102
 
103
- It interpolates between the weekly Ross checkpoints to estimate feed at ages between whole weeks.
 
 
 
 
104
 
105
- - **Starter:** feed through day 21
106
- - **Finisher:** feed after day 21
107
- - Bag count is rounded up to the number of whole bags to buy.
108
 
109
- Actual farm consumption can vary with genetics, sex, mortality, feed quality, temperature, management and other farm conditions.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  """
111
- return summary, explanation
112
 
 
 
 
113
 
114
- QUESTIONS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "farmer_questions.csv")
 
 
 
 
 
115
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- def answer_farmer_question(question):
118
- q = (question or "").strip().lower()
119
- if not q:
120
- return "Type a question first."
121
- if any(x in q for x in ["how many bags", "bags of feed", "how much feed", "feed do i need", "feed needed"]):
122
- return "Use the calculator above: select your number of birds, age in weeks + days, bag size and price. It will calculate total feed, Starter/Finisher bags and estimated feed cost."
123
- if "starter" in q and "finisher" in q:
124
- return "The calculator treats Starter as feed through day 21 and Finisher as feed after day 21, using the selected age in total days."
125
- if "cost" in q or "price" in q or "money" in q:
126
- return "Enter your current price per bag above. The app multiplies the required whole bags by your price to estimate feed cost."
127
- if "3 bags" in q or "enough" in q:
128
- return "Enter the exact number of birds, age and bag size above. The calculator will compare the required whole bags with the number you have."
129
- return "Thanks. Your question can be saved below for future app improvements. For a feed calculation, use the calculator above."
130
 
131
 
132
- def save_question(question, audio_path):
133
- question = (question or "").strip()
134
- if not question and not audio_path:
135
- return "Please type or record a question first."
136
- row = pd.DataFrame([{
137
- "timestamp": datetime.now().isoformat(timespec="seconds"),
138
- "question": question,
139
- "voice_recording": audio_path or "",
140
- }])
141
- row.to_csv(QUESTIONS_FILE, mode="a", header=not os.path.exists(QUESTIONS_FILE), index=False)
142
- return "✅ Question saved for future app improvements."
 
 
 
 
 
 
 
 
 
 
 
143
 
 
 
 
 
 
 
 
144
 
145
- def benchmark_table():
146
- d = ROSS_WEEKLY.copy()
147
- d["Body Weight (kg/bird)"] = d["Body Weight (kg/bird)"].map(lambda x: f"{x:.3f}")
148
- d["Cumulative Feed (kg/bird)"] = d["Cumulative Feed (kg/bird)"].map(lambda x: f"{x:.3f}")
149
- d["Daily Intake (g/bird/day)"] = d["Daily Intake (g/bird/day)"].map(lambda x: "-" if pd.isna(x) else f"{int(x)}")
150
- d["FCR"] = d["FCR"].map(lambda x: "-" if pd.isna(x) else f"{x:.3f}")
151
- return d
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- with gr.Blocks(title="PoultryFeedCalc") as demo:
155
- gr.Markdown("""# 🐔 PoultryFeedCalc
156
  ### Simple broiler feed calculator for farmers
157
- Choose the number of birds, age, bag size and price — **no calculations required.**""")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
  with gr.Row():
160
- with gr.Column(scale=1):
161
- gr.Markdown("## 🧮 Farm inputs")
162
- birds = gr.Dropdown(label="🐔 Number of birds", choices=["25","50","75","100","150","200","500","1,000","Custom"], value="100")
163
- custom_birds = gr.Number(label="Custom number of birds", minimum=1, value=100, precision=0, visible=False)
164
- weeks = gr.Dropdown(label="📅 Age — Weeks", choices=list(range(0,9)), value=6)
165
- days = gr.Dropdown(label="📅 Age — Days", choices=list(range(0,7)), value=0)
166
- bag_size = gr.Dropdown(label="🌾 Feed bag size", choices=[10,25,50], value=25)
167
- bag_price = gr.Number(label="💰 Price per bag (₦)", minimum=0, value=24000, precision=0)
168
- calculate_btn = gr.Button("🐔 Calculate Feed Requirement", variant="primary")
169
-
170
- with gr.Column(scale=2):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  summary = gr.Markdown()
172
- explanation = gr.Markdown()
173
 
174
- gr.Markdown("---")
175
- gr.Markdown("## ❓ Ask a question")
176
- gr.Markdown("**What would you like to know about raising your birds?**\n\nType your question or use the microphone. Questions are saved to guide future upgrades and answers.")
177
- with gr.Row():
178
- farmer_question = gr.Textbox(label="Your question", placeholder="Type your question here...", lines=3, scale=3)
179
- farmer_voice = gr.Audio(label="🎤 Speak your question", sources=["microphone"], type="filepath", scale=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  with gr.Row():
181
- answer_btn = gr.Button("🤖 Get Answer")
182
- save_question_btn = gr.Button("💾 Save Question")
 
 
 
 
 
 
 
 
 
 
183
  question_answer = gr.Markdown()
 
184
  question_status = gr.Markdown()
185
 
186
- gr.Markdown("---\n## 📊 Ross 308 weekly benchmark")
187
- gr.Dataframe(value=benchmark_table(), interactive=False, wrap=True)
188
- gr.Markdown("""## 🇳🇬 Nigeria management reference
189
- Use local management guidance alongside the numerical benchmark. Farm results vary with housing, ventilation, temperature, water, feed quality, stocking density, vaccination, mortality and management.
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
- **Benchmark source:** Aviagen — Ross 308 / Ross 308 FF Broiler Performance Objectives (2022).
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
- **Nigeria management reference:** Agrited — *Everything You Need To Know About Raising Excellent Broiler Chickens in Nigeria*.
 
 
194
 
195
- This MVP is a planning and calculation tool. It is not veterinary advice.""")
 
 
196
 
197
- birds.change(lambda v: gr.update(visible=v == "Custom"), inputs=birds, outputs=custom_birds)
198
- calculate_btn.click(
199
- lambda selected, custom, w, d, size, price: calculate(int(str(custom if selected == "Custom" else selected).replace(",", "")), w, d, size, price),
200
- inputs=[birds, custom_birds, weeks, days, bag_size, bag_price], outputs=[summary, explanation]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  )
202
- answer_btn.click(answer_farmer_question, inputs=farmer_question, outputs=question_answer)
203
- save_question_btn.click(save_question, inputs=[farmer_question, farmer_voice], outputs=question_status)
204
- demo.load(
205
- lambda selected, custom, w, d, size, price: calculate(int(str(custom if selected == "Custom" else selected).replace(",", "")), w, d, size, price),
206
- inputs=[birds, custom_birds, weeks, days, bag_size, bag_price], outputs=[summary, explanation]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  )
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  if __name__ == "__main__":
210
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import math
3
+ import re
4
+ from datetime import datetime, timezone
5
+ from urllib.parse import urlparse, urlunparse
6
+
7
+ import requests
8
  import pandas as pd
9
  import gradio as gr
10
 
11
+ from fastapi import FastAPI, Request
12
+ from fastapi.responses import RedirectResponse
13
+ from starlette.config import Config
14
+ from starlette.middleware.sessions import SessionMiddleware
15
+
16
+ from authlib.integrations.starlette_client import OAuth, OAuthError
17
+
18
+
19
+ # ============================================================
20
+ # CONFIGURATION
21
+ # ============================================================
22
+
23
+ APP_NAME = "PoultryFeedCalc"
24
+
25
+ DEFAULT_BAG_SIZE = 25
26
+ DEFAULT_BAG_PRICE = 24000
27
+
28
+ # Practical allowance above the Ross benchmark.
29
+ # Example:
30
+ # 25 birds × 6 weeks = about 4.89 benchmark bags
31
+ # 4.89 × 1.20 = about 5.86 bags
32
+ # Rounded up = 6 bags
33
+ FEED_ALLOWANCE = 1.20
34
+
35
+ # External webhook for mailing list + questions.
36
+ #
37
+ # Recommended:
38
+ # Google Apps Script Web App
39
+ #
40
+ # Set in Hugging Face Space Secrets:
41
+ # LEADS_WEBHOOK_URL=https://script.google.com/macros/s/XXXXXXXX/exec
42
+ #
43
+ LEADS_WEBHOOK_URL = os.getenv("LEADS_WEBHOOK_URL", "").strip()
44
+
45
+ # Optional OpenAI API key for answering farmer questions.
46
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
47
+
48
+ # Google OAuth settings.
49
+ GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID", "").strip()
50
+ GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET", "").strip()
51
+
52
+ # Session secret.
53
+ SESSION_SECRET = os.getenv(
54
+ "SESSION_SECRET",
55
+ "CHANGE_THIS_SECRET_IN_HUGGINGFACE_SECRETS"
56
+ )
57
+
58
+ # Your public Space URL.
59
+ # Example:
60
+ # https://okejonah1-poultry-feed-calculator.hf.space
61
+ SPACE_URL = os.getenv(
62
+ "SPACE_URL",
63
+ "https://okejonah1-poultry-feed-calculator.hf.space"
64
+ ).rstrip("/")
65
+
66
+
67
+ # ============================================================
68
+ # ROSS 308 PERFORMANCE DATA
69
+ # ============================================================
70
+
71
  ROSS_WEEKLY = pd.DataFrame([
72
+ {
73
+ "Week": 0,
74
+ "Day": 0,
75
+ "Body Weight (kg/bird)": 0.044,
76
+ "Daily Intake (g/bird/day)": None,
77
+ "Cumulative Feed (kg/bird)": 0.000,
78
+ "FCR": None,
79
+ },
80
+ {
81
+ "Week": 1,
82
+ "Day": 7,
83
+ "Body Weight (kg/bird)": 0.213,
84
+ "Daily Intake (g/bird/day)": 35,
85
+ "Cumulative Feed (kg/bird)": 0.166,
86
+ "FCR": 0.780,
87
+ },
88
+ {
89
+ "Week": 2,
90
+ "Day": 14,
91
+ "Body Weight (kg/bird)": 0.533,
92
+ "Daily Intake (g/bird/day)": 67,
93
+ "Cumulative Feed (kg/bird)": 0.535,
94
+ "FCR": 1.005,
95
+ },
96
+ {
97
+ "Week": 3,
98
+ "Day": 21,
99
+ "Body Weight (kg/bird)": 1.046,
100
+ "Daily Intake (g/bird/day)": 111,
101
+ "Cumulative Feed (kg/bird)": 1.193,
102
+ "FCR": 1.141,
103
+ },
104
+ {
105
+ "Week": 4,
106
+ "Day": 28,
107
+ "Body Weight (kg/bird)": 1.697,
108
+ "Daily Intake (g/bird/day)": 155,
109
+ "Cumulative Feed (kg/bird)": 2.147,
110
+ "FCR": 1.266,
111
+ },
112
+ {
113
+ "Week": 5,
114
+ "Day": 35,
115
+ "Body Weight (kg/bird)": 2.441,
116
+ "Daily Intake (g/bird/day)": 195,
117
+ "Cumulative Feed (kg/bird)": 3.394,
118
+ "FCR": 1.390,
119
+ },
120
+ {
121
+ "Week": 6,
122
+ "Day": 42,
123
+ "Body Weight (kg/bird)": 3.222,
124
+ "Daily Intake (g/bird/day)": 226,
125
+ "Cumulative Feed (kg/bird)": 4.886,
126
+ "FCR": 1.517,
127
+ },
128
+ {
129
+ "Week": 7,
130
+ "Day": 49,
131
+ "Body Weight (kg/bird)": 3.991,
132
+ "Daily Intake (g/bird/day)": 247,
133
+ "Cumulative Feed (kg/bird)": 6.556,
134
+ "FCR": 1.643,
135
+ },
136
+ {
137
+ "Week": 8,
138
+ "Day": 56,
139
+ "Body Weight (kg/bird)": 4.714,
140
+ "Daily Intake (g/bird/day)": 258,
141
+ "Cumulative Feed (kg/bird)": 8.332,
142
+ "FCR": 1.768,
143
+ },
144
  ])
145
 
146
 
147
+ # ============================================================
148
+ # HELPER FUNCTIONS
149
+ # ============================================================
150
+
151
+ def clean_email(email):
152
+ if not email:
153
+ return ""
154
+
155
+ email = str(email).strip().lower()
156
+
157
+ pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
158
+
159
+ if re.match(pattern, email):
160
+ return email
161
+
162
+ return ""
163
+
164
+
165
+ def get_google_user(request: gr.Request):
166
+ """
167
+ Retrieve the Google OAuth user stored in the Starlette session.
168
+ """
169
+
170
+ if request is None:
171
+ return None
172
+
173
+ try:
174
+ session = getattr(request, "session", None)
175
+
176
+ if session is None and getattr(request, "request", None):
177
+ session = getattr(request.request, "session", None)
178
+
179
+ if not session:
180
+ return None
181
+
182
+ # Authlib session structure.
183
+ oauth_info = session.get("user")
184
+
185
+ if oauth_info:
186
+ return oauth_info
187
+
188
+ oauth_info = session.get("oauth_info")
189
+
190
+ if oauth_info:
191
+ return oauth_info.get("userinfo", oauth_info)
192
+
193
+ except Exception:
194
+ pass
195
+
196
+ return None
197
+
198
+
199
+ def get_logged_in_email(request: gr.Request):
200
+ user = get_google_user(request)
201
+
202
+ if not user:
203
+ return ""
204
+
205
+ email = (
206
+ user.get("email")
207
+ if isinstance(user, dict)
208
+ else ""
209
+ )
210
+
211
+ return clean_email(email)
212
+
213
+
214
+ def post_to_webhook(payload):
215
+ """
216
+ Save lead/question to external Google Apps Script webhook.
217
+
218
+ The app remains functional if the webhook is not configured.
219
+ """
220
+
221
+ if not LEADS_WEBHOOK_URL:
222
+ return False
223
+
224
+ try:
225
+ response = requests.post(
226
+ LEADS_WEBHOOK_URL,
227
+ json=payload,
228
+ timeout=10,
229
+ )
230
+
231
+ return response.ok
232
+
233
+ except Exception:
234
+ return False
235
+
236
+
237
+ def save_lead(
238
+ email,
239
+ source="calculator",
240
+ question="",
241
+ birds=None,
242
+ age_days=None,
243
+ ):
244
+ email = clean_email(email)
245
+
246
+ if not email:
247
+ return False
248
+
249
+ payload = {
250
+ "type": "lead",
251
+ "email": email,
252
+ "source": source,
253
+ "question": question or "",
254
+ "birds": birds,
255
+ "age_days": age_days,
256
+ "timestamp": datetime.now(
257
+ timezone.utc
258
+ ).isoformat(),
259
+ }
260
+
261
+ return post_to_webhook(payload)
262
+
263
+
264
+ def save_question(
265
+ email,
266
+ question,
267
+ birds=None,
268
+ age_days=None,
269
+ ):
270
+ """
271
+ Called automatically when Get Answer is clicked.
272
+ """
273
+
274
+ question = str(question or "").strip()
275
+
276
+ if not question:
277
+ return False
278
+
279
+ payload = {
280
+ "type": "farmer_question",
281
+ "email": clean_email(email),
282
+ "question": question,
283
+ "birds": birds,
284
+ "age_days": age_days,
285
+ "timestamp": datetime.now(
286
+ timezone.utc
287
+ ).isoformat(),
288
+ }
289
+
290
+ return post_to_webhook(payload)
291
+
292
+
293
+ def interpolate_benchmark(total_days):
294
+ """
295
+ Interpolate between Ross weekly checkpoints.
296
+
297
+ Example:
298
+ 45 days = between week 6 and week 7.
299
+ """
300
+
301
+ total_days = float(total_days)
302
+
303
+ if total_days <= 0:
304
+ row = ROSS_WEEKLY.iloc[0]
305
+
306
+ return {
307
+ "body_weight": float(row["Body Weight (kg/bird)"]),
308
+ "cumulative_feed": float(row["Cumulative Feed (kg/bird)"]),
309
+ "daily_intake": row["Daily Intake (g/bird/day)"],
310
+ "fcr": row["FCR"],
311
+ "week": 0,
312
+ }
313
+
314
+ if total_days >= 56:
315
+ row = ROSS_WEEKLY.iloc[-1]
316
+
317
+ return {
318
+ "body_weight": float(row["Body Weight (kg/bird)"]),
319
+ "cumulative_feed": float(row["Cumulative Feed (kg/bird)"]),
320
+ "daily_intake": row["Daily Intake (g/bird/day)"],
321
+ "fcr": row["FCR"],
322
+ "week": 8,
323
+ }
324
+
325
+ for i in range(len(ROSS_WEEKLY) - 1):
326
+
327
+ left = ROSS_WEEKLY.iloc[i]
328
+ right = ROSS_WEEKLY.iloc[i + 1]
329
+
330
+ left_day = float(left["Day"])
331
+ right_day = float(right["Day"])
332
+
333
+ if left_day <= total_days <= right_day:
334
+
335
+ span = right_day - left_day
336
+
337
+ if span == 0:
338
+ ratio = 0
339
+ else:
340
+ ratio = (
341
+ total_days - left_day
342
+ ) / span
343
+
344
+ def interp(a, b):
345
+ return float(a) + (
346
+ float(b) - float(a)
347
+ ) * ratio
348
+
349
+ body_weight = interp(
350
+ left["Body Weight (kg/bird)"],
351
+ right["Body Weight (kg/bird)"],
352
+ )
353
+
354
+ cumulative_feed = interp(
355
+ left["Cumulative Feed (kg/bird)"],
356
+ right["Cumulative Feed (kg/bird)"],
357
+ )
358
+
359
+ left_intake = left[
360
+ "Daily Intake (g/bird/day)"
361
+ ]
362
+
363
+ right_intake = right[
364
+ "Daily Intake (g/bird/day)"
365
+ ]
366
+
367
+ if pd.isna(left_intake):
368
+ daily_intake = right_intake
369
+ else:
370
+ daily_intake = interp(
371
+ left_intake,
372
+ right_intake,
373
+ )
374
+
375
+ left_fcr = left["FCR"]
376
+ right_fcr = right["FCR"]
377
+
378
+ if pd.isna(left_fcr):
379
+ fcr = right_fcr
380
+ else:
381
+ fcr = interp(
382
+ left_fcr,
383
+ right_fcr,
384
+ )
385
+
386
+ return {
387
+ "body_weight": body_weight,
388
+ "cumulative_feed": cumulative_feed,
389
+ "daily_intake": daily_intake,
390
+ "fcr": fcr,
391
+ "week": total_days / 7,
392
+ }
393
+
394
+ return None
395
+
396
+
397
+ # ============================================================
398
+ # FEED PHASE CALCULATION
399
+ # ============================================================
400
+
401
+ def calculate_phase_feed(total_days, birds):
402
+ """
403
+ Starter is treated as feed through day 21.
404
+ Finisher is feed after day 21.
405
+
406
+ We derive each phase from the cumulative Ross benchmark.
407
+ """
408
+
409
+ benchmark = interpolate_benchmark(total_days)
410
+
411
+ total_feed_per_bird = benchmark[
412
+ "cumulative_feed"
413
+ ]
414
+
415
+ total_feed = (
416
+ total_feed_per_bird * birds
417
+ )
418
+
419
+ starter_days = min(total_days, 21)
420
+
421
+ starter_benchmark = interpolate_benchmark(
422
+ starter_days
423
+ )
424
+
425
+ starter_per_bird = starter_benchmark[
426
+ "cumulative_feed"
427
+ ]
428
+
429
+ starter_feed = (
430
+ starter_per_bird * birds
431
+ )
432
+
433
+ finisher_feed = max(
434
+ 0,
435
+ total_feed - starter_feed
436
+ )
437
+
438
+ return (
439
+ starter_feed,
440
+ finisher_feed,
441
+ total_feed,
442
+ )
443
+
444
+
445
+ def allocate_phase_bags(
446
+ total_bags,
447
+ starter_feed,
448
+ finisher_feed,
449
+ ):
450
+ """
451
+ Allocate the already-rounded TOTAL bags
452
+ between Starter and Finisher.
453
+
454
+ This prevents the previous error where:
455
+ ceil(Starter bags) + ceil(Finisher bags)
456
+
457
+ could produce more bags than the actual total.
458
+
459
+ The sum of Starter + Finisher ALWAYS equals total_bags.
460
+ """
461
+
462
+ total_phase_feed = (
463
+ starter_feed + finisher_feed
464
+ )
465
+
466
+ if total_bags <= 0 or total_phase_feed <= 0:
467
+ return 0, 0
468
+
469
+ starter_share = (
470
+ starter_feed / total_phase_feed
471
+ )
472
+
473
+ starter_bags = round(
474
+ total_bags * starter_share
475
+ )
476
+
477
+ starter_bags = max(
478
+ 0,
479
+ min(total_bags, starter_bags)
480
+ )
481
+
482
+ finisher_bags = (
483
+ total_bags - starter_bags
484
+ )
485
+
486
+ # If Starter exists, make sure it receives
487
+ # at least one bag when total feed reaches it.
488
+ if starter_feed > 0 and total_bags >= 1:
489
+ starter_bags = max(
490
+ 1,
491
+ starter_bags
492
+ )
493
+
494
+ starter_bags = min(
495
+ starter_bags,
496
+ total_bags
497
+ )
498
+
499
+ finisher_bags = (
500
+ total_bags - starter_bags
501
+ )
502
+
503
+ return (
504
+ starter_bags,
505
+ finisher_bags,
506
+ )
507
+
508
+
509
+ # ============================================================
510
+ # MAIN CALCULATOR
511
+ # ============================================================
512
+
513
+ def calculate(
514
+ birds,
515
+ weeks,
516
+ days,
517
+ bag_size,
518
+ bag_price,
519
+ email,
520
+ consent,
521
+ request: gr.Request = None,
522
+ ):
523
+ """
524
+ Main calculator.
525
+
526
+ Email is required before calculation.
527
+ Google email is used automatically when available.
528
+ """
529
+
530
+ # --------------------------------------------------------
531
+ # EMAIL / GOOGLE SIGN-IN
532
+ # --------------------------------------------------------
533
+
534
+ google_email = get_logged_in_email(request)
535
+
536
+ typed_email = clean_email(email)
537
+
538
+ final_email = (
539
+ google_email
540
+ if google_email
541
+ else typed_email
542
+ )
543
+
544
+ if not final_email:
545
+ return (
546
+ "### 🔐 Email required\n\n"
547
+ "Please enter your email address or "
548
+ "use **Continue with Google** before "
549
+ "calculating your feed requirement.",
550
+ "",
551
+ "",
552
+ gr.update(),
553
+ "⚠️ Please provide your email first.",
554
+ )
555
+
556
+ if not consent:
557
+ return (
558
+ "### 📩 One small step first\n\n"
559
+ "Please tick the box confirming that "
560
+ "you agree to receive farming tips and "
561
+ "updates by email.",
562
+ "",
563
+ "",
564
+ gr.update(value=final_email),
565
+ "⚠️ Please confirm email consent.",
566
+ )
567
+
568
+ # --------------------------------------------------------
569
+ # CLEAN INPUTS
570
+ # --------------------------------------------------------
571
+
572
+ try:
573
+ birds = int(float(birds))
574
+ except Exception:
575
+ birds = 100
576
+
577
+ birds = max(1, birds)
578
+
579
+ try:
580
+ weeks = int(float(weeks))
581
+ except Exception:
582
+ weeks = 6
583
+
584
  try:
585
+ days = int(float(days))
586
  except Exception:
587
+ days = 0
588
+
589
+ weeks = max(0, min(8, weeks))
590
+ days = max(0, min(6, days))
591
+
592
+ total_days = (
593
+ weeks * 7
594
+ ) + days
595
+
596
+ total_days = max(
597
+ 1,
598
+ min(56, total_days)
599
+ )
600
+
601
+ try:
602
+ bag_size = float(bag_size)
603
+ except Exception:
604
+ bag_size = DEFAULT_BAG_SIZE
605
+
606
+ bag_size = max(
607
+ 1,
608
+ bag_size
609
+ )
610
+
611
+ try:
612
+ bag_price = float(bag_price)
613
+ except Exception:
614
+ bag_price = DEFAULT_BAG_PRICE
615
+
616
+ bag_price = max(
617
+ 0,
618
+ bag_price
619
+ )
620
+
621
+ # --------------------------------------------------------
622
+ # BENCHMARK
623
+ # --------------------------------------------------------
624
+
625
+ benchmark = interpolate_benchmark(
626
+ total_days
627
+ )
628
+
629
+ body_weight = benchmark[
630
+ "body_weight"
631
+ ]
632
+
633
+ cumulative_feed = benchmark[
634
+ "cumulative_feed"
635
+ ]
636
+
637
+ daily_intake = benchmark[
638
+ "daily_intake"
639
+ ]
640
+
641
+ fcr = benchmark[
642
+ "fcr"
643
+ ]
644
+
645
+ # --------------------------------------------------------
646
+ # FEED REQUIREMENT
647
+ # --------------------------------------------------------
648
+
649
+ (
650
+ starter_feed,
651
+ finisher_feed,
652
+ benchmark_total_feed,
653
+ ) = calculate_phase_feed(
654
+ total_days,
655
+ birds,
656
+ )
657
+
658
+ # Add practical allowance.
659
+ adjusted_feed = (
660
+ benchmark_total_feed
661
+ * FEED_ALLOWANCE
662
+ )
663
+
664
+ adjusted_starter_feed = (
665
+ starter_feed
666
+ * FEED_ALLOWANCE
667
+ )
668
+
669
+ adjusted_finisher_feed = (
670
+ finisher_feed
671
+ * FEED_ALLOWANCE
672
+ )
673
+
674
+ # IMPORTANT:
675
+ # Round ONLY after calculating the TOTAL.
676
+ exact_bags = (
677
+ adjusted_feed
678
+ / bag_size
679
+ )
680
+
681
+ whole_bags = math.ceil(
682
+ exact_bags
683
+ )
684
+
685
+ # Allocate those final bags between phases.
686
+ starter_bags, finisher_bags = (
687
+ allocate_phase_bags(
688
+ whole_bags,
689
+ adjusted_starter_feed,
690
+ adjusted_finisher_feed,
691
+ )
692
+ )
693
+
694
+ estimated_cost = (
695
+ whole_bags
696
+ * bag_price
697
+ )
698
+
699
+ expected_live_weight = (
700
+ birds
701
+ * body_weight
702
+ )
703
+
704
+ # --------------------------------------------------------
705
+ # DISPLAY TEXT
706
+ # --------------------------------------------------------
707
+
708
+ age_text = (
709
+ f"{weeks} week"
710
+ f"{'s' if weeks != 1 else ''}"
711
+ )
712
+
713
+ if days > 0:
714
+ age_text += (
715
+ f" + {days} day"
716
+ f"{'s' if days != 1 else ''}"
717
+ )
718
+
719
+ age_text_full = (
720
+ f"{age_text} ({total_days} days)"
721
+ )
722
+
723
+ exact_text = (
724
+ f"{exact_bags:.1f}"
725
+ )
726
+
727
+ summary = f"""
728
+ # 🐔 Your feed requirement
729
+
730
+ ## You will require approximately **{whole_bags} bags of {bag_size:g} kg feed**
731
+
732
+ To raise **{birds:,} birds** to **{age_text_full}**.
733
+
734
+ ### 🌾 Feed breakdown
735
+
736
+ | Feed | Bags |
737
+ |---|---:|
738
+ | 🌱 Starter | **{starter_bags} bags** |
739
+ | 🌽 Finisher | **{finisher_bags} bags** |
740
+ | **TOTAL** | **{whole_bags} bags** |
741
 
742
  ### 💰 Estimated feed cost
 
743
 
744
+ # **₦{estimated_cost:,.0f}**
745
 
746
+ **Feed only.**
747
 
748
+ Based on approximately **{exact_text} bags** before rounding up.
749
+
750
+ ---
751
+
752
+ ## 🎯 Quick answer
753
+
754
+ **To raise {birds:,} birds for {total_days} days ({weeks} week{'s' if weeks != 1 else ''}), you will require an estimated {whole_bags} bags of {bag_size:g} kg feed ({starter_bags} Starter + {finisher_bags} Finisher), costing approximately ₦{estimated_cost:,.0f} on feed alone.**
755
+
756
+ We have included a **20% practical allowance** above the Ross benchmark to give the farmer a safer planning estimate.
757
+
758
+ Actual feed consumption can vary with genetics, sex, mortality, feed quality, temperature, management and farm conditions.
759
  """
760
 
761
+ # --------------------------------------------------------
762
+ # BENCHMARK OUTPUT
763
+ # --------------------------------------------------------
764
 
765
+ daily_intake_text = (
766
+ "-"
767
+ if pd.isna(daily_intake)
768
+ else f"{float(daily_intake):.0f}"
769
+ )
770
 
771
+ fcr_text = (
772
+ "-"
773
+ if pd.isna(fcr)
774
+ else f"{float(fcr):.3f}"
775
+ )
776
 
777
+ benchmark_text = f"""
778
+ ## 📊 Ross 308 benchmark at {total_days} days
 
779
 
780
+ - **Expected body weight:** {body_weight:.2f} kg/bird
781
+ - **Expected flock live weight:** {expected_live_weight:,.1f} kg
782
+ - **Cumulative benchmark feed:** {cumulative_feed:.3f} kg/bird
783
+ - **Daily feed intake near this age:** {daily_intake_text} g/bird/day
784
+ - **Benchmark FCR:** {fcr_text}
785
+
786
+ ### How the estimate works
787
+
788
+ Ross benchmark feed:
789
+ **{benchmark_total_feed:,.1f} kg**
790
+
791
+ Practical allowance:
792
+ **+20%**
793
+
794
+ Planning feed:
795
+ **{adjusted_feed:,.1f} kg**
796
+
797
+ Equivalent:
798
+ **{exact_bags:.1f} bags**
799
+
800
+ Rounded up:
801
+ **{whole_bags} bags**
802
  """
 
803
 
804
+ # --------------------------------------------------------
805
+ # SAVE LEAD
806
+ # --------------------------------------------------------
807
 
808
+ saved = save_lead(
809
+ email=final_email,
810
+ source="feed_calculator",
811
+ birds=birds,
812
+ age_days=total_days,
813
+ )
814
 
815
+ if saved:
816
+ status = (
817
+ f"✅ Calculation complete. "
818
+ f"Your email has been saved for "
819
+ f"farming tips and updates."
820
+ )
821
+ else:
822
+ status = (
823
+ "✅ Calculation complete."
824
+ )
825
 
826
+ return (
827
+ summary,
828
+ benchmark_text,
829
+ "",
830
+ gr.update(
831
+ value=final_email
832
+ ),
833
+ status,
834
+ )
 
 
 
 
835
 
836
 
837
+ # ============================================================
838
+ # FARMER QUESTION ANSWER
839
+ # ============================================================
840
+
841
+ def simple_question_answer(question):
842
+ """
843
+ Fallback answer engine when OPENAI_API_KEY
844
+ is not configured.
845
+
846
+ Questions are still saved automatically.
847
+ """
848
+
849
+ q = question.lower().strip()
850
+
851
+ if "bag" in q or "feed" in q:
852
+ return (
853
+ "Use the feed calculator above and select "
854
+ "your number of birds, age in weeks + days, "
855
+ "bag size and price. It will estimate the "
856
+ "Starter and Finisher feed requirement and "
857
+ "total feed cost."
858
+ )
859
 
860
+ if "water" in q:
861
+ return (
862
+ "Clean, safe drinking water is essential "
863
+ "for broilers. Water quality and availability "
864
+ "can strongly affect feed intake and bird "
865
+ "performance."
866
+ )
867
 
868
+ if "weight" in q:
869
+ return (
870
+ "Expected weight varies with genetics, sex, "
871
+ "nutrition, temperature and management. "
872
+ "The calculator uses Ross 308 performance "
873
+ "objectives as its numerical benchmark."
874
+ )
875
 
876
+ if "vaccin" in q:
877
+ return (
878
+ "Vaccination programs should follow the "
879
+ "recommendation of your veterinarian and "
880
+ "local poultry health program because disease "
881
+ "risk varies by location and farm."
882
+ )
883
+
884
+ return (
885
+ "Your question has been recorded. The app will "
886
+ "use farmer questions like this to improve the "
887
+ "answers available in future versions."
888
+ )
889
+
890
+
891
+ def ai_question_answer(question):
892
+ """
893
+ Optional OpenAI-powered answer.
894
+
895
+ If OPENAI_API_KEY is not configured, use the
896
+ built-in fallback answer.
897
+ """
898
+
899
+ if not OPENAI_API_KEY:
900
+ return simple_question_answer(
901
+ question
902
+ )
903
+
904
+ try:
905
+ from openai import OpenAI
906
+
907
+ client = OpenAI(
908
+ api_key=OPENAI_API_KEY
909
+ )
910
+
911
+ response = client.responses.create(
912
+ model="gpt-5-mini",
913
+ input=[
914
+ {
915
+ "role": "system",
916
+ "content": (
917
+ "You are a practical poultry farming "
918
+ "assistant for farmers in Nigeria. "
919
+ "Give clear, simple and useful answers. "
920
+ "Use metric units and Nigerian naira where "
921
+ "appropriate. Do not invent veterinary "
922
+ "instructions. If a question requires "
923
+ "veterinary diagnosis or treatment, advise "
924
+ "the farmer to consult a qualified poultry "
925
+ "veterinarian. Keep answers farmer-friendly."
926
+ ),
927
+ },
928
+ {
929
+ "role": "user",
930
+ "content": question,
931
+ },
932
+ ],
933
+ )
934
+
935
+ return response.output_text
936
+
937
+ except Exception:
938
+ return simple_question_answer(
939
+ question
940
+ )
941
+
942
+
943
+ def answer_farmer_question(
944
+ question,
945
+ email,
946
+ consent,
947
+ birds,
948
+ weeks,
949
+ days,
950
+ request: gr.Request = None,
951
+ ):
952
+ """
953
+ IMPORTANT:
954
+ Clicking GET ANSWER automatically saves the question.
955
+ """
956
+
957
+ question = str(
958
+ question or ""
959
+ ).strip()
960
+
961
+ if not question:
962
+ return (
963
+ "Please type or speak your question first.",
964
+ "⚠️ No question was entered.",
965
+ )
966
+
967
+ google_email = get_logged_in_email(
968
+ request
969
+ )
970
+
971
+ final_email = (
972
+ google_email
973
+ or clean_email(email)
974
+ )
975
+
976
+ if not final_email:
977
+ return (
978
+ "### 🔐 Email required\n\n"
979
+ "Please enter your email or use "
980
+ "**Continue with Google** first.",
981
+ "⚠️ Please provide your email first.",
982
+ )
983
+
984
+ if not consent:
985
+ return (
986
+ "### 📩 Almost there\n\n"
987
+ "Please confirm that you agree to receive "
988
+ "farming tips and updates by email.",
989
+ "⚠️ Please confirm email consent.",
990
+ )
991
+
992
+ try:
993
+ total_days = (
994
+ int(weeks) * 7
995
+ + int(days)
996
+ )
997
+ except Exception:
998
+ total_days = 0
999
+
1000
+ # SAVE QUESTION FIRST.
1001
+ saved = save_question(
1002
+ email=final_email,
1003
+ question=question,
1004
+ birds=birds,
1005
+ age_days=total_days,
1006
+ )
1007
+
1008
+ # Answer after saving.
1009
+ answer = ai_question_answer(
1010
+ question
1011
+ )
1012
+
1013
+ if saved:
1014
+ status = (
1015
+ "✅ Question saved automatically. "
1016
+ "Thank you — this helps us understand "
1017
+ "what farmers need."
1018
+ )
1019
+ else:
1020
+ status = (
1021
+ "✅ Answer generated. "
1022
+ "The question was also processed for "
1023
+ "future improvements."
1024
+ )
1025
+
1026
+ return (
1027
+ f"## 🤖 Answer\n\n{answer}",
1028
+ status,
1029
+ )
1030
+
1031
+
1032
+ # ============================================================
1033
+ # GOOGLE OAUTH
1034
+ # ============================================================
1035
+
1036
+ oauth = OAuth(
1037
+ Config(
1038
+ environ={
1039
+ "GOOGLE_CLIENT_ID": GOOGLE_CLIENT_ID,
1040
+ "GOOGLE_CLIENT_SECRET": GOOGLE_CLIENT_SECRET,
1041
+ }
1042
+ )
1043
+ )
1044
+
1045
+ if GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
1046
+
1047
+ oauth.register(
1048
+ name="google",
1049
+ server_metadata_url=(
1050
+ "https://accounts.google.com/"
1051
+ ".well-known/openid-configuration"
1052
+ ),
1053
+ client_kwargs={
1054
+ "scope": (
1055
+ "openid email profile"
1056
+ )
1057
+ },
1058
+ )
1059
+
1060
+
1061
+ # ============================================================
1062
+ # FASTAPI APP
1063
+ # ============================================================
1064
+
1065
+ fastapi_app = FastAPI()
1066
+
1067
+ fastapi_app.add_middleware(
1068
+ SessionMiddleware,
1069
+ secret_key=SESSION_SECRET,
1070
+ same_site="lax",
1071
+ https_only=True,
1072
+ )
1073
+
1074
+
1075
+ @fastapi_app.get("/login")
1076
+ async def google_login(request: Request):
1077
+
1078
+ if not (
1079
+ GOOGLE_CLIENT_ID
1080
+ and GOOGLE_CLIENT_SECRET
1081
+ ):
1082
+ return RedirectResponse(
1083
+ url="/"
1084
+ )
1085
+
1086
+ redirect_uri = (
1087
+ SPACE_URL
1088
+ + "/auth"
1089
+ )
1090
+
1091
+ return await oauth.google.authorize_redirect(
1092
+ request,
1093
+ redirect_uri,
1094
+ )
1095
+
1096
+
1097
+ @fastapi_app.get("/auth")
1098
+ async def google_auth(request: Request):
1099
+
1100
+ if not (
1101
+ GOOGLE_CLIENT_ID
1102
+ and GOOGLE_CLIENT_SECRET
1103
+ ):
1104
+ return RedirectResponse(
1105
+ url="/"
1106
+ )
1107
+
1108
+ try:
1109
+
1110
+ token = await oauth.google.authorize_access_token(
1111
+ request
1112
+ )
1113
+
1114
+ userinfo = dict(
1115
+ token.get("userinfo", {})
1116
+ )
1117
+
1118
+ request.session[
1119
+ "user"
1120
+ ] = userinfo
1121
+
1122
+ request.session[
1123
+ "oauth_info"
1124
+ ] = {
1125
+ "userinfo": userinfo
1126
+ }
1127
+
1128
+ except OAuthError:
1129
+
1130
+ return RedirectResponse(
1131
+ url="/"
1132
+ )
1133
+
1134
+ return RedirectResponse(
1135
+ url="/"
1136
+ )
1137
+
1138
+
1139
+ @fastapi_app.get("/logout")
1140
+ async def logout(request: Request):
1141
+
1142
+ request.session.clear()
1143
+
1144
+ return RedirectResponse(
1145
+ url="/"
1146
+ )
1147
+
1148
+
1149
+ # ============================================================
1150
+ # GRADIO UI
1151
+ # ============================================================
1152
+
1153
+ with gr.Blocks(
1154
+ title=APP_NAME,
1155
+ theme=gr.themes.Soft(),
1156
+ ) as demo:
1157
+
1158
+ gr.Markdown(
1159
+ """
1160
+ # 🐔 PoultryFeedCalc
1161
 
 
 
1162
  ### Simple broiler feed calculator for farmers
1163
+
1164
+ Choose the number of birds, age, feed bag size and price —
1165
+ **no calculations required.**
1166
+
1167
+ The calculator converts **weeks + days into total days**
1168
+ and estimates the feed required to raise your birds.
1169
+ """
1170
+ )
1171
+
1172
+ # --------------------------------------------------------
1173
+ # EMAIL / SIGN-IN
1174
+ # --------------------------------------------------------
1175
+
1176
+ with gr.Group():
1177
+
1178
+ gr.Markdown(
1179
+ """
1180
+ ## 🔐 Before you calculate
1181
+
1182
+ Enter your email address so we can send you useful
1183
+ poultry-farming tips, updates and new tools.
1184
+
1185
+ You can type your email **or sign in with Google**.
1186
+ """
1187
+ )
1188
+
1189
+ with gr.Row():
1190
+
1191
+ email = gr.Textbox(
1192
+ label="📧 Email address",
1193
+ placeholder="farmer@example.com",
1194
+ type="email",
1195
+ )
1196
+
1197
+ if GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
1198
+
1199
+ google_btn = gr.Button(
1200
+ "🔵 Continue with Google",
1201
+ link="/login",
1202
+ )
1203
+
1204
+ else:
1205
+
1206
+ gr.Markdown(
1207
+ """
1208
+ **Google Sign-In will appear once Google OAuth
1209
+ credentials are configured in the Space Secrets.**
1210
+ """
1211
+ )
1212
+
1213
+ consent = gr.Checkbox(
1214
+ label=(
1215
+ "Yes, I agree to receive poultry farming "
1216
+ "tips, useful updates and new tools by email."
1217
+ ),
1218
+ value=False,
1219
+ )
1220
+
1221
+ # --------------------------------------------------------
1222
+ # CALCULATOR
1223
+ # --------------------------------------------------------
1224
 
1225
  with gr.Row():
1226
+
1227
+ with gr.Column(
1228
+ scale=1
1229
+ ):
1230
+
1231
+ gr.Markdown(
1232
+ "## 🧮 Farm inputs"
1233
+ )
1234
+
1235
+ birds = gr.Dropdown(
1236
+ label="🐔 Number of birds",
1237
+ choices=[
1238
+ "25",
1239
+ "50",
1240
+ "75",
1241
+ "100",
1242
+ "150",
1243
+ "200",
1244
+ "500",
1245
+ "1000",
1246
+ "Custom",
1247
+ ],
1248
+ value="25",
1249
+ )
1250
+
1251
+ custom_birds = gr.Number(
1252
+ label="Custom number of birds",
1253
+ minimum=1,
1254
+ precision=0,
1255
+ value=25,
1256
+ visible=False,
1257
+ )
1258
+
1259
+ def show_custom_birds(value):
1260
+
1261
+ if value == "Custom":
1262
+ return gr.update(
1263
+ visible=True
1264
+ )
1265
+
1266
+ return gr.update(
1267
+ visible=False
1268
+ )
1269
+
1270
+ birds.change(
1271
+ show_custom_birds,
1272
+ inputs=birds,
1273
+ outputs=custom_birds,
1274
+ )
1275
+
1276
+ weeks = gr.Dropdown(
1277
+ label="📅 Age — Weeks",
1278
+ choices=list(
1279
+ range(0, 9)
1280
+ ),
1281
+ value=6,
1282
+ )
1283
+
1284
+ days = gr.Dropdown(
1285
+ label="📅 Age — Days",
1286
+ choices=list(
1287
+ range(0, 7)
1288
+ ),
1289
+ value=0,
1290
+ )
1291
+
1292
+ bag_size = gr.Dropdown(
1293
+ label="🌾 Feed bag size",
1294
+ choices=[
1295
+ 10,
1296
+ 25,
1297
+ 50,
1298
+ 70,
1299
+ "Custom",
1300
+ ],
1301
+ value=25,
1302
+ )
1303
+
1304
+ custom_bag_size = gr.Number(
1305
+ label="Custom bag size (kg)",
1306
+ minimum=1,
1307
+ value=25,
1308
+ visible=False,
1309
+ )
1310
+
1311
+ def show_custom_bag(value):
1312
+
1313
+ if value == "Custom":
1314
+ return gr.update(
1315
+ visible=True
1316
+ )
1317
+
1318
+ return gr.update(
1319
+ visible=False
1320
+ )
1321
+
1322
+ bag_size.change(
1323
+ show_custom_bag,
1324
+ inputs=bag_size,
1325
+ outputs=custom_bag_size,
1326
+ )
1327
+
1328
+ bag_price = gr.Number(
1329
+ label="💰 Price per bag (₦)",
1330
+ minimum=0,
1331
+ value=DEFAULT_BAG_PRICE,
1332
+ )
1333
+
1334
+ calculate_btn = gr.Button(
1335
+ "🐔 Calculate Feed Requirement",
1336
+ variant="primary",
1337
+ size="lg",
1338
+ )
1339
+
1340
+ # ----------------------------------------------------
1341
+ # RESULTS
1342
+ # ----------------------------------------------------
1343
+
1344
+ with gr.Column(
1345
+ scale=2
1346
+ ):
1347
+
1348
  summary = gr.Markdown()
 
1349
 
1350
+ benchmark = gr.Markdown()
1351
+
1352
+ comparison = gr.Markdown()
1353
+
1354
+ calculation_status = gr.Markdown()
1355
+
1356
+ # --------------------------------------------------------
1357
+ # CALCULATION WRAPPER
1358
+ # --------------------------------------------------------
1359
+
1360
+ def run_calculation(
1361
+ birds_value,
1362
+ custom_birds_value,
1363
+ weeks_value,
1364
+ days_value,
1365
+ bag_value,
1366
+ custom_bag_value,
1367
+ bag_price_value,
1368
+ email_value,
1369
+ consent_value,
1370
+ request=None,
1371
+ ):
1372
+
1373
+ if birds_value == "Custom":
1374
+
1375
+ actual_birds = (
1376
+ custom_birds_value
1377
+ )
1378
+
1379
+ else:
1380
+
1381
+ actual_birds = (
1382
+ birds_value
1383
+ )
1384
+
1385
+ if bag_value == "Custom":
1386
+
1387
+ actual_bag_size = (
1388
+ custom_bag_value
1389
+ )
1390
+
1391
+ else:
1392
+
1393
+ actual_bag_size = (
1394
+ bag_value
1395
+ )
1396
+
1397
+ return calculate(
1398
+ actual_birds,
1399
+ weeks_value,
1400
+ days_value,
1401
+ actual_bag_size,
1402
+ bag_price_value,
1403
+ email_value,
1404
+ consent_value,
1405
+ request,
1406
+ )
1407
+
1408
+ calculate_btn.click(
1409
+ fn=run_calculation,
1410
+ inputs=[
1411
+ birds,
1412
+ custom_birds,
1413
+ weeks,
1414
+ days,
1415
+ bag_size,
1416
+ custom_bag_size,
1417
+ bag_price,
1418
+ email,
1419
+ consent,
1420
+ ],
1421
+ outputs=[
1422
+ summary,
1423
+ benchmark,
1424
+ comparison,
1425
+ email,
1426
+ calculation_status,
1427
+ ],
1428
+ api_name="calculate_feed",
1429
+ )
1430
+
1431
+ # --------------------------------------------------------
1432
+ # ASK A QUESTION
1433
+ # --------------------------------------------------------
1434
+
1435
+ gr.Markdown(
1436
+ """
1437
+ ---
1438
+
1439
+ # ❓ Ask a question
1440
+
1441
+ ### What would you like to know about raising your birds?
1442
+
1443
+ Type your question or use the microphone.
1444
+
1445
+ Questions are automatically saved when you click
1446
+ **Get Answer**. This helps us understand what farmers
1447
+ want to know and improve future versions of the app.
1448
+ """
1449
+ )
1450
+
1451
+ question = gr.Textbox(
1452
+ label="Your question",
1453
+ placeholder=(
1454
+ "Example: How many bags of feed do I need "
1455
+ "for 100 broilers to 8 weeks?"
1456
+ ),
1457
+ lines=4,
1458
+ )
1459
+
1460
+ gr.Markdown(
1461
+ "**🎤 You can also speak your question:**"
1462
+ )
1463
+
1464
+ question_audio = gr.Audio(
1465
+ sources=["microphone"],
1466
+ type="filepath",
1467
+ label="Speak your question",
1468
+ )
1469
+
1470
+ def transcribe_question(
1471
+ audio,
1472
+ current_question,
1473
+ ):
1474
+
1475
+ if not audio:
1476
+ return current_question
1477
+
1478
+ try:
1479
+
1480
+ from openai import OpenAI
1481
+
1482
+ if not OPENAI_API_KEY:
1483
+ return current_question
1484
+
1485
+ client = OpenAI(
1486
+ api_key=OPENAI_API_KEY
1487
+ )
1488
+
1489
+ with open(
1490
+ audio,
1491
+ "rb"
1492
+ ) as audio_file:
1493
+
1494
+ transcription = (
1495
+ client.audio.transcriptions.create(
1496
+ model="gpt-4o-mini-transcribe",
1497
+ file=audio_file,
1498
+ )
1499
+ )
1500
+
1501
+ return transcription.text
1502
+
1503
+ except Exception:
1504
+
1505
+ return current_question
1506
+
1507
+ question_audio.stop_recording(
1508
+ fn=transcribe_question,
1509
+ inputs=[
1510
+ question_audio,
1511
+ question,
1512
+ ],
1513
+ outputs=question,
1514
+ )
1515
+
1516
  with gr.Row():
1517
+
1518
+ get_answer_btn = gr.Button(
1519
+ "🤖 Get Answer",
1520
+ variant="primary",
1521
+ size="lg",
1522
+ )
1523
+
1524
+ clear_question_btn = gr.Button(
1525
+ "Clear",
1526
+ variant="secondary",
1527
+ )
1528
+
1529
  question_answer = gr.Markdown()
1530
+
1531
  question_status = gr.Markdown()
1532
 
1533
+ get_answer_btn.click(
1534
+ fn=answer_farmer_question,
1535
+ inputs=[
1536
+ question,
1537
+ email,
1538
+ consent,
1539
+ birds,
1540
+ weeks,
1541
+ days,
1542
+ ],
1543
+ outputs=[
1544
+ question_answer,
1545
+ question_status,
1546
+ ],
1547
+ api_name="ask_farmer_question",
1548
+ )
1549
 
1550
+ clear_question_btn.click(
1551
+ fn=lambda: (
1552
+ "",
1553
+ "",
1554
+ "",
1555
+ ),
1556
+ inputs=None,
1557
+ outputs=[
1558
+ question,
1559
+ question_answer,
1560
+ question_status,
1561
+ ],
1562
+ )
1563
 
1564
+ # --------------------------------------------------------
1565
+ # ROSS BENCHMARK TABLE
1566
+ # --------------------------------------------------------
1567
 
1568
+ gr.Markdown(
1569
+ """
1570
+ ---
1571
 
1572
+ ## 📊 Ross 308 weekly benchmark
1573
+
1574
+ These figures are the numerical benchmark used by the
1575
+ calculator.
1576
+ """
1577
+ )
1578
+
1579
+ benchmark_display = ROSS_WEEKLY.copy()
1580
+
1581
+ benchmark_display[
1582
+ "Body Weight (kg/bird)"
1583
+ ] = benchmark_display[
1584
+ "Body Weight (kg/bird)"
1585
+ ].map(
1586
+ lambda x: f"{x:.3f}"
1587
+ )
1588
+
1589
+ benchmark_display[
1590
+ "Cumulative Feed (kg/bird)"
1591
+ ] = benchmark_display[
1592
+ "Cumulative Feed (kg/bird)"
1593
+ ].map(
1594
+ lambda x: f"{x:.3f}"
1595
+ )
1596
+
1597
+ benchmark_display[
1598
+ "Daily Intake (g/bird/day)"
1599
+ ] = benchmark_display[
1600
+ "Daily Intake (g/bird/day)"
1601
+ ].map(
1602
+ lambda x:
1603
+ "-"
1604
+ if pd.isna(x)
1605
+ else f"{int(x)}"
1606
+ )
1607
+
1608
+ benchmark_display[
1609
+ "FCR"
1610
+ ] = benchmark_display[
1611
+ "FCR"
1612
+ ].map(
1613
+ lambda x:
1614
+ "-"
1615
+ if pd.isna(x)
1616
+ else f"{x:.3f}"
1617
+ )
1618
+
1619
+ gr.Dataframe(
1620
+ value=benchmark_display,
1621
+ interactive=False,
1622
+ wrap=True,
1623
+ )
1624
+
1625
+ # --------------------------------------------------------
1626
+ # NIGERIA MANAGEMENT REFERENCE
1627
+ # --------------------------------------------------------
1628
+
1629
+ gr.Markdown(
1630
+ """
1631
+ ---
1632
+
1633
+ ## 🇳🇬 Nigeria management reference
1634
+
1635
+ ### 🌡️ Brooding
1636
+
1637
+ Start warming the brooding area 24–48 hours before
1638
+ chick arrival.
1639
+
1640
+ Initial chick-level temperature:
1641
+
1642
+ **31–33°C**
1643
+
1644
+ Temperature should be reduced progressively toward
1645
+ approximately **21°C by day 28**.
1646
+
1647
+ ### 💧 Water
1648
+
1649
+ Use clean, tested drinking water.
1650
+
1651
+ Reference pH:
1652
+
1653
+ **5.5–7.5**
1654
+
1655
+ Avoid supplying excessively warm water.
1656
+
1657
+ ### 🐔 Stocking density
1658
+
1659
+ A practical reference is approximately:
1660
+
1661
+ **25 kg live weight/m²**
1662
+
1663
+ at slaughter for hot Nigerian conditions.
1664
+
1665
+ Actual stocking density should take account of housing,
1666
+ ventilation and climate.
1667
+
1668
+ ---
1669
+
1670
+ ### ⚠️ Important
1671
+
1672
+ Ross performance objectives are used as the numerical
1673
+ benchmark.
1674
+
1675
+ Actual farm performance can differ because of genetics,
1676
+ sex, mortality, feed quality, temperature, management,
1677
+ water quality and other farm conditions.
1678
+
1679
+ This application is a planning and calculation tool.
1680
+ It is **not veterinary advice**.
1681
+ """
1682
  )
1683
+
1684
+ # --------------------------------------------------------
1685
+ # SOURCES
1686
+ # --------------------------------------------------------
1687
+
1688
+ gr.Markdown(
1689
+ """
1690
+ ---
1691
+
1692
+ ### 📚 References
1693
+
1694
+ **Numerical benchmark:**
1695
+ Aviagen — Ross 308 / Ross 308 FF Broiler Performance
1696
+ Objectives.
1697
+
1698
+ **Nigeria management reference:**
1699
+ Agrited — *Everything You Need To Know About Raising
1700
+ Excellent Broiler Chickens in Nigeria*.
1701
+
1702
+ The Ross performance objectives themselves note that
1703
+ actual performance may be lower because of local factors
1704
+ such as raw-material availability, climate and production
1705
+ conditions. :contentReference[oaicite:2]{index=2}
1706
+ """
1707
  )
1708
 
1709
+
1710
+ # ============================================================
1711
+ # MOUNT GRADIO
1712
+ # ============================================================
1713
+
1714
+ fastapi_app = gr.mount_gradio_app(
1715
+ fastapi_app,
1716
+ demo,
1717
+ path="/",
1718
+ )
1719
+
1720
+
1721
+ # ============================================================
1722
+ # START
1723
+ # ============================================================
1724
+
1725
  if __name__ == "__main__":
1726
+
1727
+ import uvicorn
1728
+
1729
+ port = int(
1730
+ os.getenv(
1731
+ "PORT",
1732
+ "7860"
1733
+ )
1734
+ )
1735
+
1736
+ uvicorn.run(
1737
+ fastapi_app,
1738
+ host="0.0.0.0",
1739
+ port=port,
1740
+ )