Spaces:
Paused
Paused
File size: 69,657 Bytes
2b56ea8 bda0a57 da4e598 2b56ea8 9d8d72d 4562227 2b56ea8 b1f5518 08cc03c 2b56ea8 b1f5518 6087658 2b56ea8 bda0a57 95e5a9a 67da504 2b56ea8 d6790bc da4e598 d6790bc da4e598 d6790bc 2b56ea8 95e5a9a 2b56ea8 da4e598 2b56ea8 95e5a9a 2b56ea8 da4e598 2b56ea8 95e5a9a 2b56ea8 da4e598 1cfa99c da4e598 2b56ea8 da4e598 95e5a9a da4e598 95e5a9a da4e598 95e5a9a 2b56ea8 95e5a9a da4e598 95e5a9a 2b56ea8 da4e598 95e5a9a da4e598 95e5a9a da4e598 95e5a9a 2b56ea8 95e5a9a da4e598 95e5a9a da4e598 2b56ea8 da4e598 2b56ea8 da4e598 2b56ea8 da4e598 2b56ea8 da4e598 2b56ea8 da4e598 98e2408 da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 98e2408 d6790bc 98e2408 d6790bc 98e2408 d6790bc 98e2408 d6790bc 98e2408 d6790bc 98e2408 d6790bc 98e2408 d6790bc 98e2408 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc 95e5a9a a3ddfc3 95e5a9a a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 95e5a9a 2b56ea8 da4e598 d6790bc da4e598 d6790bc da4e598 2b56ea8 95e5a9a a3ddfc3 95e5a9a da4e598 a3ddfc3 2b56ea8 da4e598 d6790bc da4e598 d6790bc da4e598 a3ddfc3 da4e598 a3ddfc3 2b56ea8 da4e598 a3ddfc3 95e5a9a da4e598 a3ddfc3 2b56ea8 da4e598 a3ddfc3 b69ad1c da4e598 d6790bc da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 2b56ea8 da4e598 a3ddfc3 da4e598 d6790bc da4e598 d6790bc da4e598 95e5a9a da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 2b56ea8 da4e598 d6790bc da4e598 a3ddfc3 da4e598 2b56ea8 da4e598 d6790bc da4e598 d6790bc da4e598 2b56ea8 da4e598 d6790bc da4e598 a3ddfc3 da4e598 2b56ea8 da4e598 d6790bc da4e598 a3ddfc3 da4e598 2b56ea8 da4e598 a3ddfc3 2b56ea8 a3ddfc3 bda0a57 2b56ea8 d6790bc da4e598 d6790bc 95e5a9a da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc 95e5a9a d6790bc 95e5a9a da4e598 2b56ea8 da4e598 95e5a9a 2b56ea8 da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc 2b56ea8 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc 2b56ea8 da4e598 2b56ea8 a3ddfc3 da4e598 1cfa99c da4e598 1c94841 da4e598 74820bf 67da504 da4e598 67da504 da4e598 a3ddfc3 da4e598 74820bf eddfa89 da4e598 67da504 da4e598 a3ddfc3 da4e598 d6790bc da4e598 d6790bc da4e598 67da504 da4e598 67da504 da4e598 67da504 da4e598 67da504 da4e598 d6790bc da4e598 74820bf da4e598 67da504 da4e598 67da504 da4e598 a3ddfc3 da4e598 67da504 74820bf da4e598 67da504 da4e598 a3ddfc3 67da504 da4e598 67da504 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 67da504 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 67da504 da4e598 a3ddfc3 da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 d6790bc da4e598 67da504 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 d6790bc da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 d6790bc da4e598 d6790bc a3ddfc3 da4e598 67da504 da4e598 67da504 da4e598 a3ddfc3 da4e598 67da504 da4e598 a3ddfc3 da4e598 a3ddfc3 67da504 da4e598 67da504 da4e598 d6790bc a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 d6790bc da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 67da504 da4e598 a3ddfc3 da4e598 a3ddfc3 da4e598 d6790bc da4e598 1c94841 da4e598 67da504 a3ddfc3 da4e598 d6790bc da4e598 e50cebd 86cc7c3 da4e598 1639927 67da504 da4e598 1c94841 eddfa89 2b56ea8 8b5c8d2 b1f5518 08cc03c 8b5c8d2 aca6d70 f4987c7 aca6d70 8b5c8d2 aca6d70 8b5c8d2 aca6d70 8b5c8d2 aca6d70 8b5c8d2 0ef2aae 2b56ea8 fb50440 568480b 2b56ea8 da4e598 b69ad1c da4e598 1cfa99c da4e598 67da504 da4e598 67da504 95e5a9a da4e598 95e5a9a 67da504 95e5a9a da4e598 95e5a9a da4e598 67da504 95e5a9a da4e598 67da504 da4e598 67da504 98d9cb6 da4e598 a3ddfc3 da4e598 67da504 2b56ea8 da4e598 9d8d72d da4e598 9d8d72d b69ad1c 9d8d72d da4e598 67da504 da4e598 67da504 95e5a9a da4e598 0e09b12 da4e598 2b56ea8 da4e598 95e5a9a da4e598 95e5a9a da4e598 2b56ea8 da4e598 67da504 da4e598 67da504 2b56ea8 4562227 6de560e 69cbf4e 6de560e 69cbf4e 6de560e 69cbf4e 6de560e 69cbf4e 6de560e 69cbf4e 6de560e 69cbf4e 6de560e 69cbf4e 6de560e 69cbf4e 6de560e 69cbf4e 4562227 aca6d70 58106bd 47ad6d0 25fca72 fb50440 09f9088 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 | import os
import math
import re
import sqlite3
import json
import urllib.parse
from datetime import datetime, timezone
from pathlib import Path
import threading
from fastapi import FastAPI
from fastapi.responses import Response
import gradio as gr
from pathlib import Path
SOCIAL_PREVIEW_PATH = Path("social-preview.jpg").resolve()
gr.set_static_paths(paths=[SOCIAL_PREVIEW_PATH])
# ============================================================
# APP CONFIG
# ============================================================
APP_NAME = "π How Much Feed?"
DB_PATH = os.environ.get("DATABASE_PATH", "/data/howmuchfeed.db")
# Admin password - set this in Hugging Face Secrets
ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "")
# Create directory if it doesn't exist
db_dir = os.path.dirname(DB_PATH)
if db_dir and not os.path.exists(db_dir):
os.makedirs(db_dir, exist_ok=True)
STARTER_END_DAY = 21
# ============================================================
# GOOGLE SHEETS INTEGRATION
# ============================================================
def init_google_sheets():
"""Initialize Google Sheets connection."""
try:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
creds_json = os.environ.get("GOOGLE_SHEETS_CREDENTIALS")
sheet_id = os.environ.get("GOOGLE_SHEETS_ID")
if not creds_json or not sheet_id:
print("β οΈ Google Sheets not configured. Using local database only.")
return None, None
creds_dict = json.loads(creds_json)
scope = [
"https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/drive"
]
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
client = gspread.authorize(creds)
try:
sheet = client.open_by_key(sheet_id)
print(f"β
Google Sheets connected: {sheet.title}")
except:
sheet = client.create("How Much Feed Calculator Leads")
print(f"β
New Google Sheet created")
return client, sheet
except Exception as e:
print(f"β οΈ Google Sheets error: {e}")
return None, None
# Google Sheets is initialized lazily on first sync.
# This keeps the public calculator fast to load even when Sheets is not configured.
gs_client = None
gs_sheet = None
gs_initialized = False
gs_init_lock = threading.Lock()
def get_google_sheets():
global gs_client, gs_sheet, gs_initialized
if gs_initialized:
return gs_client, gs_sheet
with gs_init_lock:
if not gs_initialized:
gs_client, gs_sheet = init_google_sheets()
gs_initialized = True
return gs_client, gs_sheet
def sync_to_google_sheets(email, country, currency, breed, action="lead", question=""):
"""Sync a lead or farmer question to Google Sheets, if configured."""
client, sheet = get_google_sheets()
if not client or not sheet:
return False
try:
if action == "lead":
worksheet_name = "Leads"
headers = ["Email", "Country", "Currency", "Breed", "Created At"]
row_data = [email, country, currency, breed, datetime.now(timezone.utc).isoformat()]
elif action == "question":
worksheet_name = "Questions"
headers = ["Email", "Question", "Breed", "Created At"]
row_data = [email or "", question or "", breed or "", datetime.now(timezone.utc).isoformat()]
else:
return False
try:
worksheet = sheet.worksheet(worksheet_name)
except Exception:
worksheet = sheet.add_worksheet(title=worksheet_name, rows=1000, cols=20)
worksheet.append_row(headers)
worksheet.append_row(row_data)
print(f"β
Synced to Google Sheets: {email or 'anonymous'}")
return True
except Exception as e:
print(f"β οΈ Google Sheets sync error: {e}")
return False
# ============================================================
# VERIFIED BREED DATA - From Official PDFs
# ============================================================
# Body Weight (kg) at key days - As-Hatched Performance
BREED_WEIGHT_DATA = {
"Ross 308": {
0: 0.044, 7: 0.213, 14: 0.533, 21: 1.012,
28: 1.616, 35: 2.296, 42: 2.998, 49: 3.681, 56: 4.318,
},
"Cobb 500": {
0: 0.042, 7: 0.177, 14: 0.459, 21: 0.891,
28: 1.436, 35: 2.067, 42: 2.732, 49: 3.369, 56: 3.958,
},
"Arbor Acres": {
0: 0.044, 7: 0.209, 14: 0.527, 21: 1.006,
28: 1.611, 35: 2.287, 42: 2.964, 49: 3.662, 56: 4.318,
}
}
# Cumulative Feed (kg) at key days - As-Hatched Performance
BREED_FEED_DATA = {
"Ross 308": {
0: 0.000, 7: 0.166, 14: 0.535, 21: 1.155,
28: 2.051, 35: 3.211, 42: 4.586, 49: 6.115, 56: 7.733,
},
"Cobb 500": {
0: 0.000, 7: 0.150, 14: 0.465, 21: 1.053,
28: 1.963, 35: 3.216, 42: 4.659, 49: 6.185, 56: 7.772,
},
"Arbor Acres": {
0: 0.000, 7: 0.207, 14: 0.638, 21: 1.163,
28: 2.069, 35: 3.237, 42: 4.625, 49: 6.111, 56: 7.647,
}
}
# Breed descriptions and availability
BREED_INFO = {
"Ross 308": {
"description": "Big chest, thick legs, very fast growth. Excellent for meat production.",
"available_at": "Agrited, Sayed, Valentine",
"color": "#00A86B"
},
"Cobb 500": {
"description": "Good early growth, strong legs, solid feed conversion.",
"available_at": "Chikun, Zartech",
"color": "#00A86B"
},
"Arbor Acres": {
"description": "Balanced growth, hardy and adaptable. Great survival rate.",
"available_at": "Supreme, CHI,Vertex, Fidan, Cascada, Sunchi, Farm Support e.t.c",
"color": "#00A86B"
}
}
def get_breed_weight_data(breed):
return BREED_WEIGHT_DATA.get(breed, BREED_WEIGHT_DATA["Ross 308"])
def get_breed_feed_data(breed):
return BREED_FEED_DATA.get(breed, BREED_FEED_DATA["Ross 308"])
def interpolate_weight(day, breed):
"""Interpolate body weight between known checkpoints."""
weight_data = get_breed_weight_data(breed)
if day <= 0:
return weight_data[0]
if day >= 56:
return weight_data[56]
keys = sorted(weight_data.keys())
for i in range(len(keys) - 1):
if keys[i] <= day <= keys[i + 1]:
ratio = (day - keys[i]) / (keys[i + 1] - keys[i])
return weight_data[keys[i]] + (weight_data[keys[i + 1]] - weight_data[keys[i]]) * ratio
return weight_data[56]
def interpolate_feed(day, breed):
"""Interpolate cumulative feed between known checkpoints."""
feed_data = get_breed_feed_data(breed)
if day <= 0:
return 0.0
if day >= 56:
return feed_data[56]
keys = sorted(feed_data.keys())
for i in range(len(keys) - 1):
if keys[i] <= day <= keys[i + 1]:
ratio = (day - keys[i]) / (keys[i + 1] - keys[i])
return feed_data[keys[i]] + (feed_data[keys[i + 1]] - feed_data[keys[i]]) * ratio
return feed_data[56]
# ============================================================
# BENCHMARK TABLE GENERATOR
# ============================================================
def get_benchmark_table(breed):
"""Generate benchmark table for the selected breed."""
weight_data = get_breed_weight_data(breed)
feed_data = get_breed_feed_data(breed)
days = [7, 14, 21, 28, 35, 42, 49, 56]
table_data = []
for day in days:
weight = weight_data.get(day, 0)
feed = feed_data.get(day, 0)
fcr = feed / weight if weight > 0 else 0
table_data.append([day, f"{weight:.3f}", f"{feed:.3f}", f"{fcr:.3f}"])
return table_data, days
def get_benchmark_html(breed):
"""Render the selected breed benchmark as lightweight HTML instead of a JS dataframe."""
table_data, _ = get_benchmark_table(breed)
rows = []
for day, weight, feed, fcr in table_data:
rows.append(
f"<tr><td>{day}</td><td>{weight} kg</td><td>{feed} kg</td><td>{fcr}</td></tr>"
)
return f"""
<div class="table-wrap benchmark-html">
<table class="feed-table benchmark-table">
<thead><tr><th>Days</th><th>Body Weight</th><th>Cumulative Feed</th><th>FCR</th></tr></thead>
<tbody>{''.join(rows)}</tbody>
</table>
</div>
"""
def get_comparison_html():
"""Render the breed comparison as lightweight HTML."""
data, breeds, _ = get_breed_comparison_table()
headers = ['Days'] + [f'{b} Weight' for b in breeds] + [f'{b} Feed' for b in breeds]
# Keep the comparison compact on phones: weight and feed are the most useful fields.
rows = []
for row in data:
day = row[0]
vals = row[1:]
weights = vals[0::3]
feeds = vals[1::3]
cells = [f'<td>{day}</td>']
cells += [f'<td>{v} kg</td>' for v in weights]
cells += [f'<td>{v} kg</td>' for v in feeds]
rows.append('<tr>' + ''.join(cells) + '</tr>')
head = ''.join(f'<th>{h}</th>' for h in headers)
return f"""
<div class="table-wrap benchmark-html">
<table class="feed-table benchmark-table comparison-table">
<thead><tr>{head}</tr></thead>
<tbody>{''.join(rows)}</tbody>
</table>
</div>
"""
def get_breed_comparison_table():
"""Generate comparison table for all three breeds."""
breeds = ["Ross 308", "Cobb 500", "Arbor Acres"]
days = [7, 14, 21, 28, 35, 42, 49, 56]
table_data = []
for day in days:
row = [day]
for breed in breeds:
weight_data = get_breed_weight_data(breed)
feed_data = get_breed_feed_data(breed)
weight = weight_data.get(day, 0)
feed = feed_data.get(day, 0)
fcr = feed / weight if weight > 0 else 0
row.append(f"{weight:.3f}")
row.append(f"{feed:.3f}")
row.append(f"{fcr:.3f}")
table_data.append(row)
return table_data, breeds, days
# ============================================================
# CURRENCY DATA
# ============================================================
CURRENCIES = {
"NG": ("Nigeria", "β¦", "NGN"),
"GH": ("Ghana", "β΅", "GHS"),
"KE": ("Kenya", "KSh", "KES"),
"UG": ("Uganda", "USh", "UGX"),
"TZ": ("Tanzania", "TSh", "TZS"),
"ZA": ("South Africa", "R", "ZAR"),
"ZM": ("Zambia", "ZK", "ZMW"),
"ZW": ("Zimbabwe", "ZiG", "ZWG"),
"CM": ("Cameroon", "FCFA", "XAF"),
"CI": ("CΓ΄te d'Ivoire", "CFA", "XOF"),
"SN": ("Senegal", "CFA", "XOF"),
"US": ("United States", "$", "USD"),
"GB": ("United Kingdom", "Β£", "GBP"),
"CA": ("Canada", "C$", "CAD"),
"AU": ("Australia", "A$", "AUD"),
"IN": ("India", "βΉ", "INR"),
"PK": ("Pakistan", "β¨", "PKR"),
"BD": ("Bangladesh", "ΰ§³", "BDT"),
"BR": ("Brazil", "R$", "BRL"),
}
DEFAULT_PRICES = {
"NGN": 24000, "GHS": 300, "KES": 2200, "UGX": 100000,
"TZS": 30000, "ZAR": 300, "ZMW": 350, "USD": 25,
"GBP": 20, "EUR": 23, "INR": 2200, "PKR": 7000,
"BDT": 2500, "AUD": 35, "CAD": 35, "NZD": 40,
"BRL": 130, "XAF": 15000, "XOF": 15000, "ZWG": 350,
}
def detect_country_from_env():
"""Best-effort country detection from environment variables."""
candidates = [
os.environ.get("COUNTRY_CODE"),
os.environ.get("CF-IPCOUNTRY"),
os.environ.get("GEOIP_COUNTRY"),
os.environ.get("HTTP_CF_IPCOUNTRY"),
]
for value in candidates:
if value:
value = value.strip().upper()
if value in CURRENCIES:
return value
return None
def get_country_info(country_code):
"""Get currency info for a country code."""
if country_code in CURRENCIES:
name, symbol, code = CURRENCIES[country_code]
return country_code, symbol, code
return "NG", "β¦", "NGN"
def get_default_price(currency_code):
return DEFAULT_PRICES.get(currency_code, 24000)
COUNTRY_LIST = sorted([(code, f"{name} ({symbol})") for code, (name, symbol, curr) in CURRENCIES.items()])
# ============================================================
# DATABASE
# ============================================================
def init_db():
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS leads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE,
country TEXT,
currency TEXT,
breed TEXT,
created_at TEXT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS farmer_questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT,
question TEXT,
breed TEXT,
created_at TEXT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS calculations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT,
country TEXT,
currency TEXT,
breed TEXT,
birds INTEGER,
weeks INTEGER,
days INTEGER,
total_days INTEGER,
bag_size REAL,
price_per_bag REAL,
total_feed_kg REAL,
starter_kg REAL,
finisher_kg REAL,
starter_bags REAL,
finisher_bags REAL,
total_bags REAL,
rounded_bags INTEGER,
total_cost REAL,
created_at TEXT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS analytics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
visit_date TEXT,
ip TEXT,
country TEXT,
breed TEXT,
action TEXT,
created_at TEXT
)
""")
# Backward-compatible analytics migration
analytics_columns = {
"referrer": "TEXT",
"utm_source": "TEXT",
"utm_medium": "TEXT",
"utm_campaign": "TEXT",
"utm_content": "TEXT",
"utm_term": "TEXT",
}
cur.execute("PRAGMA table_info(analytics)")
existing_columns = {row[1] for row in cur.fetchall()}
for column, column_type in analytics_columns.items():
if column not in existing_columns:
cur.execute(
f"ALTER TABLE analytics ADD COLUMN {column} {column_type}"
)
conn.commit()
conn.close()
print(f"β
Database initialized at: {DB_PATH}")
init_db()
# ============================================================
# DATABASE HELPERS
# ============================================================
def valid_email(email):
if not email:
return False
email = email.strip()
pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
return bool(re.match(pattern, email))
def save_lead(email, country, currency, breed):
if not valid_email(email):
return
# Save to SQLite
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
INSERT OR IGNORE INTO leads (email, country, currency, breed, created_at)
VALUES (?, ?, ?, ?, ?)
""", (email.strip().lower(), country, currency, breed, datetime.now(timezone.utc).isoformat()))
conn.commit()
conn.close()
# Sync to Google Sheets
try:
sync_to_google_sheets(email, country, currency, breed, "lead")
except Exception as e:
print(f"Google Sheets sync error: {e}")
def save_question(email, question, breed):
if not question or not question.strip():
return
# Save to SQLite
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
INSERT INTO farmer_questions (email, question, breed, created_at)
VALUES (?, ?, ?, ?)
""", (email.strip().lower() if email else "", question.strip(), breed, datetime.now(timezone.utc).isoformat()))
conn.commit()
conn.close()
# Sync to Google Sheets
try:
sync_to_google_sheets(email, "", "", breed, "question", question)
except Exception as e:
print(f"Google Sheets sync error: {e}")
def save_calculation(email, country, currency, breed, birds, weeks, days, total_days,
bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
starter_bags, finisher_bags, total_bags, rounded_bags, total_cost):
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
INSERT INTO calculations (
email, country, currency, breed, birds, weeks, days, total_days,
bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
starter_bags, finisher_bags, total_bags, rounded_bags, total_cost, created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (email.strip().lower() if email else "", country, currency, breed, birds, weeks, days, total_days,
bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
starter_bags, finisher_bags, total_bags, rounded_bags, total_cost,
datetime.now(timezone.utc).isoformat()))
conn.commit()
conn.close()
def track_visit(request: gr.Request):
"""Track page visit, country, referrer and UTM campaign data."""
try:
client_ip = (
request.client.host
if request and hasattr(request, "client")
else "unknown"
)
headers = request.headers if request and hasattr(request, "headers") else {}
# Referrer
referrer = (
headers.get("referer")
or headers.get("referrer")
or ""
)
# UTM parameters
query_params = {}
if request and hasattr(request, "query_params"):
try:
query_params = dict(request.query_params)
except Exception:
query_params = {}
utm_source = query_params.get("utm_source", "")
utm_medium = query_params.get("utm_medium", "")
utm_campaign = query_params.get("utm_campaign", "")
utm_content = query_params.get("utm_content", "")
utm_term = query_params.get("utm_term", "")
country = detect_country_from_env() or "NG"
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
INSERT INTO analytics (
visit_date,
ip,
country,
action,
created_at,
referrer,
utm_source,
utm_medium,
utm_campaign,
utm_content,
utm_term
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
datetime.now().strftime("%Y-%m-%d"),
client_ip,
country,
"page_visit",
datetime.now(timezone.utc).isoformat(),
referrer,
utm_source,
utm_medium,
utm_campaign,
utm_content,
utm_term,
))
conn.commit()
conn.close()
except Exception as e:
print(f"Analytics error: {e}")
def track_calculation(breed, birds, days):
"""Track when a calculation is performed."""
try:
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
INSERT INTO analytics (visit_date, country, breed, action, created_at)
VALUES (?, ?, ?, ?, ?)
""", (
datetime.now().strftime("%Y-%m-%d"),
detect_country_from_env() or "NG",
breed,
f"calculation_{birds}_{days}",
datetime.now().isoformat()
))
conn.commit()
conn.close()
return True
except:
return False
def get_analytics_summary():
"""Get analytics summary."""
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM analytics WHERE action = 'page_visit'")
total_visits = cur.fetchone()[0] or 0
cur.execute("SELECT COUNT(*) FROM analytics WHERE action = 'page_visit' AND visit_date = ?",
(datetime.now().strftime("%Y-%m-%d"),))
today_visits = cur.fetchone()[0] or 0
cur.execute("SELECT COUNT(*) FROM analytics WHERE action LIKE 'calculation_%'")
total_calculations = cur.fetchone()[0] or 0
cur.execute("SELECT COUNT(DISTINCT ip) FROM analytics WHERE action = 'page_visit' AND ip != 'unknown'")
unique_visitors = cur.fetchone()[0] or 0
cur.execute("SELECT breed, COUNT(*) FROM analytics WHERE action LIKE 'calculation_%' GROUP BY breed")
breed_stats = cur.fetchall()
# Total leads
cur.execute("SELECT COUNT(*) FROM leads")
total_leads = cur.fetchone()[0] or 0
conn.close()
return {
"total_visits": total_visits,
"today_visits": today_visits,
"unique_visitors": unique_visitors,
"total_calculations": total_calculations,
"total_leads": total_leads,
"breed_stats": breed_stats
}
# ============================================================
# SHARE LINKS GENERATOR
# ============================================================
def get_share_links(app_url="https://howmuchfeed.com"):
"""Generate share links for WhatsApp, Email, Facebook, Twitter."""
share_text = f"π Calculate your poultry feed needs at {app_url}"
encoded = urllib.parse.quote(share_text)
links = {
"whatsapp": f"https://wa.me/?text={encoded}",
"email": f"mailto:?subject=How Much Feed? - Poultry Feed Calculator&body={encoded}",
"facebook": f"https://www.facebook.com/sharer/sharer.php?u={urllib.parse.quote(app_url)}",
"twitter": f"https://twitter.com/intent/tweet?text={encoded}",
}
return links
# ============================================================
# FEED CALCULATION - MINT GREEN & EGG YELLOW DESIGN
# ============================================================
def calculate_feed(birds, weeks, days, bag_size, price_per_bag, email, country_code, breed, request: gr.Request):
# Validation
try:
birds = int(birds)
weeks = int(weeks)
days = int(days)
bag_size = float(bag_size)
price_per_bag = float(price_per_bag)
except Exception:
return "β οΈ Please enter valid numbers.", ""
if birds <= 0:
return "β οΈ Number of birds must be greater than zero.", ""
if weeks < 0:
return "β οΈ Weeks cannot be negative.", ""
if days < 0 or days > 6:
return "β οΈ Days must be between 0 and 6.", ""
if bag_size <= 0:
return "β οΈ Feed bag size must be greater than zero.", ""
if price_per_bag < 0:
return "β οΈ Price per bag cannot be negative.", ""
if not valid_email(email):
return "π§ **Email required**\n\nPlease enter your email address before calculating.", ""
# Country / Currency
country_name, symbol, currency_code = get_country_info(country_code)
currency_symbol = symbol
# Save lead with breed
save_lead(email, country_code, currency_code, breed)
# Track calculation
track_calculation(breed, birds, (weeks * 7 + days))
# Total days
total_days = (weeks * 7) + days
# Total feed
total_feed_per_bird = interpolate_feed(total_days, breed)
total_feed_kg = birds * total_feed_per_bird
# Starter / Finisher
starter_days = min(total_days, STARTER_END_DAY)
starter_per_bird = interpolate_feed(starter_days, breed)
starter_kg = birds * starter_per_bird
finisher_kg = max(total_feed_kg - starter_kg, 0)
# Bags
starter_bags = starter_kg / bag_size
finisher_bags = finisher_kg / bag_size
total_bags = total_feed_kg / bag_size
rounded_bags = math.ceil(total_bags)
total_cost = rounded_bags * price_per_bag
# Expected performance
expected_weight = interpolate_weight(total_days, breed)
# Save calculation
save_calculation(email, country_code, currency_code, breed, birds, weeks, days, total_days,
bag_size, price_per_bag, total_feed_kg, starter_kg, finisher_kg,
starter_bags, finisher_bags, total_bags, rounded_bags, total_cost)
# Breed info
breed_info = BREED_INFO.get(breed, BREED_INFO["Ross 308"])
breed_color = breed_info["color"]
# Generate share links
share_links = get_share_links()
# Output HTML - mobile-first farmer-friendly result
starter_bags_display = f"{starter_bags:.1f}"
finisher_bags_display = f"{finisher_bags:.1f}"
age_text = f"{weeks} week{'s' if weeks != 1 else ''}"
if days:
age_text += f" + {days} day{'s' if days != 1 else ''}"
share_text = (
f"How Much Feed?\n"
f"{breed} broilers: {birds:,} birds for {age_text}.\n"
f"Feed needed: {total_feed_kg:,.1f} kg ({total_bags:.1f} bags).\n"
f"Buy {rounded_bags} bags."
)
share_encoded = urllib.parse.quote(share_text)
share_links = {
"whatsapp": f"https://wa.me/?text={share_encoded}",
"email": f"mailto:?subject=My How Much Feed result&body={share_encoded}",
"facebook": f"https://www.facebook.com/sharer/sharer.php?u={urllib.parse.quote('https://howmuchfeed.com')}",
"twitter": f"https://twitter.com/intent/tweet?text={share_encoded}",
}
html = f"""
<div class="results-shell">
<section class="buy-card">
<div class="eyebrow">YOUR FEED RESULT</div>
<div class="buy-label">BUY</div>
<div class="buy-number">{rounded_bags}</div>
<div class="buy-unit">BAGS</div>
<div class="buy-note">Recommended amount, rounded up to the next whole bag.</div>
</section>
<div class="result-context">
<strong>{birds:,} {breed} broilers</strong> Β· {age_text} ({total_days} days)
</div>
<p class="plain-answer">
You need <strong>{total_feed_kg:,.1f} kg</strong> of feed, equal to about
<strong>{total_bags:.1f} bags</strong> of {bag_size:g} kg feed.
</p>
<div class="metric-grid">
<div class="metric-card">
<span class="metric-icon">βοΈ</span>
<span class="metric-label">Feed needed</span>
<strong>{total_feed_kg:,.1f} kg</strong>
</div>
<div class="metric-card">
<span class="metric-icon">β</span>
<span class="metric-label">Exact amount</span>
<strong>{total_bags:.1f} bags</strong>
</div>
<div class="metric-card">
<span class="metric-icon">β¦</span>
<span class="metric-label">Estimated cost</span>
<strong>{currency_symbol}{total_cost:,.0f}</strong>
</div>
<div class="metric-card">
<span class="metric-icon">π
</span>
<span class="metric-label">Growing period</span>
<strong>{total_days} days</strong>
</div>
</div>
<section class="result-section">
<div class="section-title">πΎ Feed Breakdown</div>
<div class="table-wrap">
<table class="feed-table">
<thead>
<tr><th>Stage</th><th>Feed</th><th>Bags</th></tr>
</thead>
<tbody>
<tr><td>Starter <span class="muted">(0β21 days)</span></td><td>{starter_kg:,.1f} kg</td><td>{starter_bags_display}</td></tr>
<tr><td>Finisher <span class="muted">(Day 22+)</span></td><td>{finisher_kg:,.1f} kg</td><td>{finisher_bags_display}</td></tr>
<tr class="total-row"><td>TOTAL</td><td>{total_feed_kg:,.1f} kg</td><td>{total_bags:.1f} bags</td></tr>
</tbody>
</table>
</div>
</section>
<section class="cost-card">
<div class="section-title">π° Feed Cost Estimate</div>
<div class="cost-main">{currency_symbol}{total_cost:,.0f}</div>
<div class="cost-note">Based on {rounded_bags} bags Γ {currency_symbol}{price_per_bag:,.0f} per bag.</div>
</section>
<section class="result-section performance-section">
<div class="section-title">π Expected Performance</div>
<div class="performance-grid">
<div><span>Body weight per bird</span><strong>{expected_weight:.3f} kg</strong></div>
</div>
</section>
<section class="result-section share-section">
<div class="section-title">π€ Share Result</div>
<div class="share-grid">
<a class="share-btn whatsapp" href="{share_links['whatsapp']}" target="_blank" rel="noopener">WhatsApp</a>
<a class="share-btn email" href="{share_links['email']}" target="_blank" rel="noopener">Email</a>
<a class="share-btn facebook" href="{share_links['facebook']}" target="_blank" rel="noopener">Facebook</a>
<a class="share-btn twitter" href="{share_links['twitter']}" target="_blank" rel="noopener">X</a>
</div>
</section>
<div class="result-disclaimer">
β οΈ This is an estimate based on the selected {breed} benchmark. Actual feed use can vary with feed quality, management, environment and bird performance.
</div>
</div>
"""
return html, f"β
Saved for {email.strip().lower()}."
# ============================================================
# QUESTION / ANSWER
# ============================================================
def answer_farmer_question(question, email, breed):
if not question or not question.strip():
return "Please type or speak your question first."
save_question(email or "", question, breed)
q = question.lower().strip()
if "bag" in q and ("feed" in q or "birds" in q):
answer = """
### Feed-bag questions
For an exact feed estimate, use the calculator above.
Enter:
1. Number of birds
2. Age in weeks + days
3. Feed bag size
4. Price per bag
5. Your email
6. Breed
The calculator will give you the estimated total bags, starter/finisher breakdown and feed cost.
"""
elif "breed" in q or "ross" in q or "cobb" in q or "arbor" in q:
answer = """
### Common Broiler Breeds in Nigeria
| Breed | Characteristics | Available At |
|-------|-----------------|--------------|
| **Ross 308** | Big chest, thick legs, very fast growth | Agrited, Sayed, Valentine |
| **Cobb 500** | Good early growth, strong legs | Chikun, Zartech |
| **Arbor Acres** | Balanced growth, hardy, adaptable | Supreme, CHI, GS, Vertex, Fidan, Cascada, Orobor, Sunchi, Farm Support, Ajila |
Tip: Before buying chicks, ask about the breed and hatchery. Not all broilers are the same!
"""
elif "starter" in q:
answer = f"""
### Starter feed
Starter feed is used during the early growth period (Day 0β{STARTER_END_DAY}).
The calculator separates the estimated feed requirement into **Starter** and **Finisher** based on the selected age.
"""
elif "finisher" in q:
answer = f"""
### Finisher feed
Finisher feed is used after day {STARTER_END_DAY}.
Your calculator automatically estimates the finisher requirement from the selected number of birds and total age.
"""
elif "cost" in q or "price" in q:
answer = """
### Feed cost
Enter the current price of one feed bag in the calculator.
The app calculates: **Number of bags Γ price per bag = estimated feed cost**
The result is for **feed alone**.
"""
else:
answer = f"""
### Question received
**β{question.strip()}β**
Your question has been saved.
We can use the questions farmers submit to decide which answers, calculators and features should be added to the app next.
"""
return answer
# ============================================================
# UPDATE FUNCTIONS
# ============================================================
def update_benchmark(breed):
"""Update the benchmark table when breed changes."""
return get_benchmark_html(breed)
def update_selected_breed_badge(breed):
"""Update the always-visible selected-breed badge."""
safe_breed = breed or "Ross 308"
return f'<span class="selected-breed-badge">{safe_breed}</span>'
def on_country_change_handler(country_selection):
"""Update country state and default feed price when country changes."""
if country_selection == "Auto-Detect":
country_code = detect_country_from_env() or "NG"
else:
country_code = country_selection
_, symbol, currency_code = get_country_info(country_code)
default_price = get_default_price(currency_code)
return country_code, default_price
# ============================================================
# ADMIN FUNCTIONS
# ============================================================
def show_analytics(password):
"""Display analytics summary - only with correct password."""
if password != ADMIN_PASSWORD:
return """
### Admin Access Required
Please enter the correct admin password to view analytics.
"""
stats = get_analytics_summary()
breed_stats_html = ""
for breed, count in stats["breed_stats"]:
breed_stats_html += f"<li><strong>{breed}</strong>: {count} calculations</li>"
if not breed_stats_html:
breed_stats_html = "<li>No calculations yet</li>"
return f"""
### How Much Feed? - Analytics
| Metric | Value |
|--------|-------|
| **Total Visits** | **{stats['total_visits']:,}** |
| **Today's Visits** | **{stats['today_visits']}** |
| **Unique Visitors** | **{stats['unique_visitors']:,}** |
| **Total Calculations** | **{stats['total_calculations']:,}** |
| **Total Leads (Emails)** | **{stats['total_leads']:,}** |
### Most Popular Breeds
<ul>{breed_stats_html}</ul>
---
*Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
"""
def admin_login(password):
"""Check admin password and return the dashboard text."""
return show_analytics(password)
def export_leads_to_csv():
"""Export all leads to CSV format."""
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("SELECT email, country, currency, breed, created_at FROM leads ORDER BY created_at DESC")
rows = cur.fetchall()
conn.close()
import csv
from io import StringIO
output = StringIO()
writer = csv.writer(output)
writer.writerow(["Email", "Country", "Currency", "Breed", "Created At"])
writer.writerows(rows)
return output.getvalue()
def export_leads_wrapper():
"""Export leads to CSV file for download."""
import tempfile
csv_data = export_leads_to_csv()
temp = tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8')
temp.write(csv_data)
temp.close()
return temp.name
def export_calculations_wrapper():
"""Export calculations to CSV file for download."""
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
SELECT email, breed, birds, total_days, rounded_bags, bag_size, total_cost, created_at
FROM calculations
ORDER BY created_at DESC
""")
rows = cur.fetchall()
conn.close()
import csv
import tempfile
temp = tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8')
writer = csv.writer(temp)
writer.writerow(["Email", "Breed", "Birds", "Total Days", "Bags", "Bag Size (kg)", "Total Cost", "Created At"])
writer.writerows(rows)
temp.close()
return temp.name
# ============================================================
# CSS - MINT GREEN & EGG YELLOW DESIGN SYSTEM
# ============================================================
CSS = """
:root {
--app-bg-main: #f4f7f5;
--app-card-surface: #ffffff;
--brand-primary-mint: #00a86b;
--brand-dark-charcoal: #0b3022;
--brand-accent-yellow: #ffb800;
--ui-border-muted: #d6e0db;
--text-helper: #5a6e65;
/* Compatibility aliases used throughout the app */
--mint: var(--brand-primary-mint);
--mint-dark: var(--brand-dark-charcoal);
--mint-soft: #eaf8f1;
--yellow: var(--brand-accent-yellow);
--yellow-soft: #fff7db;
--surface: var(--app-card-surface);
--page: var(--app-bg-main);
--border: var(--ui-border-muted);
--muted: var(--text-helper);
--danger: #b42318;
}
/* ============================================================
HIDE HUGGING FACE SPACE HEADER
============================================================ */
#huggingface-space-header,
#space-header__collapse,
.hf-header,
[data-testid="header"],
.huggingface-space-header {
display: none !important;
visibility: hidden !important;
height: 0 !important;
min-height: 0 !important;
max-height: 0 !important;
padding: 0 !important;
margin: 0 !important;
border: 0 !important;
overflow: hidden !important;
pointer-events: none !important;
}
/* =========================
GLOBAL MOBILE-FIRST UI
========================= */
html, body {
margin: 0 !important;
padding: 0 !important;
background: var(--page) !important;
color: var(--mint-dark) !important;
color-scheme: light !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif !important;
-webkit-text-size-adjust: 100%;
}
body,
.gradio-container,
.gradio-container > .main,
.gradio-container .block,
.gradio-container .gr-group,
.gradio-container .gr-box,
.gradio-container .gr-panel {
background: var(--page) !important;
color: var(--mint-dark) !important;
}
.gradio-container {
width: 100% !important;
max-width: 1180px !important;
margin: 0 auto !important;
padding: 0 12px 48px !important;
box-sizing: border-box !important;
color-scheme: light !important;
--body-background-fill: #f4f7f5 !important;
--body-background-fill-dark: #f4f7f5 !important;
--body-text-color: #0b3022 !important;
--body-text-color-dark: #0b3022 !important;
--body-text-color-subdued: #5a6e65 !important;
--body-text-color-subdued-dark: #5a6e65 !important;
--background-fill-primary: #ffffff !important;
--background-fill-primary-dark: #ffffff !important;
--background-fill-secondary: #f4f7f5 !important;
--background-fill-secondary-dark: #f4f7f5 !important;
--border-color-primary: #d6e0db !important;
--border-color-primary-dark: #d6e0db !important;
}
/* Never force a dark theme onto the mobile browser. */
.dark body,
.dark .gradio-container,
.dark .gradio-container .block,
.dark .gradio-container .gr-group,
.dark .gradio-container .gr-box,
.dark .gradio-container .gr-panel {
background: var(--page) !important;
color: var(--mint-dark) !important;
}
h1, h2, h3, h4, p, label, span, div {
color: inherit;
}
/* =========================
HEADER
========================= */
.app-header {
background: var(--mint-dark);
color: #fff;
border-radius: 0 0 18px 18px;
padding: 18px 16px 20px;
margin: 0 -12px 16px;
}
.app-header .brand-row {
display: flex;
align-items: center;
gap: 10px;
}
.app-header .brand-icon { font-size: 30px; line-height: 1; }
.app-header h1 {
color: #fff !important;
margin: 0;
font-size: clamp(23px, 6vw, 32px);
line-height: 1.1;
font-weight: 800;
}
.app-header p {
color: rgba(255,255,255,.88) !important;
margin: 6px 0 0 40px;
font-size: 14px;
line-height: 1.45;
}
/* =========================
STATUS / FORM SECTIONS
========================= */
.status-card {
background: var(--surface);
border: 1px solid var(--border);
border-left: 4px solid var(--mint);
border-radius: 12px;
padding: 12px 14px;
margin-bottom: 12px;
font-size: 13px;
}
.status-card strong { color: var(--mint-dark) !important; }
.status-card a { color: var(--mint) !important; font-weight: 700; }
.form-section {
background: var(--surface) !important;
border: 1px solid var(--border) !important;
border-radius: 14px !important;
margin-bottom: 12px !important;
overflow: visible !important;
padding: 14px !important;
box-shadow: 0 2px 8px rgba(11,48,34,.04) !important;
}
.section-heading {
display: flex;
align-items: center;
gap: 9px;
margin: 0 0 12px;
color: var(--mint-dark) !important;
font-size: 17px;
font-weight: 800;
}
.step-number {
width: 28px;
height: 28px;
border-radius: 50%;
background: var(--mint-dark);
color: #fff !important;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 13px;
font-weight: 800;
flex: 0 0 28px;
}
/* Gradio field controls */
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container [role="combobox"] {
background: #fff !important;
color: var(--mint-dark) !important;
border: 1px solid #C8D5CE !important;
border-radius: 10px !important;
min-height: 48px !important;
box-sizing: border-box !important;
font-size: 16px !important;
}
.gradio-container input:focus,
.gradio-container textarea:focus,
.gradio-container select:focus,
.gradio-container [role="combobox"]:focus-within {
border-color: var(--mint) !important;
box-shadow: 0 0 0 3px rgba(0,168,107,.16) !important;
}
.gradio-container label {
color: var(--mint-dark) !important;
font-weight: 650 !important;
}
.gradio-container .info,
.gradio-container small {
color: var(--muted) !important;
}
/* Give Weeks and Days a real touch gap on mobile. */
.age-row,
.feed-row {
gap: 10px !important;
}
.age-row > *,
.feed-row > * {
min-width: 0 !important;
}
.email-box textarea,
.email-box input {
background: #fff !important;
border: 2px solid var(--mint) !important;
}
/* =========================
PRIMARY ACTION
========================= */
.calculate-btn button {
width: 100% !important;
min-height: 52px !important;
border: 0 !important;
border-radius: 12px !important;
background: var(--mint) !important;
color: #fff !important;
font-size: 16px !important;
font-weight: 800 !important;
box-shadow: 0 5px 14px rgba(0,168,107,.20) !important;
}
.calculate-btn button:hover { background: #008F5A !important; }
/* =========================
RESULT HTML
========================= */
.results-shell {
width: 100%;
box-sizing: border-box;
color: var(--mint-dark);
}
.buy-card {
background: linear-gradient(145deg, #F1FBF6 0%, #FFFFFF 100%);
border: 2px solid var(--mint);
border-radius: 16px;
padding: 18px 16px;
text-align: center;
box-shadow: 0 5px 16px rgba(11,48,34,.08);
}
.eyebrow {
color: var(--mint) !important;
font-size: 12px;
font-weight: 800;
letter-spacing: .09em;
}
.buy-label {
margin-top: 7px;
color: var(--mint-dark) !important;
font-size: 13px;
font-weight: 800;
}
.buy-number {
color: var(--mint) !important;
font-size: clamp(62px, 18vw, 92px);
font-weight: 900;
line-height: .9;
margin-top: 2px;
}
.buy-unit {
color: var(--mint-dark) !important;
font-size: 21px;
font-weight: 900;
letter-spacing: .08em;
}
.buy-note {
margin-top: 8px;
color: var(--muted) !important;
font-size: 12px;
}
.result-context {
text-align: center;
margin: 12px 2px 6px;
color: var(--muted) !important;
font-size: 13px;
}
.result-context strong { color: var(--mint-dark) !important; }
.plain-answer {
background: #fff;
border-left: 4px solid var(--yellow);
border-radius: 10px;
padding: 11px 12px;
margin: 10px 0 12px;
font-size: 14px;
line-height: 1.5;
color: var(--mint-dark) !important;
}
.plain-answer strong { color: var(--mint-dark) !important; }
.metric-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0,1fr));
gap: 9px;
margin-bottom: 14px;
}
.metric-card {
background: #fff;
border: 1px solid var(--border);
border-radius: 12px;
padding: 11px 9px;
min-width: 0;
}
.metric-icon {
display: block;
color: var(--mint) !important;
font-size: 18px;
font-weight: 900;
}
.metric-label {
display: block;
color: var(--muted) !important;
font-size: 11px;
margin: 2px 0 3px;
}
.metric-card strong {
display: block;
color: var(--mint-dark) !important;
font-size: 17px;
line-height: 1.2;
overflow-wrap: anywhere;
}
.result-section { margin: 14px 0; }
.section-title {
color: var(--mint-dark) !important;
font-size: 14px;
font-weight: 850;
margin-bottom: 8px;
}
.table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.feed-table {
width: 100%;
min-width: 330px;
border-collapse: separate;
border-spacing: 0;
background: #fff;
border: 1px solid var(--border);
border-radius: 11px;
overflow: hidden;
font-size: 12px;
}
.feed-table th {
background: var(--mint) !important;
color: #fff !important;
padding: 9px 8px;
text-align: left;
font-weight: 800;
}
.feed-table th:not(:first-child),
.feed-table td:not(:first-child) { text-align: right; }
.feed-table td {
padding: 9px 8px;
border-top: 1px solid var(--border);
color: var(--mint-dark) !important;
white-space: nowrap;
}
.feed-table .muted { color: var(--muted) !important; font-size: 10px; }
.feed-table .total-row td {
background: var(--mint-soft) !important;
font-weight: 900 !important;
}
.feed-table .total-row td:last-child { font-size: 14px; }
.cost-card {
background: var(--yellow-soft);
border: 1px solid #EBC34A;
border-left: 4px solid var(--yellow);
border-radius: 12px;
padding: 13px 14px;
margin: 14px 0;
}
.cost-main {
color: var(--mint-dark) !important;
font-size: clamp(27px, 8vw, 38px);
line-height: 1.1;
font-weight: 900;
}
.cost-note { color: var(--muted) !important; font-size: 11px; margin-top: 5px; }
.performance-grid { display: grid; gap: 0; background: #fff; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
.performance-grid > div { display: flex; justify-content: space-between; gap: 12px; padding: 11px; border-top: 1px solid var(--border); font-size: 13px; }
.performance-grid > div:first-child { border-top: 0; }
.performance-grid span { color: var(--muted) !important; }
.performance-grid strong { color: var(--mint) !important; white-space: nowrap; }
.share-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 8px; }
.share-btn {
display: block;
text-align: center;
text-decoration: none !important;
background: var(--mint);
color: #fff !important;
border-radius: 9px;
padding: 11px 8px;
font-size: 12px;
font-weight: 800;
min-height: 44px;
box-sizing: border-box;
}
.share-btn:hover { background: #008F5A; }
.result-disclaimer {
background: #F1F6F3;
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 11px;
color: var(--muted) !important;
font-size: 10px;
line-height: 1.45;
margin-top: 14px;
}
/* =========================
BENCHMARK / REFERENCE CONTENT
========================= */
.benchmark-card {
background: var(--app-card-surface);
border: 1px solid var(--ui-border-muted);
border-radius: 14px;
padding: 14px;
margin: 16px 0 12px;
box-shadow: 0 2px 8px rgba(11,48,34,.04);
}
.benchmark-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 10px;
}
.benchmark-title {
color: var(--brand-dark-charcoal) !important;
font-size: 16px;
font-weight: 850;
}
.selected-breed-badge {
display: inline-flex;
align-items: center;
min-height: 34px;
padding: 6px 12px;
border-radius: 999px;
background: var(--brand-dark-charcoal);
color: #fff !important;
font-size: 13px;
font-weight: 800;
white-space: nowrap;
}
.benchmark-help {
color: var(--text-helper) !important;
font-size: 12px;
line-height: 1.45;
margin: 0 0 10px;
}
.benchmark-accordion { margin-top: 10px !important; }
/* Ask a Question stays visible because it is a farmer-facing feature. */
.question-card {
background: var(--app-card-surface);
border: 1px solid var(--ui-border-muted);
border-radius: 14px;
padding: 14px;
margin: 14px 0;
box-shadow: 0 2px 8px rgba(11,48,34,.04);
}
.question-heading {
color: var(--brand-dark-charcoal) !important;
font-size: 16px;
font-weight: 850;
margin-bottom: 5px;
}
.question-help {
color: var(--text-helper) !important;
font-size: 12px;
margin-bottom: 10px;
}
/* Traditional social colours: recognizable at a glance. */
.share-btn.whatsapp { background: #25D366 !important; }
.share-btn.email { background: #EA4335 !important; }
.share-btn.facebook { background: #1877F2 !important; }
.share-btn.twitter { background: #000000 !important; }
.share-btn.whatsapp:hover { background: #1ebe5d !important; }
.share-btn.email:hover { background: #d93025 !important; }
.share-btn.facebook:hover { background: #166fe5 !important; }
.share-btn.twitter:hover { background: #222 !important; }
/* Replace Gradio's default blue emphasis with the brand system. */
.gradio-container button.primary,
.gradio-container button[data-variant="primary"] {
background: var(--brand-primary-mint) !important;
color: #fff !important;
border-color: var(--brand-primary-mint) !important;
}
.gradio-container button.secondary,
.gradio-container button[data-variant="secondary"] {
background: var(--brand-dark-charcoal) !important;
color: #fff !important;
border-color: var(--brand-dark-charcoal) !important;
}
.gradio-container button:focus-visible {
outline: 3px solid rgba(255,184,0,.45) !important;
outline-offset: 2px;
}
/* =========================
COLLAPSIBLE LOWER CONTENT
========================= */
.gradio-container details,
.gradio-container .gr-accordion {
background: #fff !important;
border: 1px solid var(--border) !important;
border-radius: 12px !important;
margin-bottom: 10px !important;
overflow: hidden !important;
}
.gradio-container summary,
.gradio-container .gr-accordion > button {
color: var(--mint-dark) !important;
font-weight: 800 !important;
}
/* Dataframes: allow horizontal scrolling on phones. */
.benchmark-wrap { overflow-x: auto !important; -webkit-overflow-scrolling: touch !important; }
.benchmark-wrap .table-wrap { overflow-x: auto !important; }
/* =========================
ADMIN / FOOTER
========================= */
.admin-login {
background: #fff !important;
border: 1px solid var(--border) !important;
border-left: 4px solid var(--yellow) !important;
border-radius: 12px !important;
padding: 12px !important;
}
.admin-footer {
margin-top: 24px;
padding-top: 10px;
border-top: 1px solid var(--ui-border-muted);
}
.admin-footer summary,
.admin-footer .gr-accordion > button {
color: var(--text-helper) !important;
font-size: 12px !important;
font-weight: 650 !important;
}
.footer-note { color: var(--muted) !important; font-size: 11px; line-height: 1.5; }
/* =========================
PERFORMANCE / MOBILE POLISH
========================= */
* { box-sizing: border-box; }
img, svg { max-width: 100%; }
button, input, select, textarea { font: inherit; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
scroll-behavior: auto !important;
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
.benchmark-html { width: 100%; }
.benchmark-table { min-width: 0; font-size: 11px; }
.benchmark-table th, .benchmark-table td { padding: 8px 7px; }
.comparison-table { min-width: 620px; }
/* Desktop gets breathing room; mobile stays single-column. */
@media (min-width: 900px) {
.gradio-container { padding: 0 22px 60px !important; }
.app-header { margin-left: -22px; margin-right: -22px; padding-left: 28px; padding-right: 28px; }
.buy-number { font-size: 84px; }
.metric-grid { grid-template-columns: repeat(4,minmax(0,1fr)); }
}
@media (max-width: 480px) {
.gradio-container { padding-left: 10px !important; padding-right: 10px !important; }
.app-header { margin-left: -10px; margin-right: -10px; }
.age-row, .feed-row { gap: 12px !important; }
.metric-grid { gap: 7px; }
.metric-card { padding: 10px 8px; }
.metric-card strong { font-size: 15px; }
.performance-grid > div { font-size: 12px; }
}
"""
# ============================================================
# UI
# ============================================================
SOCIAL_PREVIEW_URL = (
"https://googlecalc-howmuchfeed.hf.space/"
"gradio_api/file=social-preview.jpg"
)
# ============================================================
# SOCIAL MEDIA META TAGS
# ============================================================
SOCIAL_META = """
<title>How Much Feed? β Broiler Feed Calculator</title>
<meta name="description" content="Calculate how much feed your broilers need, how many bags to buy, and your estimated feed cost.">
<!-- Open Graph / Facebook -->
<meta property="og:title" content="How Much Feed? β Broiler Feed Calculator">
<meta property="og:description" content="Calculate how much feed your broilers need, how many bags to buy, and your estimated feed cost.">
<meta property="og:image" content="https://huggingface.co/spaces/GoogleCalc/HowMuchFeed/resolve/main/social-preview.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:url" content="https://www.howmuchfeed.com/">
<meta property="og:type" content="website">
<meta property="og:site_name" content="How Much Feed?">
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="How Much Feed? β Broiler Feed Calculator">
<meta name="twitter:description" content="Calculate your broiler feed requirement, bags needed and estimated feed cost.">
<meta name="twitter:image" content="https://huggingface.co/spaces/GoogleCalc/HowMuchFeed/resolve/main/social-preview.jpg">
"""
with gr.Blocks(title=APP_NAME, analytics_enabled=False) as demo:
# INJECT SOCIAL META TAGS
gr.HTML(f"""
<title>How Much Feed? β Broiler Feed Calculator</title>
<meta name="description" content="Calculate how much feed your broilers need, how many bags to buy, and your estimated feed cost.">
<meta property="og:title" content="How Much Feed? β Broiler Feed Calculator">
<meta property="og:description" content="Calculate how much feed your broilers need, how many bags to buy, and your estimated feed cost.">
<meta property="og:image" content="https://huggingface.co/spaces/GoogleCalc/HowMuchFeed/resolve/main/social-preview.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:url" content="https://www.howmuchfeed.com/">
<meta property="og:type" content="website">
<meta property="og:site_name" content="How Much Feed?">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="How Much Feed? β Broiler Feed Calculator">
<meta name="twitter:description" content="Calculate your broiler feed requirement, bags needed and estimated feed cost.">
<meta name="twitter:image" content="https://huggingface.co/spaces/GoogleCalc/HowMuchFeed/resolve/main/social-preview.jpg">
""")
gr.HTML("""
<header class="app-header">
<div class="brand-row">
<div class="brand-icon">π</div>
<div>
<h1>How Much Feed?</h1>
</div>
</div>
<p>Broiler feed calculator β find out how many bags of feed you need for your birds.</p>
</header>
""")
gr.HTML("""
<div class="status-card">
<strong>β Simple farmer estimate</strong><br>
Enter your breed, number of birds, age and feed price. The calculator shows how much feed you need and the number of bags to buy.
</div>
""")
# ============================================================
# MOBILE-FIRST INPUT FORM
# ============================================================
with gr.Column(elem_classes=["mobile-form"]):
with gr.Group(elem_classes=["form-section"]):
gr.HTML('<div class="section-heading"><span class="step-number">1</span><span>π Breed & Birds</span></div>')
breed = gr.Dropdown(
choices=["Ross 308", "Cobb 500", "Arbor Acres"],
value="Ross 308",
label="Breed",
info="Choose the breed of your broilers.",
)
birds = gr.Dropdown(
choices=[25, 50, 75, 100, 150, 200, 500, 1000],
value=50,
label="Number of birds",
allow_custom_value=True,
)
with gr.Group(elem_classes=["form-section"]):
gr.HTML('<div class="section-heading"><span class="step-number">2</span><span>π
Expected Age</span></div>')
with gr.Row(elem_classes=["age-row"]):
weeks = gr.Dropdown(
choices=list(range(0, 21)), value=8, label="Weeks", scale=1
)
days = gr.Dropdown(
choices=list(range(0, 7)), value=0, label="Days", scale=1
)
with gr.Group(elem_classes=["form-section"]):
gr.HTML('<div class="section-heading"><span class="step-number">3</span><span>πΎ Feed Details</span></div>')
with gr.Row(elem_classes=["feed-row"]):
bag_size = gr.Dropdown(
choices=[10, 20, 25, 50, 100], value=25, label="Bag size (kg)", scale=1
)
price = gr.Number(
value=24000, label="Price per bag ", minimum=0, scale=1
)
with gr.Group(elem_classes=["form-section"]):
gr.HTML('<div class="section-heading"><span class="step-number">4</span><span>π Your Location</span></div>')
detected_country = detect_country_from_env() or "NG"
country_choices = ["Auto-Detect"] + [code for code, _ in COUNTRY_LIST]
country_dropdown = gr.Dropdown(
choices=country_choices,
value="Auto-Detect",
label="Country",
info="Auto-Detect uses your connection location when available.",
)
country_code_state = gr.State(detected_country)
with gr.Group(elem_classes=["form-section"]):
gr.HTML('<div class="section-heading"><span class="step-number">5</span><span>π§ Email for your result</span></div>')
email = gr.Textbox(
label="Email address",
placeholder="farmer@example.com",
type="email",
elem_classes=["email-box"],
info="We'll save your calculation so you can access it later.",
)
calculate_btn = gr.Button(
"π Calculate Feed Requirement",
variant="primary",
size="lg",
elem_classes=["calculate-btn"],
)
save_status = gr.Markdown("")
# ============================================================
# RESULTS
# ============================================================
gr.Markdown("## π Your Feed Result")
result = gr.HTML(
value="""
<div class="results-shell">
<section class="buy-card">
<div class="eyebrow">YOUR FEED RESULT</div>
<div class="buy-label">BUY</div>
<div class="buy-number">β</div>
<div class="buy-unit">BAGS</div>
<div class="buy-note">Enter your flock details above to calculate.</div>
</section>
</div>
""",
elem_classes=["answer-box"],
)
# ============================================================
# REFERENCE / BENCHMARKS
# ============================================================
with gr.Group(elem_classes=["benchmark-card"]):
with gr.Row(elem_classes=["benchmark-heading"]):
gr.HTML('<div class="benchmark-title">π Selected Breed Benchmark</div>')
selected_breed_badge = gr.HTML('<span class="selected-breed-badge">Ross 308</span>')
with gr.Accordion(
"π Weekly benchmark data used by the calculator",
open=False,
elem_classes=["benchmark-accordion"],
):
gr.HTML('<p class="benchmark-help">Weekly benchmark data used by the calculator for the selected breed.</p>')
benchmark_table = gr.HTML(
value=get_benchmark_html("Ross 308"),
elem_classes=["benchmark-wrap"],
)
with gr.Accordion("π Breed Comparison", open=False):
gr.Markdown("Compare Ross 308, Cobb 500 and Arbor Acres at the same age checkpoints.")
comparison_table = gr.HTML(
value=get_comparison_html(),
elem_classes=["benchmark-wrap"],
)
with gr.Accordion("π Common Broiler Breeds in Nigeria", open=False):
gr.Markdown("""
| Breed | Characteristics | Available At |
|---|---|---|
| **Ross 308** | Big chest, thick legs, very fast growth. | Agrited, Sayed, Valentine |
| **Cobb 500** | Good early growth, strong legs, solid feed conversion. | Chikun, Zartech |
| **Arbor Acres** | Balanced growth, hardy and adaptable. | Supreme, CHI, GS, Vertex, Fidan, Cascada, Orobor, Sunchi, Farm Support, Ajila |
**Tip:** Ask the hatchery which breed you are buying before using the benchmark.
""")
with gr.Accordion("π How It Works & Data Sources", open=False):
gr.Markdown(f"""
**How the estimate works**
- Your weeks + days are converted to total days.
- Breed-specific cumulative feed benchmarks estimate total feed per bird.
- Starter feed is estimated through Day {STARTER_END_DAY}; feed after that is treated as finisher.
- Exact bags = total feed Γ· bag size.
- Bags to buy = exact bags rounded up to the next whole bag.
- Feed cost = bags to buy Γ your current price per bag.
**Data sources**
- Ross 308 β Aviagen (2022)
- Cobb 500 β Cobb-Vantress
- Arbor Acres β Aviagen (2022)
**Important:** This is a benchmark estimate. Actual feed use varies with management, feed quality, environment and bird performance.
""")
# ============================================================
# ASK A QUESTION
# ============================================================
with gr.Column(elem_classes=["question-card"]):
gr.HTML('<div class="question-heading">β Ask a Question</div>')
gr.HTML('<div class="question-help">Ask a simple poultry-feed question. Your question can also help us improve the calculator.</div>')
question = gr.Textbox(
label="Your question",
placeholder="How many bags of feed for 100 broilers for 6 weeks?",
lines=3,
)
ask_btn = gr.Button("π¬ Get Answer", variant="secondary", size="lg")
question_answer = gr.Markdown("")
# ============================================================
# FOOTER + LOW-PROMINENCE ADMIN
# ============================================================
gr.HTML("""
<div class="footer-note" style="margin-top:18px; text-align:center;">
π <strong>How Much Feed?</strong> β A simple broiler feed planning tool.<br>
Feed estimates are guides and should be adjusted to actual broiler performance.
</div>
""")
with gr.Accordion("π Admin", open=False, elem_classes=["admin-footer"]):
gr.Markdown("Password-protected analytics and CSV exports.")
with gr.Column(elem_classes=["admin-login"]):
admin_password_input = gr.Textbox(
label="Admin Password", placeholder="Enter password...", type="password"
)
login_btn = gr.Button("View Dashboard", variant="secondary")
admin_output = gr.Markdown("π Enter the admin password to view analytics.")
with gr.Row():
export_leads_btn = gr.Button("π₯ Export Leads (CSV)", variant="secondary")
export_leads_output = gr.File(label="Leads CSV")
with gr.Row():
export_calc_btn = gr.Button("π₯ Export Calculations (CSV)", variant="secondary")
export_calc_output = gr.File(label="Calculations CSV")
# ============================================================
# EVENTS
# ============================================================
breed.change(
fn=update_benchmark,
inputs=[breed],
outputs=[benchmark_table],
)
breed.change(
fn=update_selected_breed_badge,
inputs=[breed],
outputs=[selected_breed_badge],
)
country_dropdown.change(
fn=on_country_change_handler,
inputs=[country_dropdown],
outputs=[country_code_state, price],
)
def calculate_wrapper(birds, weeks, days, bag_size, price_per_bag, email, country_code_state, breed, request: gr.Request):
if not country_code_state:
country_code_state = "NG"
return calculate_feed(
birds, weeks, days, bag_size, price_per_bag,
email, country_code_state, breed, request
)
calculate_btn.click(
fn=calculate_wrapper,
inputs=[birds, weeks, days, bag_size, price, email, country_code_state, breed],
outputs=[result, save_status],
)
ask_btn.click(
fn=answer_farmer_question,
inputs=[question, email, breed],
outputs=[question_answer],
)
login_btn.click(
fn=admin_login,
inputs=[admin_password_input],
outputs=[admin_output],
)
export_leads_btn.click(
fn=export_leads_wrapper,
inputs=[],
outputs=[export_leads_output],
)
export_calc_btn.click(
fn=export_calculations_wrapper,
inputs=[],
outputs=[export_calc_output],
)
def track_visit_async(request: gr.Request):
# Do not make the first page render wait for analytics I/O.
threading.Thread(target=track_visit, args=(request,), daemon=True).start()
demo.load(fn=track_visit_async, inputs=None, outputs=None)
# ============================================================
# START APP
# ============================================================
# ============================================================
# SEO SITEMAP
# ============================================================
SITEMAP_XML = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.howmuchfeed.com/</loc>
</url>
</urlset>
"""
app = FastAPI()
# ============================================================
# SEO METADATA FIX - Remove Duplicate OG Tags
# ============================================================
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
import re
class SEOMetadataMiddleware(BaseHTTPMiddleware):
"""Intercept HTML responses and fix duplicate OG tags."""
async def dispatch(self, request, call_next):
response = await call_next(request)
# Only process HTML responses
content_type = response.headers.get("content-type", "")
if "text/html" in content_type:
try:
# Read the response body
body = b""
async for chunk in response.body_iterator:
body += chunk
html = body.decode("utf-8")
# Remove the default Gradio OG image
default_og = r'<meta\s+property="og:image"\s+content="https://raw\.githubusercontent\.com/gradio-app/gradio/main/js/_website/src/lib/assets/img/header-image\.jpg"\s*/>'
html = re.sub(default_og, '', html)
# Remove default Twitter image
default_twitter = r'<meta\s+name="twitter:image"\s+content="https://raw\.githubusercontent\.com/gradio-app/gradio/main/js/_website/src/lib/assets/img/header-image\.jpg"\s*/>'
html = re.sub(default_twitter, '', html)
# Check if correct OG image exists
correct_og = 'content="https://huggingface.co/spaces/GoogleCalc/HowMuchFeed/resolve/main/social-preview.jpg"'
if correct_og not in html:
# Inject it
og_tag = '<meta property="og:image" content="https://huggingface.co/spaces/GoogleCalc/HowMuchFeed/resolve/main/social-preview.jpg">'
html = html.replace('<head>', f'<head>\n {og_tag}')
return Response(
content=html.encode("utf-8"),
status_code=response.status_code,
headers=dict(response.headers),
media_type=response.media_type,
)
except Exception as e:
print(f"β οΈ SEO middleware error: {e}")
return response
return response
# Add the middleware AFTER the app is created
app.add_middleware(SEOMetadataMiddleware)
@app.get("/sitemap.xml")
def sitemap():
return Response(
content=SITEMAP_XML,
media_type="application/xml"
)
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
demo.launch(
server_name="0.0.0.0",
server_port=port,
ssr_mode=False,
theme=gr.themes.Base(),
css=CSS,
head=SOCIAL_META,
footer_links=[]
) |