NTEIGBANAM OKE commited on
Commit
fe3b74d
Β·
verified Β·
1 Parent(s): aa93869

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -69
app.py CHANGED
@@ -132,7 +132,6 @@ def get_benchmark_table(breed):
132
  for day in days:
133
  weight = weight_data.get(day, 0)
134
  feed = feed_data.get(day, 0)
135
- # Calculate FCR = feed / weight
136
  fcr = feed / weight if weight > 0 else 0
137
  table_data.append([day, f"{weight:.3f}", f"{feed:.3f}", f"{fcr:.3f}"])
138
 
@@ -162,7 +161,7 @@ def get_breed_comparison_table():
162
 
163
 
164
  # ============================================================
165
- # CURRENCY
166
  # ============================================================
167
 
168
  CURRENCIES = {
@@ -181,14 +180,44 @@ CURRENCIES = {
181
  "GB": ("United Kingdom", "Β£", "GBP"),
182
  "CA": ("Canada", "C$", "CAD"),
183
  "AU": ("Australia", "A$", "AUD"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  }
185
 
186
 
187
- def detect_country():
 
188
  candidates = [
189
  os.environ.get("COUNTRY_CODE"),
190
  os.environ.get("CF-IPCOUNTRY"),
191
  os.environ.get("GEOIP_COUNTRY"),
 
192
  ]
193
 
194
  for value in candidates:
@@ -197,12 +226,23 @@ def detect_country():
197
  if value in CURRENCIES:
198
  return value
199
 
200
- return "NG"
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
 
203
- def currency_for_country(country_code):
204
- data = CURRENCIES.get(country_code, CURRENCIES["NG"])
205
- return data[1]
206
 
207
 
208
  # ============================================================
@@ -345,30 +385,28 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
345
  bag_size = float(bag_size)
346
  price_per_bag = float(price_per_bag)
347
  except Exception:
348
- return "⚠️ Please enter valid numbers."
349
 
350
  if birds <= 0:
351
- return "⚠️ Number of birds must be greater than zero."
352
  if weeks < 0:
353
- return "⚠️ Weeks cannot be negative."
354
  if days < 0 or days > 6:
355
- return "⚠️ Days must be between 0 and 6."
356
  if bag_size <= 0:
357
- return "⚠️ Feed bag size must be greater than zero."
358
  if price_per_bag < 0:
359
- return "⚠️ Price per bag cannot be negative."
360
 
361
  if not valid_email(email):
362
- return "πŸ“§ **Email required**\n\nPlease enter your email address before calculating."
363
 
364
  # Country / Currency
365
- country_code = country_code or "NG"
366
- if country_code not in CURRENCIES:
367
- country_code = "NG"
368
- currency = currency_for_country(country_code)
369
 
370
  # Save lead with breed
371
- save_lead(email, country_code, currency, breed)
372
 
373
  # Total days
374
  total_days = (weeks * 7) + days
@@ -395,7 +433,7 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
395
  flock_weight = expected_weight * birds
396
 
397
  # Save calculation
398
- save_calculation(email, country_code, currency, breed, birds, weeks, days, total_days,
399
  bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
400
  starter_bags, finisher_bags, total_bags, rounded_bags, total_cost)
401
 
@@ -416,14 +454,15 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
416
 
417
  <div style="background: #f0fdf4; padding: 16px 20px; border-radius: 12px; border-left: 5px solid #22c55e; margin-bottom: 20px;">
418
  <div style="font-size: 14px; color: #16a34a; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">🎯 Quick Answer</div>
419
- <div style="font-size: 22px; font-weight: 700; color: #166534;">
420
- {rounded_bags} bags of {bag_size:g} kg feed
421
  </div>
422
  <div style="color: #4b5563; margin-top: 4px;">
423
  To raise <strong>{birds:,} birds</strong> for <strong>{age_text} ({total_days} days)</strong>
424
  </div>
425
  <div style="margin-top: 6px; font-size: 14px;">
426
  <span style="background: {breed_color}; color: white; padding: 2px 10px; border-radius: 12px; font-weight: 600;">{breed}</span>
 
427
  </div>
428
  </div>
429
 
@@ -451,10 +490,10 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
451
  <div style="margin-bottom: 16px;">
452
  <div style="font-size: 14px; color: #6b7280; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">πŸ’° Feed Cost</div>
453
  <div style="font-size: 28px; font-weight: 800; color: #1e40af;">
454
- {currency}{total_cost:,.0f}
455
  </div>
456
  <div style="color: #6b7280; font-size: 14px;">
457
- {rounded_bags} bags Γ— {currency}{price_per_bag:,.0f} per bag
458
  </div>
459
  </div>
460
 
@@ -478,7 +517,7 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
478
  </div>
479
  """
480
 
481
- return html
482
 
483
 
484
  # ============================================================
@@ -561,19 +600,6 @@ We can use the questions farmers submit to decide which answers, calculators and
561
  return answer
562
 
563
 
564
- # ============================================================
565
- # COUNTRY / CURRENCY UI
566
- # ============================================================
567
-
568
- def get_country_info():
569
- country = detect_country()
570
- currency = currency_for_country(country)
571
- return country, currency
572
-
573
-
574
- DEFAULT_COUNTRY, DEFAULT_CURRENCY = get_country_info()
575
-
576
-
577
  # ============================================================
578
  # UPDATE BENCHMARK TABLE
579
  # ============================================================
@@ -584,6 +610,19 @@ def update_benchmark(breed):
584
  return table_data
585
 
586
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587
  # ============================================================
588
  # CSS
589
  # ============================================================
@@ -604,7 +643,7 @@ button { min-height: 48px !important; }
604
  # UI
605
  # ============================================================
606
 
607
- with gr.Blocks(title=APP_NAME, css=CSS) as demo:
608
 
609
  gr.HTML("""
610
  <div class="main-title">
@@ -655,7 +694,33 @@ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
655
  label="+ Days",
656
  )
657
 
658
- gr.Markdown("## 🌾 3. Feed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
659
 
660
  with gr.Row():
661
  bag_size = gr.Dropdown(
@@ -665,11 +730,11 @@ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
665
  )
666
  price = gr.Number(
667
  value=24000,
668
- label=f"Price per bag ({DEFAULT_CURRENCY})",
669
  minimum=0,
670
  )
671
 
672
- gr.Markdown("## πŸ“§ 4. Your email")
673
 
674
  email = gr.Textbox(
675
  label="",
@@ -684,7 +749,7 @@ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
684
  size="lg",
685
  )
686
 
687
- country_state = gr.State(DEFAULT_COUNTRY)
688
 
689
  # RIGHT COLUMN: RESULTS
690
  with gr.Column(scale=1, min_width=350):
@@ -712,7 +777,6 @@ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
712
  with gr.TabItem("πŸ“Š Selected Breed Benchmark"):
713
  gr.Markdown("### πŸ“Š Weekly Benchmark for Selected Breed")
714
 
715
- # Get initial benchmark table
716
  initial_table, _ = get_benchmark_table("Ross 308")
717
 
718
  benchmark_table = gr.Dataframe(
@@ -725,13 +789,13 @@ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
725
  with gr.TabItem("πŸ“ˆ Breed Comparison"):
726
  gr.Markdown("### πŸ“Š Breed Comparison (As-Hatched Performance)")
727
 
728
- comp_data, breeds, days = get_breed_comparison_table()
729
 
730
  headers = ["Days"]
731
- for breed in breeds:
732
- headers.append(f"{breed} Weight (kg)")
733
- headers.append(f"{breed} Feed (kg)")
734
- headers.append(f"{breed} FCR")
735
 
736
  comparison_table = gr.Dataframe(
737
  value=comp_data,
@@ -789,6 +853,28 @@ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
789
  *All data from official breed performance objectives.*
790
  """)
791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792
  # ============================================================
793
  # EVENTS
794
  # ============================================================
@@ -796,27 +882,26 @@ with gr.Blocks(title=APP_NAME, css=CSS) as demo:
796
  # Update benchmark table when breed changes
797
  breed.change(
798
  fn=update_benchmark,
799
- inputs=breed,
800
- outputs=benchmark_table,
801
  )
802
 
803
- calculate_btn.click(
804
- fn=calculate_feed,
805
- inputs=[birds, weeks, days, bag_size, price, email, country_state, breed],
806
- outputs=result,
 
 
 
 
 
 
 
 
 
 
 
807
  )
808
 
809
- ask_btn.click(
810
- fn=answer_farmer_question,
811
- inputs=[question, email, breed],
812
- outputs=question_answer,
813
- )
814
-
815
-
816
- # ============================================================
817
- # START APP
818
- # ============================================================
819
-
820
- if __name__ == "__main__":
821
- port = int(os.environ.get("PORT", "7860"))
822
- demo.launch(server_name="0.0.0.0", server_port=port, root_path="/")
 
132
  for day in days:
133
  weight = weight_data.get(day, 0)
134
  feed = feed_data.get(day, 0)
 
135
  fcr = feed / weight if weight > 0 else 0
136
  table_data.append([day, f"{weight:.3f}", f"{feed:.3f}", f"{fcr:.3f}"])
137
 
 
161
 
162
 
163
  # ============================================================
164
+ # CURRENCY DATA
165
  # ============================================================
166
 
167
  CURRENCIES = {
 
180
  "GB": ("United Kingdom", "Β£", "GBP"),
181
  "CA": ("Canada", "C$", "CAD"),
182
  "AU": ("Australia", "A$", "AUD"),
183
+ "IN": ("India", "β‚Ή", "INR"),
184
+ "PK": ("Pakistan", "₨", "PKR"),
185
+ "BD": ("Bangladesh", "ΰ§³", "BDT"),
186
+ "BR": ("Brazil", "R$", "BRL"),
187
+ }
188
+
189
+ # Default feed prices per currency (approximate)
190
+ DEFAULT_PRICES = {
191
+ "NGN": 24000,
192
+ "GHS": 300,
193
+ "KES": 2200,
194
+ "UGX": 100000,
195
+ "TZS": 30000,
196
+ "ZAR": 300,
197
+ "ZMW": 350,
198
+ "USD": 25,
199
+ "GBP": 20,
200
+ "EUR": 23,
201
+ "INR": 2200,
202
+ "PKR": 7000,
203
+ "BDT": 2500,
204
+ "AUD": 35,
205
+ "CAD": 35,
206
+ "NZD": 40,
207
+ "BRL": 130,
208
+ "XAF": 15000,
209
+ "XOF": 15000,
210
+ "ZWG": 350,
211
  }
212
 
213
 
214
+ def detect_country_from_env():
215
+ """Best-effort country detection from environment variables."""
216
  candidates = [
217
  os.environ.get("COUNTRY_CODE"),
218
  os.environ.get("CF-IPCOUNTRY"),
219
  os.environ.get("GEOIP_COUNTRY"),
220
+ os.environ.get("HTTP_CF_IPCOUNTRY"),
221
  ]
222
 
223
  for value in candidates:
 
226
  if value in CURRENCIES:
227
  return value
228
 
229
+ return None
230
+
231
+
232
+ def get_country_info(country_code):
233
+ """Get currency info for a country code."""
234
+ if country_code in CURRENCIES:
235
+ name, symbol, code = CURRENCIES[country_code]
236
+ return country_code, symbol, code
237
+ return "NG", "₦", "NGN"
238
+
239
+
240
+ def get_default_price(currency_code):
241
+ return DEFAULT_PRICES.get(currency_code, 24000)
242
 
243
 
244
+ # Country list for dropdown
245
+ COUNTRY_LIST = sorted([(code, f"{name} ({symbol})") for code, (name, symbol, curr) in CURRENCIES.items()])
 
246
 
247
 
248
  # ============================================================
 
385
  bag_size = float(bag_size)
386
  price_per_bag = float(price_per_bag)
387
  except Exception:
388
+ return "⚠️ Please enter valid numbers.", ""
389
 
390
  if birds <= 0:
391
+ return "⚠️ Number of birds must be greater than zero.", ""
392
  if weeks < 0:
393
+ return "⚠️ Weeks cannot be negative.", ""
394
  if days < 0 or days > 6:
395
+ return "⚠️ Days must be between 0 and 6.", ""
396
  if bag_size <= 0:
397
+ return "⚠️ Feed bag size must be greater than zero.", ""
398
  if price_per_bag < 0:
399
+ return "⚠️ Price per bag cannot be negative.", ""
400
 
401
  if not valid_email(email):
402
+ return "πŸ“§ **Email required**\n\nPlease enter your email address before calculating.", ""
403
 
404
  # Country / Currency
405
+ country_name, symbol, currency_code = get_country_info(country_code)
406
+ currency_symbol = symbol
 
 
407
 
408
  # Save lead with breed
409
+ save_lead(email, country_code, currency_code, breed)
410
 
411
  # Total days
412
  total_days = (weeks * 7) + days
 
433
  flock_weight = expected_weight * birds
434
 
435
  # Save calculation
436
+ save_calculation(email, country_code, currency_code, breed, birds, weeks, days, total_days,
437
  bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
438
  starter_bags, finisher_bags, total_bags, rounded_bags, total_cost)
439
 
 
454
 
455
  <div style="background: #f0fdf4; padding: 16px 20px; border-radius: 12px; border-left: 5px solid #22c55e; margin-bottom: 20px;">
456
  <div style="font-size: 14px; color: #16a34a; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">🎯 Quick Answer</div>
457
+ <div style="font-size: 24px; font-weight: 700; color: #166534;">
458
+ You will need approximately <span style="font-size: 28px;">{rounded_bags}</span> bags of <span style="font-size: 28px;">{bag_size:g} kg</span> feed
459
  </div>
460
  <div style="color: #4b5563; margin-top: 4px;">
461
  To raise <strong>{birds:,} birds</strong> for <strong>{age_text} ({total_days} days)</strong>
462
  </div>
463
  <div style="margin-top: 6px; font-size: 14px;">
464
  <span style="background: {breed_color}; color: white; padding: 2px 10px; border-radius: 12px; font-weight: 600;">{breed}</span>
465
+ <span style="background: #6b7280; color: white; padding: 2px 10px; border-radius: 12px; font-weight: 600; margin-left: 6px;">{country_name}</span>
466
  </div>
467
  </div>
468
 
 
490
  <div style="margin-bottom: 16px;">
491
  <div style="font-size: 14px; color: #6b7280; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">πŸ’° Feed Cost</div>
492
  <div style="font-size: 28px; font-weight: 800; color: #1e40af;">
493
+ {currency_symbol}{total_cost:,.0f}
494
  </div>
495
  <div style="color: #6b7280; font-size: 14px;">
496
+ {rounded_bags} bags Γ— {currency_symbol}{price_per_bag:,.0f} per bag
497
  </div>
498
  </div>
499
 
 
517
  </div>
518
  """
519
 
520
+ return html, f"βœ… Calculation saved for {email.strip().lower()}."
521
 
522
 
523
  # ============================================================
 
600
  return answer
601
 
602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603
  # ============================================================
604
  # UPDATE BENCHMARK TABLE
605
  # ============================================================
 
610
  return table_data
611
 
612
 
613
+ def update_price(country_code):
614
+ """Update default price when country changes."""
615
+ _, _, currency_code = get_country_info(country_code)
616
+ default_price = get_default_price(currency_code)
617
+ return default_price
618
+
619
+
620
+ def update_currency(country_code):
621
+ """Update currency symbol when country changes."""
622
+ _, symbol, _ = get_country_info(country_code)
623
+ return symbol
624
+
625
+
626
  # ============================================================
627
  # CSS
628
  # ============================================================
 
643
  # UI
644
  # ============================================================
645
 
646
+ with gr.Blocks(title=APP_NAME) as demo:
647
 
648
  gr.HTML("""
649
  <div class="main-title">
 
694
  label="+ Days",
695
  )
696
 
697
+ gr.Markdown("## 🌍 3. Country & Currency")
698
+
699
+ # Auto-detect country
700
+ detected_country = detect_country_from_env() or "NG"
701
+
702
+ # Country dropdown with auto-detect label
703
+ country_choices = ["Auto-Detect"] + [f"{code}" for code, _ in COUNTRY_LIST]
704
+
705
+ country_dropdown = gr.Dropdown(
706
+ choices=country_choices,
707
+ value="Auto-Detect",
708
+ label="Country (select manually or use Auto-Detect)",
709
+ info="Auto-Detect uses your IP location. Select manually if detection fails.",
710
+ )
711
+
712
+ # Hidden state for actual country code
713
+ country_code_state = gr.State(detected_country)
714
+
715
+ # Currency symbol display
716
+ currency_display = gr.Textbox(
717
+ value="₦",
718
+ label="Currency Symbol",
719
+ interactive=False,
720
+ visible=False,
721
+ )
722
+
723
+ gr.Markdown("## 🌾 4. Feed")
724
 
725
  with gr.Row():
726
  bag_size = gr.Dropdown(
 
730
  )
731
  price = gr.Number(
732
  value=24000,
733
+ label=f"Price per bag (₦)",
734
  minimum=0,
735
  )
736
 
737
+ gr.Markdown("## πŸ“§ 5. Your email")
738
 
739
  email = gr.Textbox(
740
  label="",
 
749
  size="lg",
750
  )
751
 
752
+ save_status = gr.Markdown("")
753
 
754
  # RIGHT COLUMN: RESULTS
755
  with gr.Column(scale=1, min_width=350):
 
777
  with gr.TabItem("πŸ“Š Selected Breed Benchmark"):
778
  gr.Markdown("### πŸ“Š Weekly Benchmark for Selected Breed")
779
 
 
780
  initial_table, _ = get_benchmark_table("Ross 308")
781
 
782
  benchmark_table = gr.Dataframe(
 
789
  with gr.TabItem("πŸ“ˆ Breed Comparison"):
790
  gr.Markdown("### πŸ“Š Breed Comparison (As-Hatched Performance)")
791
 
792
+ comp_data, breeds_list, days_list = get_breed_comparison_table()
793
 
794
  headers = ["Days"]
795
+ for b in breeds_list:
796
+ headers.append(f"{b} Weight (kg)")
797
+ headers.append(f"{b} Feed (kg)")
798
+ headers.append(f"{b} FCR")
799
 
800
  comparison_table = gr.Dataframe(
801
  value=comp_data,
 
853
  *All data from official breed performance objectives.*
854
  """)
855
 
856
+ # ============================================================
857
+ # QUESTION SECTION
858
+ # ============================================================
859
+
860
+ gr.Markdown("---")
861
+
862
+ with gr.Row():
863
+ with gr.Column(scale=2):
864
+ gr.Markdown("""
865
+ # ❓ Ask a question
866
+ ### What would you like to know about raising your birds?
867
+ """)
868
+
869
+ question = gr.Textbox(
870
+ label="",
871
+ placeholder="Type or speak your question...",
872
+ lines=3,
873
+ )
874
+
875
+ ask_btn = gr.Button("πŸ’¬ Get Answer", variant="secondary", size="lg")
876
+ question_answer = gr.Markdown("")
877
+
878
  # ============================================================
879
  # EVENTS
880
  # ============================================================
 
882
  # Update benchmark table when breed changes
883
  breed.change(
884
  fn=update_benchmark,
885
+ inputs=[breed],
886
+ outputs=[benchmark_table],
887
  )
888
 
889
+ # Update price and currency when country changes
890
+ def on_country_change(country_selection):
891
+ if country_selection == "Auto-Detect":
892
+ country_code = detect_country_from_env() or "NG"
893
+ else:
894
+ country_code = country_selection
895
+
896
+ _, symbol, currency_code = get_country_info(country_code)
897
+ default_price = get_default_price(currency_code)
898
+ return country_code, default_price, symbol, f"Price per bag ({symbol})"
899
+
900
+ country_dropdown.change(
901
+ fn=on_country_change,
902
+ inputs=[country_dropdown],
903
+ outputs=[country_code_state, price, currency_display, price],
904
  )
905
 
906
+ # Calculate button
907
+ def