NTEIGBANAM OKE commited on
Commit
2f640b2
·
verified ·
1 Parent(s): 687e783

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -235
app.py CHANGED
@@ -2,6 +2,7 @@ import os
2
  import math
3
  import re
4
  import sqlite3
 
5
  from datetime import datetime
6
  from pathlib import Path
7
 
@@ -12,8 +13,13 @@ import gradio as gr
12
  # APP CONFIG
13
  # ============================================================
14
 
15
- APP_NAME = "Poultry Feed Calculator"
16
- DB_PATH = os.environ.get("DATABASE_PATH", "poultry_calculator.db")
 
 
 
 
 
17
 
18
  STARTER_END_DAY = 21
19
 
@@ -186,28 +192,12 @@ CURRENCIES = {
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
 
@@ -241,7 +231,6 @@ 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
 
@@ -299,8 +288,21 @@ def init_db():
299
  )
300
  """)
301
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  conn.commit()
303
  conn.close()
 
304
 
305
 
306
  init_db()
@@ -372,11 +374,99 @@ def save_calculation(email, country, currency, breed, birds, weeks, days, total_
372
  conn.close()
373
 
374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  # ============================================================
376
  # FEED CALCULATION
377
  # ============================================================
378
 
379
- def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_code, breed):
380
  # Validation
381
  try:
382
  birds = int(birds)
@@ -408,6 +498,9 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
408
  # Save lead with breed
409
  save_lead(email, country_code, currency_code, breed)
410
 
 
 
 
411
  # Total days
412
  total_days = (weeks * 7) + days
413
 
@@ -450,25 +543,25 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
450
  age_text += f" + {days} day{'s' if days != 1 else ''}"
451
 
452
  html = f"""
453
- <div style="font-size: 18px; line-height: 1.6;">
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
 
469
  <div style="margin-bottom: 16px;">
470
- <div style="font-size: 14px; color: #6b7280; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">🌾 Feed Breakdown</div>
471
- <table style="width: 100%; border-collapse: collapse; margin-top: 6px;">
472
  <tr style="border-bottom: 1px solid #e5e7eb;">
473
  <td style="padding: 8px 4px;"><strong>🌱 Starter</strong></td>
474
  <td style="padding: 8px 4px; text-align: right;">{starter_kg:,.1f} kg</td>
@@ -487,9 +580,9 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
487
  </table>
488
  </div>
489
 
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;">
@@ -498,8 +591,8 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
498
  </div>
499
 
500
  <div style="border-top: 1px solid #e5e7eb; padding-top: 14px;">
501
- <div style="font-size: 14px; color: #6b7280; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">📊 Expected Performance</div>
502
- <table style="width: 100%; border-collapse: collapse; margin-top: 6px;">
503
  <tr style="border-bottom: 1px solid #e5e7eb;">
504
  <td style="padding: 6px 4px;">Body weight / bird</td>
505
  <td style="padding: 6px 4px; text-align: right; font-weight: 600;">{expected_weight:.3f} kg</td>
@@ -512,7 +605,7 @@ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_c
512
  </div>
513
 
514
  <div style="margin-top: 14px; font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 10px;">
515
- Estimate based on {breed} benchmark. Actual results may vary.
516
  </div>
517
  </div>
518
  """
@@ -610,7 +703,7 @@ def update_benchmark(breed):
610
  return table_data
611
 
612
 
613
- def on_country_change(country_selection):
614
  """Update price and currency when country changes."""
615
  if country_selection == "Auto-Detect":
616
  country_code = detect_country_from_env() or "NG"
@@ -619,7 +712,38 @@ def on_country_change(country_selection):
619
 
620
  _, symbol, currency_code = get_country_info(country_code)
621
  default_price = get_default_price(currency_code)
622
- return country_code, default_price, symbol, f"Price per bag ({symbol})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
 
624
 
625
  # ============================================================
@@ -646,28 +770,22 @@ with gr.Blocks(title=APP_NAME) as demo:
646
 
647
  gr.HTML("""
648
  <div class="main-title">
649
- <h1>🐔 Poultry Feed Calculator</h1>
650
- <p>Know exactly how much feed you need before buying.</p>
651
  </div>
652
  """)
653
 
654
- # Breed Info Banner
655
- gr.Markdown("""
656
- ### 🐔 Select your breed
657
- **Ross 308** — Fastest growth, big chest | **Cobb 500** — Good early growth | **Arbor Acres** — Hardy & adaptable
658
- """)
659
-
660
  with gr.Row(equal_height=True):
661
 
662
  # LEFT COLUMN: INPUTS
663
  with gr.Column(scale=1, min_width=350):
664
 
665
  with gr.Group():
666
- gr.Markdown("## 🐔 1. Breed & Number of birds")
667
 
668
  breed = gr.Dropdown(
669
  choices=["Ross 308", "Cobb 500", "Arbor Acres"],
670
- value="Ross 308",
671
  label="Breed",
672
  info="Select your broiler breed for accurate estimates",
673
  )
@@ -684,7 +802,7 @@ with gr.Blocks(title=APP_NAME) as demo:
684
  with gr.Row():
685
  weeks = gr.Dropdown(
686
  choices=list(range(0, 21)),
687
- value=6,
688
  label="Weeks",
689
  )
690
  days = gr.Dropdown(
@@ -693,25 +811,7 @@ with gr.Blocks(title=APP_NAME) as demo:
693
  label="+ Days",
694
  )
695
 
696
- gr.Markdown("## 🌍 3. Country & Currency")
697
-
698
- # Auto-detect country
699
- detected_country = detect_country_from_env() or "NG"
700
-
701
- # Country dropdown with auto-detect label
702
- country_choices = ["Auto-Detect"] + [code for code, _ in COUNTRY_LIST]
703
-
704
- country_dropdown = gr.Dropdown(
705
- choices=country_choices,
706
- value="Auto-Detect",
707
- label="Country (select manually or use Auto-Detect)",
708
- info="Auto-Detect uses your IP location. Select manually if detection fails.",
709
- )
710
-
711
- # Hidden state for actual country code
712
- country_code_state = gr.State(detected_country)
713
-
714
- gr.Markdown("## 🌾 4. Feed")
715
 
716
  with gr.Row():
717
  bag_size = gr.Dropdown(
@@ -725,6 +825,19 @@ with gr.Blocks(title=APP_NAME) as demo:
725
  minimum=0,
726
  )
727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728
  gr.Markdown("## 📧 5. Your email")
729
 
730
  email = gr.Textbox(
@@ -732,10 +845,11 @@ with gr.Blocks(title=APP_NAME) as demo:
732
  placeholder="farmer@example.com",
733
  type="email",
734
  elem_classes=["email-box"],
 
735
  )
736
 
737
  calculate_btn = gr.Button(
738
- "🐔 Calculate",
739
  variant="primary",
740
  size="lg",
741
  )
@@ -759,164 +873,7 @@ with gr.Blocks(title=APP_NAME) as demo:
759
  )
760
 
761
  # ============================================================
762
- # BENCHMARK SECTION - Dynamic Tables
763
- # ============================================================
764
-
765
- gr.Markdown("---")
766
-
767
- with gr.Tabs():
768
- with gr.TabItem("📊 Selected Breed Benchmark"):
769
- gr.Markdown("### 📊 Weekly Benchmark for Selected Breed")
770
-
771
- initial_table, _ = get_benchmark_table("Ross 308")
772
-
773
- benchmark_table = gr.Dataframe(
774
- value=initial_table,
775
- headers=["Days", "Body Weight (kg)", "Cumulative Feed (kg)", "FCR"],
776
- interactive=False,
777
- wrap=True,
778
- )
779
-
780
- with gr.TabItem("📈 Breed Comparison"):
781
- gr.Markdown("### 📊 Breed Comparison (As-Hatched Performance)")
782
-
783
- comp_data, breeds_list, days_list = get_breed_comparison_table()
784
-
785
- headers = ["Days"]
786
- for b in breeds_list:
787
- headers.append(f"{b} Weight (kg)")
788
- headers.append(f"{b} Feed (kg)")
789
- headers.append(f"{b} FCR")
790
-
791
- comparison_table = gr.Dataframe(
792
- value=comp_data,
793
- headers=headers,
794
- interactive=False,
795
- wrap=True,
796
- )
797
-
798
- # ============================================================
799
- # BREED REFERENCE
800
- # ============================================================
801
-
802
- gr.Markdown("---")
803
-
804
- gr.Markdown("""
805
- ### 🐔 Common Broiler Breeds in Nigeria
806
-
807
- | Breed | Characteristics | Available At |
808
- |-------|-----------------|--------------|
809
- | **Ross 308** | Big chest, thick legs, very fast growth | Agrited, Sayed, Valentine |
810
- | **Cobb 500** | Good early growth, strong legs | Chikun, Zartech |
811
- | **Arbor Acres** | Balanced growth, hardy, adaptable | Supreme, CHI, GS, Vertex, Fidan, Cascada, Orobor, Sunchi, Farm Support, Ajila |
812
-
813
- 💡 **Tip:** Before buying chicks, ask about the breed and hatchery. Not all broilers are the same!
814
- """)
815
-
816
- # ============================================================
817
- # HOW IT WORKS
818
- # ============================================================
819
-
820
- gr.Markdown("---")
821
-
822
- with gr.Row():
823
- with gr.Column(scale=1):
824
- gr.Markdown("""
825
- ### 📌 How it works
826
-
827
- - **Weeks + Days** → total days
828
- - **Starter** → Day 0–21
829
- - **Finisher** → Day 22+
830
- - **Bags** → rounded up to next whole bag
831
- - **Breed-specific benchmarks** used for estimates
832
-
833
- ⚠️ Actual results may vary with management, feed quality, and other conditions.
834
- """)
835
-
836
- with gr.Column(scale=1):
837
- gr.Markdown("""
838
- ### 📊 Data Sources
839
-
840
- - **Ross 308** — Aviagen (2022)
841
- - **Cobb 500** — Cobb-Vantress
842
- - **Arbor Acres** — Aviagen (2022)
843
-
844
- *All data from official breed performance objectives.*
845
- """)
846
-
847
- # ============================================================
848
- # QUESTION SECTION
849
- # ============================================================
850
-
851
- gr.Markdown("---")
852
-
853
- with gr.Row():
854
- with gr.Column(scale=2):
855
- gr.Markdown("""
856
- # ❓ Ask a question
857
- ### What would you like to know about raising your birds?
858
- """)
859
-
860
- question = gr.Textbox(
861
- label="",
862
- placeholder="Type or speak your question...",
863
- lines=3,
864
- )
865
-
866
- ask_btn = gr.Button("💬 Get Answer", variant="secondary", size="lg")
867
- question_answer = gr.Markdown("")
868
-
869
- # ============================================================
870
- # EVENTS
871
  # ============================================================
872
 
873
- # Update benchmark table when breed changes
874
- breed.change(
875
- fn=update_benchmark,
876
- inputs=[breed],
877
- outputs=[benchmark_table],
878
- )
879
-
880
- # Update price and currency when country changes
881
- def on_country_change_handler(country_selection):
882
- if country_selection == "Auto-Detect":
883
- country_code = detect_country_from_env() or "NG"
884
- else:
885
- country_code = country_selection
886
-
887
- _, symbol, currency_code = get_country_info(country_code)
888
- default_price = get_default_price(currency_code)
889
- return country_code, default_price, symbol
890
-
891
- country_dropdown.change(
892
- fn=on_country_change_handler,
893
- inputs=[country_dropdown],
894
- outputs=[country_code_state, price, price],
895
- )
896
-
897
- # Calculate button
898
- def calculate_wrapper(birds, weeks, days, bag_size, price_per_bag, email, country_code_state, breed):
899
- if not country_code_state:
900
- country_code_state = "NG"
901
- return calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_code_state, breed)
902
-
903
- calculate_btn.click(
904
- fn=calculate_wrapper,
905
- inputs=[birds, weeks, days, bag_size, price, email, country_code_state, breed],
906
- outputs=[result, save_status],
907
- )
908
-
909
- ask_btn.click(
910
- fn=answer_farmer_question,
911
- inputs=[question, email, breed],
912
- outputs=[question_answer],
913
- )
914
-
915
-
916
- # ============================================================
917
- # START APP
918
- # ============================================================
919
-
920
- if __name__ == "__main__":
921
- port = int(os.environ.get("PORT", "7860"))
922
- demo.launch(server_name="0.0.0.0", server_port=port, root_path="/")
 
2
  import math
3
  import re
4
  import sqlite3
5
+ import json
6
  from datetime import datetime
7
  from pathlib import Path
8
 
 
13
  # APP CONFIG
14
  # ============================================================
15
 
16
+ APP_NAME = "🐔 PoultryFeedCalc"
17
+ DB_PATH = os.environ.get("DATABASE_PATH", "/data/poultryfeedcalc.db")
18
+
19
+ # Create directory if it doesn't exist
20
+ db_dir = os.path.dirname(DB_PATH)
21
+ if db_dir and not os.path.exists(db_dir):
22
+ os.makedirs(db_dir, exist_ok=True)
23
 
24
  STARTER_END_DAY = 21
25
 
 
192
  "BR": ("Brazil", "R$", "BRL"),
193
  }
194
 
 
195
  DEFAULT_PRICES = {
196
+ "NGN": 24000, "GHS": 300, "KES": 2200, "UGX": 100000,
197
+ "TZS": 30000, "ZAR": 300, "ZMW": 350, "USD": 25,
198
+ "GBP": 20, "EUR": 23, "INR": 2200, "PKR": 7000,
199
+ "BDT": 2500, "AUD": 35, "CAD": 35, "NZD": 40,
200
+ "BRL": 130, "XAF": 15000, "XOF": 15000, "ZWG": 350,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  }
202
 
203
 
 
231
  return DEFAULT_PRICES.get(currency_code, 24000)
232
 
233
 
 
234
  COUNTRY_LIST = sorted([(code, f"{name} ({symbol})") for code, (name, symbol, curr) in CURRENCIES.items()])
235
 
236
 
 
288
  )
289
  """)
290
 
291
+ cur.execute("""
292
+ CREATE TABLE IF NOT EXISTS analytics (
293
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
294
+ visit_date TEXT,
295
+ ip TEXT,
296
+ country TEXT,
297
+ breed TEXT,
298
+ action TEXT,
299
+ created_at TEXT
300
+ )
301
+ """)
302
+
303
  conn.commit()
304
  conn.close()
305
+ print(f"✅ Database initialized at: {DB_PATH}")
306
 
307
 
308
  init_db()
 
374
  conn.close()
375
 
376
 
377
+ def track_visit(request: gr.Request):
378
+ """Track page visit."""
379
+ try:
380
+ client_ip = request.client.host if request and hasattr(request, 'client') else "unknown"
381
+
382
+ conn = sqlite3.connect(DB_PATH)
383
+ cur = conn.cursor()
384
+
385
+ cur.execute("""
386
+ INSERT INTO analytics (visit_date, ip, country, action, created_at)
387
+ VALUES (?, ?, ?, ?, ?)
388
+ """, (
389
+ datetime.now().strftime("%Y-%m-%d"),
390
+ client_ip,
391
+ detect_country_from_env() or "NG",
392
+ "page_visit",
393
+ datetime.now().isoformat()
394
+ ))
395
+
396
+ conn.commit()
397
+ conn.close()
398
+ return True
399
+ except Exception as e:
400
+ print(f"Analytics error: {e}")
401
+ return False
402
+
403
+
404
+ def track_calculation(breed, birds, days):
405
+ """Track when a calculation is performed."""
406
+ try:
407
+ conn = sqlite3.connect(DB_PATH)
408
+ cur = conn.cursor()
409
+
410
+ cur.execute("""
411
+ INSERT INTO analytics (visit_date, country, breed, action, created_at)
412
+ VALUES (?, ?, ?, ?, ?)
413
+ """, (
414
+ datetime.now().strftime("%Y-%m-%d"),
415
+ detect_country_from_env() or "NG",
416
+ breed,
417
+ f"calculation_{birds}_{days}",
418
+ datetime.now().isoformat()
419
+ ))
420
+
421
+ conn.commit()
422
+ conn.close()
423
+ return True
424
+ except:
425
+ return False
426
+
427
+
428
+ def get_analytics_summary():
429
+ """Get analytics summary."""
430
+ conn = sqlite3.connect(DB_PATH)
431
+ cur = conn.cursor()
432
+
433
+ cur.execute("SELECT COUNT(*) FROM analytics WHERE action = 'page_visit'")
434
+ total_visits = cur.fetchone()[0] or 0
435
+
436
+ cur.execute("SELECT COUNT(*) FROM analytics WHERE action = 'page_visit' AND visit_date = ?",
437
+ (datetime.now().strftime("%Y-%m-%d"),))
438
+ today_visits = cur.fetchone()[0] or 0
439
+
440
+ cur.execute("SELECT COUNT(*) FROM analytics WHERE action LIKE 'calculation_%'")
441
+ total_calculations = cur.fetchone()[0] or 0
442
+
443
+ cur.execute("SELECT COUNT(DISTINCT ip) FROM analytics WHERE action = 'page_visit' AND ip != 'unknown'")
444
+ unique_visitors = cur.fetchone()[0] or 0
445
+
446
+ cur.execute("SELECT breed, COUNT(*) FROM analytics WHERE action LIKE 'calculation_%' GROUP BY breed")
447
+ breed_stats = cur.fetchall()
448
+
449
+ # Total leads
450
+ cur.execute("SELECT COUNT(*) FROM leads")
451
+ total_leads = cur.fetchone()[0] or 0
452
+
453
+ conn.close()
454
+
455
+ return {
456
+ "total_visits": total_visits,
457
+ "today_visits": today_visits,
458
+ "unique_visitors": unique_visitors,
459
+ "total_calculations": total_calculations,
460
+ "total_leads": total_leads,
461
+ "breed_stats": breed_stats
462
+ }
463
+
464
+
465
  # ============================================================
466
  # FEED CALCULATION
467
  # ============================================================
468
 
469
+ def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_code, breed, request: gr.Request):
470
  # Validation
471
  try:
472
  birds = int(birds)
 
498
  # Save lead with breed
499
  save_lead(email, country_code, currency_code, breed)
500
 
501
+ # Track calculation
502
+ track_calculation(breed, birds, (weeks * 7 + days))
503
+
504
  # Total days
505
  total_days = (weeks * 7) + days
506
 
 
543
  age_text += f" + {days} day{'s' if days != 1 else ''}"
544
 
545
  html = f"""
546
+ <div style="font-size: 17px; line-height: 1.6;">
547
 
548
+ <div style="background: #f0fdf4; padding: 18px 22px; border-radius: 14px; border-left: 6px solid #22c55e; margin-bottom: 20px;">
549
+ <div style="font-size: 13px; color: #16a34a; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px;">🎯 Quick Answer</div>
550
+ <div style="font-size: 26px; font-weight: 800; color: #166534; margin: 6px 0 4px 0;">
551
+ ⭐ {rounded_bags} bags of {bag_size:g} kg feed
552
  </div>
553
+ <div style="color: #374151; font-size: 16px;">
554
+ To raise <strong>{birds:,} {breed}</strong> broilers to <strong>{age_text} ({total_days} days)</strong>
555
  </div>
556
+ <div style="margin-top: 6px; font-size: 13px;">
557
+ <span style="background: {breed_color}; color: white; padding: 3px 12px; border-radius: 14px; font-weight: 600;">{breed}</span>
558
+ <span style="background: #6b7280; color: white; padding: 3px 12px; border-radius: 14px; font-weight: 600; margin-left: 8px;">{country_name}</span>
559
  </div>
560
  </div>
561
 
562
  <div style="margin-bottom: 16px;">
563
+ <div style="font-size: 13px; color: #6b7280; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">🌾 Feed Breakdown</div>
564
+ <table style="width: 100%; border-collapse: collapse; margin-top: 6px; font-size: 15px;">
565
  <tr style="border-bottom: 1px solid #e5e7eb;">
566
  <td style="padding: 8px 4px;"><strong>🌱 Starter</strong></td>
567
  <td style="padding: 8px 4px; text-align: right;">{starter_kg:,.1f} kg</td>
 
580
  </table>
581
  </div>
582
 
583
+ <div style="margin-bottom: 16px; background: #eff6ff; padding: 14px 18px; border-radius: 10px; border-left: 4px solid #3b82f6;">
584
+ <div style="font-size: 13px; color: #6b7280; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">💰 Feed Cost</div>
585
+ <div style="font-size: 30px; font-weight: 800; color: #1e40af;">
586
  {currency_symbol}{total_cost:,.0f}
587
  </div>
588
  <div style="color: #6b7280; font-size: 14px;">
 
591
  </div>
592
 
593
  <div style="border-top: 1px solid #e5e7eb; padding-top: 14px;">
594
+ <div style="font-size: 13px; color: #6b7280; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">📊 Expected Performance</div>
595
+ <table style="width: 100%; border-collapse: collapse; margin-top: 6px; font-size: 15px;">
596
  <tr style="border-bottom: 1px solid #e5e7eb;">
597
  <td style="padding: 6px 4px;">Body weight / bird</td>
598
  <td style="padding: 6px 4px; text-align: right; font-weight: 600;">{expected_weight:.3f} kg</td>
 
605
  </div>
606
 
607
  <div style="margin-top: 14px; font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 10px;">
608
+ ⚠️ Estimate based on {breed} benchmark. Actual results may vary.
609
  </div>
610
  </div>
611
  """
 
703
  return table_data
704
 
705
 
706
+ def on_country_change_handler(country_selection):
707
  """Update price and currency when country changes."""
708
  if country_selection == "Auto-Detect":
709
  country_code = detect_country_from_env() or "NG"
 
712
 
713
  _, symbol, currency_code = get_country_info(country_code)
714
  default_price = get_default_price(currency_code)
715
+ return country_code, default_price, symbol
716
+
717
+
718
+ def show_analytics():
719
+ """Display analytics summary in UI."""
720
+ stats = get_analytics_summary()
721
+
722
+ breed_stats_html = ""
723
+ for breed, count in stats["breed_stats"]:
724
+ breed_stats_html += f"<li><strong>{breed}</strong>: {count} calculations</li>"
725
+
726
+ if not breed_stats_html:
727
+ breed_stats_html = "<li>No calculations yet</li>"
728
+
729
+ return f"""
730
+ ### 📊 Poultry Feed Calculator - Analytics
731
+
732
+ | Metric | Value |
733
+ |--------|-------|
734
+ | **Total Visits** | **{stats['total_visits']:,}** |
735
+ | **Today's Visits** | **{stats['today_visits']}** |
736
+ | **Unique Visitors** | **{stats['unique_visitors']:,}** |
737
+ | **Total Calculations** | **{stats['total_calculations']:,}** |
738
+ | **Total Leads (Emails)** | **{stats['total_leads']:,}** |
739
+
740
+ ### 🐔 Most Popular Breeds
741
+
742
+ <ul>{breed_stats_html}</ul>
743
+
744
+ ---
745
+ *Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
746
+ """
747
 
748
 
749
  # ============================================================
 
770
 
771
  gr.HTML("""
772
  <div class="main-title">
773
+ <h1>🐔 PoultryFeedCalc</h1>
774
+ <p>Simple Broiler Feed Calculator — Know exactly how much feed you need before buying chicks.</p>
775
  </div>
776
  """)
777
 
 
 
 
 
 
 
778
  with gr.Row(equal_height=True):
779
 
780
  # LEFT COLUMN: INPUTS
781
  with gr.Column(scale=1, min_width=350):
782
 
783
  with gr.Group():
784
+ gr.Markdown("## 🐔 1. Breed & Birds")
785
 
786
  breed = gr.Dropdown(
787
  choices=["Ross 308", "Cobb 500", "Arbor Acres"],
788
+ value="Cobb 500",
789
  label="Breed",
790
  info="Select your broiler breed for accurate estimates",
791
  )
 
802
  with gr.Row():
803
  weeks = gr.Dropdown(
804
  choices=list(range(0, 21)),
805
+ value=8,
806
  label="Weeks",
807
  )
808
  days = gr.Dropdown(
 
811
  label="+ Days",
812
  )
813
 
814
+ gr.Markdown("## 🌾 3. Feed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
815
 
816
  with gr.Row():
817
  bag_size = gr.Dropdown(
 
825
  minimum=0,
826
  )
827
 
828
+ gr.Markdown("## 🌍 4. Country & Currency")
829
+
830
+ detected_country = detect_country_from_env() or "NG"
831
+ country_choices = ["Auto-Detect"] + [code for code, _ in COUNTRY_LIST]
832
+
833
+ country_dropdown = gr.Dropdown(
834
+ choices=country_choices,
835
+ value="Auto-Detect",
836
+ label="Select your country (Auto-Detect uses your IP)",
837
+ )
838
+
839
+ country_code_state = gr.State(detected_country)
840
+
841
  gr.Markdown("## 📧 5. Your email")
842
 
843
  email = gr.Textbox(
 
845
  placeholder="farmer@example.com",
846
  type="email",
847
  elem_classes=["email-box"],
848
+ info="Required — we'll send you future updates",
849
  )
850
 
851
  calculate_btn = gr.Button(
852
+ "🐔 Calculate Feed Requirement",
853
  variant="primary",
854
  size="lg",
855
  )
 
873
  )
874
 
875
  # ============================================================
876
+ # BENCHMARK SECTION
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
  # ============================================================
878
 
879
+ gr.Markdown("---