File size: 70,829 Bytes
9c465fe 8a60efe 9c465fe 8a60efe fdc39c7 8a60efe 9ad4f72 3454374 8a60efe fdc39c7 9347d6f fdc39c7 8a60efe 554c506 17224d8 9f84c44 3454374 8a60efe 93fd919 3454374 665fbfd 3454374 8a60efe 32b4040 93fd919 9c465fe 8a60efe efb605d 8a60efe fd29ef8 3454374 8a60efe 9f84c44 9c465fe 8a60efe 9c465fe 9f84c44 9c465fe 554c506 9f84c44 8a60efe 9c465fe 8a60efe 3454374 8a60efe 3454374 8a60efe 3454374 a0fd364 8a60efe 9c465fe 93fd919 a0fd364 93fd919 0d209c2 93fd919 a0fd364 93fd919 a0fd364 93fd919 a0fd364 93fd919 a0fd364 93fd919 e43ea9d 93fd919 e43ea9d 93fd919 e43ea9d 4028cdf 93fd919 fdc39c7 665fbfd fdc39c7 9c465fe 8a60efe 32b4040 9c465fe 8a60efe 32b4040 8a60efe 9c465fe 8a60efe fdc39c7 8a60efe fdc39c7 8a60efe 146a5aa 9c465fe 146a5aa 8a60efe 9c465fe 8a60efe 146a5aa 8a60efe fdc39c7 8a60efe fdc39c7 8a60efe fdc39c7 9347d6f fdc39c7 9347d6f 8a60efe fdc39c7 e4a72c8 146a5aa 8a60efe 146a5aa 9ad4f72 8a60efe 146a5aa aeb584b 8a60efe 146a5aa aeb584b 8a60efe 9ad4f72 146a5aa 9ad4f72 146a5aa 9c465fe 9ad4f72 146a5aa 9c465fe 8a60efe 9c465fe 8a60efe fd29ef8 9c465fe 8a60efe 9f84c44 8a60efe 9f84c44 8a60efe 9f84c44 9c465fe 9f84c44 634e5b4 554c506 9c465fe 634e5b4 554c506 634e5b4 9f84c44 9c465fe 9f84c44 554c506 9c465fe 554c506 fdc39c7 9f84c44 554c506 9f84c44 554c506 fdc39c7 554c506 fdc39c7 554c506 fdc39c7 554c506 fdc39c7 554c506 fdc39c7 554c506 8a60efe 17224d8 8a60efe 554c506 17224d8 554c506 8a60efe 93fd919 8a60efe 32b4040 9c465fe 8a60efe 32b4040 9c465fe 8a60efe 9c465fe 8a60efe fdc39c7 5de8aaf 665fbfd 3d48b97 665fbfd 5de8aaf 665fbfd 5de8aaf fdc39c7 32b4040 8a60efe 9c465fe a4099a4 fdc39c7 8a60efe 32b4040 8a60efe 9c465fe 8a60efe 629b9ba 17224d8 554c506 93fd919 17224d8 93fd919 1d7fb79 93fd919 1d7fb79 1e2e647 554c506 12aa95e 1e2e647 554c506 12aa95e 554c506 12aa95e 554c506 12aa95e 554c506 12aa95e 1e2e647 fdc39c7 554c506 32b4040 8a60efe 554c506 8a60efe 9c465fe 8a60efe 9c465fe 3454374 9c465fe 3454374 9c465fe 3454374 be95560 3454374 be95560 3454374 be95560 3454374 9c465fe fd29ef8 9c465fe 3454374 9c465fe 8a60efe 3454374 8a60efe 3454374 93fd919 3454374 93fd919 8a60efe 9c465fe 93fd919 3454374 8a60efe 93fd919 3454374 93fd919 3454374 93fd919 3454374 93fd919 8a60efe fd29ef8 8a60efe fd29ef8 8a60efe fd29ef8 8a60efe fd29ef8 8a60efe df5b94a | 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 | from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from typing import Optional
import pandas as pd
from PIL import Image
import torch
import numpy as np
from datetime import datetime
import os
import sys
import logging
import builtins
import open_clip
import base64
from io import BytesIO
from dotenv import load_dotenv
import requests
from difflib import SequenceMatcher
from supabase import create_client, Client
# ── Logging setup ────────────────────────────────────────────────────────────
# Force stdout/stderr to flush immediately (covers non-Docker HF Spaces runs)
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)
# Route all output through Python's logging system so uvicorn captures it
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
force=True,
)
logger = logging.getLogger(__name__)
# Suppress noisy httpx request logs (Supabase/HF HTTP calls)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
# Override built-in print so all existing print() calls also go through logging
# and are always flushed — no code changes needed elsewhere
_builtin_print = builtins.print
def print(*args, **kwargs): # noqa: A001
msg = " ".join(str(a) for a in args)
level = logging.WARNING if any(w in msg for w in ("[WARNING]", "[ERROR]")) else logging.INFO
logger.log(level, msg)
# ─────────────────────────────────────────────────────────────────────────────
# Load environment variables
load_dotenv()
THRESHOLD = 0.50 # Threshold for mushrooms
PLANT_THRESHOLD = 0.70 # High threshold for plants (very strict to avoid false matches)
MUSHROOM_THRESHOLD = 0.30 # Minimum confidence that it's actually a mushroom
# Persistent storage configuration for Hugging Face Spaces
# If /data exists (persistent storage), use it. Otherwise use local data/
PERSISTENT_DATA_DIR = "/data" if os.path.exists("/data") and os.access("/data", os.W_OK) else "data"
DATA_DIR = PERSISTENT_DATA_DIR
LOG_FILE = os.path.join(DATA_DIR, "recognition_log.csv")
SUBMISSION_LOG_FILE = os.path.join(DATA_DIR, "new_species_submissions.csv")
MUSHROOM_CSV = os.path.join(DATA_DIR, "mushrooms.csv")
PLANT_CSV = os.path.join(DATA_DIR, "plants.csv")
print(f"[INFO] Using data directory: {DATA_DIR}")
if DATA_DIR == "/data":
print("[INFO] Persistent storage enabled - changes will be saved across restarts")
else:
print("[WARNING] Using ephemeral storage - changes will be lost on restart")
print("[WARNING] Enable persistent storage in HuggingFace Space settings for data persistence")
# Copy initial CSV files to persistent storage if they don't exist
if DATA_DIR == "/data":
for filename in ["mushrooms.csv", "plants.csv", "recognition_log.csv", "new_species_submissions.csv"]:
source = os.path.join("data", filename)
dest = os.path.join(DATA_DIR, filename)
if os.path.exists(source) and not os.path.exists(dest):
import shutil
shutil.copy2(source, dest)
print(f"[INFO] Copied {filename} to persistent storage")
# Read from environment (works with Hugging Face Spaces secrets)
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
PLANTNET_API_KEY = os.getenv("PLANTNET_API_KEY", "")
SUPABASE_URL = os.getenv("SUPABASE_URL", "")
SUPABASE_KEY = os.getenv("SUPABASE_KEY", "")
MUSHROOM_OBSERVER_API_URL = "https://mushroomobserver.org/api2"
# Initialize Supabase client (optional - falls back to CSV if not configured)
supabase: Optional[Client] = None
USE_SUPABASE = False
if SUPABASE_URL and SUPABASE_KEY:
try:
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
# Test connection
supabase.table("species").select("count").limit(1).execute()
USE_SUPABASE = True
print(f"[INFO] Supabase connected successfully")
print(f"[INFO] Using Supabase for data persistence (FREE & permanent)")
except Exception as e:
print(f"[WARNING] Supabase connection failed: {e}")
print(f"[WARNING] Falling back to CSV storage")
USE_SUPABASE = False
else:
print("[INFO] Supabase not configured - using CSV storage")
print("[INFO] Add SUPABASE_URL and SUPABASE_KEY to .env for permanent data storage")
# Print API key status at startup (first 10 chars only for security)
if OPENROUTER_API_KEY:
print(f"[INFO] OpenRouter API Key loaded: {OPENROUTER_API_KEY[:10]}...")
else:
print("[WARNING] OpenRouter API Key not found. VLM fallback will be disabled.")
if PLANTNET_API_KEY:
print(f"[INFO] PlantNet API Key loaded: {PLANTNET_API_KEY[:10]}...")
else:
print("[WARNING] PlantNet API Key not found. PlantNet identification will be disabled.")
# MCC Location options
MCC_LOCATIONS = ["QSC", "BOTANY TANK", "MMIP", "CANTEEN", "ANDERSON HALL"]
# Default coordinates for MCC locations
MCC_LOCATION_COORDS = {
"QSC": (12.92000, 80.12100),
"BOTANY TANK": (12.92050, 80.12080),
"MMIP": (12.91900, 80.12000),
"CANTEEN": (12.91800, 80.11900),
"ANDERSON HALL": (12.92100, 80.12200),
}
# Load BioCLIP model
print("[INFO] Loading BioCLIP model (may take a moment)...")
model, _, preprocess = open_clip.create_model_and_transforms('hf-hub:imageomics/bioclip')
tokenizer = open_clip.get_tokenizer('hf-hub:imageomics/bioclip')
# Set model to evaluation mode (important for consistent predictions)
model.eval()
print("[INFO] BioCLIP model loaded and set to evaluation mode")
def load_species_from_supabase():
"""Load species from Supabase and convert to pandas DataFrames"""
try:
print("[INFO] Loading species from Supabase...")
# Load mushrooms
mushroom_response = supabase.table("species").select("*").eq("species_type", "mushroom").execute()
mushrooms = []
for item in mushroom_response.data:
mushrooms.append({
"sno": item["sno"],
"species": item["species_name"],
"location": item["location"],
"lat": item["latitude"],
"lon": item["longitude"]
})
mushroom_df = pd.DataFrame(mushrooms) if mushrooms else pd.DataFrame(columns=["sno", "species", "location", "lat", "lon"])
# Load plants
plant_response = supabase.table("species").select("*").eq("species_type", "plant").execute()
plants = []
for item in plant_response.data:
plants.append({
"sno": item["sno"],
"species": item["species_name"],
"location": item["location"],
"lat": item["latitude"],
"lon": item["longitude"]
})
plant_df = pd.DataFrame(plants) if plants else pd.DataFrame(columns=["sno", "species", "location", "lat", "lon"])
print(f"[INFO] Loaded from Supabase: {len(mushroom_df)} mushrooms, {len(plant_df)} plants")
return mushroom_df, plant_df
except Exception as e:
print(f"[ERROR] Failed to load from Supabase: {e}")
print(f"[INFO] Falling back to CSV...")
return None, None
# Load species databases (from Supabase if available, otherwise CSV)
if USE_SUPABASE:
mushroom_db, plant_db = load_species_from_supabase()
if mushroom_db is None or plant_db is None:
# Fallback to CSV
mushroom_db = pd.read_csv(MUSHROOM_CSV)
plant_db = pd.read_csv(PLANT_CSV)
else:
# Use CSV
mushroom_db = pd.read_csv(MUSHROOM_CSV)
plant_db = pd.read_csv(PLANT_CSV)
print(f"[INFO] Loaded from CSV: {len(mushroom_db)} mushrooms, {len(plant_db)} plants")
# Create labels for species identification
mushroom_labels = [species for species in mushroom_db["species"]]
mushroom_labels.append("unknown species")
plant_labels = [species for species in plant_db["species"]]
plant_labels.append("unknown species")
# Labels for general classification (to detect plants vs mushrooms)
general_labels = [
"mushroom",
"fungus",
"toadstool",
"plant",
"flower",
"tree",
"leaf",
"shrub",
"herb",
"foliage",
"vegetation",
"blossom",
"crop",
"grass",
"car",
"vehicle",
"person",
"animal",
"building",
"food",
"object",
"landscape"
]
# Initialize log file
if not os.path.exists(LOG_FILE):
log_df = pd.DataFrame(columns=["timestamp", "species", "confidence", "location", "lat", "lon", "status"])
log_df.to_csv(LOG_FILE, index=False)
# Initialize submissions log file
if not os.path.exists(SUBMISSION_LOG_FILE):
submissions_df = pd.DataFrame(columns=["timestamp", "species_name", "location", "user_id", "user_email", "notes", "status"])
submissions_df.to_csv(SUBMISSION_LOG_FILE, index=False)
# Initialize FastAPI
app = FastAPI(title="Mushroom Recognition API", version="1.0.0")
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def log_recognition(species, confidence, location="N/A", lat="N/A", lon="N/A", status="success"):
"""Log recognition to Supabase (if available) and CSV"""
log_entry = {
"species_name": species,
"confidence": float(confidence),
"location": location,
"latitude": str(lat),
"longitude": str(lon),
"status": status
}
# Log to Supabase if available
if USE_SUPABASE:
try:
supabase.table("recognition_logs").insert(log_entry).execute()
except Exception as e:
print(f"[WARNING] Failed to log to Supabase: {e}")
# Also log to CSV as backup
csv_log_entry = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"species": species,
"confidence": confidence,
"location": location,
"lat": lat,
"lon": lon,
"status": status
}
log_df = pd.read_csv(LOG_FILE)
new_row_df = pd.DataFrame([csv_log_entry])
log_df = pd.concat([log_df, new_row_df], ignore_index=True)
log_df.to_csv(LOG_FILE, index=False)
def log_new_species_submission(species_name, location, user_id="", user_email="", notes=""):
submission_entry = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"species_name": species_name,
"location": location,
"user_id": user_id,
"user_email": user_email,
"notes": notes,
"status": "pending"
}
submissions_df = pd.read_csv(SUBMISSION_LOG_FILE)
submissions_df = pd.concat([submissions_df, pd.DataFrame([submission_entry])], ignore_index=True)
submissions_df.to_csv(SUBMISSION_LOG_FILE, index=False)
return submission_entry
def identify_with_plantnet(image: Image.Image, species_type="plant"):
"""
Identify plants using PlantNet API
Args:
image: PIL Image object
species_type: Type of species (should be "plant")
Returns:
tuple: (species_idx, species_name, found_in_db, species_type)
"""
if not PLANTNET_API_KEY:
print("[PlantNet] API key not configured, skipping PlantNet identification")
return None, "PlantNet API key not configured", False, species_type
if species_type != "plant":
print(f"[PlantNet] Skipping - PlantNet only works for plants, not {species_type}")
return None, "PlantNet only identifies plants", False, species_type
print(f"[PlantNet] Starting PlantNet identification...")
try:
# Convert image to JPEG bytes
buffered = BytesIO()
image.save(buffered, format="JPEG", quality=90)
buffered.seek(0)
# PlantNet API endpoint - using "k-indian-subcontinent" project for Indian plants
# Available options: "k-world-flora" (82920 species), "k-indian-subcontinent" (7469 species)
# See full list at: https://my-api.plantnet.org/v2/projects
api_url = f"https://my-api.plantnet.org/v2/identify/k-indian-subcontinent"
# Prepare the multipart form data
files = {
'images': ('plant.jpg', buffered, 'image/jpeg')
}
params = {
'api-key': PLANTNET_API_KEY
# Note: 'organs' parameter not supported by k-indian-subcontinent project
}
# Make API request
response = requests.post(api_url, files=files, params=params, timeout=30)
# Check for errors
if response.status_code == 401:
print("[PlantNet ERROR] Invalid API key - check your .env file")
return None, "Invalid PlantNet API key", False, species_type
elif response.status_code == 400:
error_detail = response.text[:200] if response.text else "Bad request"
print(f"[PlantNet ERROR] 400 Bad Request: {error_detail}")
# Check if API key is still placeholder
if PLANTNET_API_KEY.startswith("your_"):
print("[PlantNet ERROR] API key appears to be a placeholder. Get your key from https://my.plantnet.org/")
return None, "PlantNet API key not configured (placeholder detected)", False, species_type
return None, f"PlantNet API error 400: {error_detail}", False, species_type
elif response.status_code == 429:
print("[PlantNet ERROR] API quota exceeded (500/day limit)")
return None, "PlantNet API quota exceeded", False, species_type
elif response.status_code != 200:
error_detail = response.text[:200] if response.text else "Unknown error"
print(f"[PlantNet ERROR] Status {response.status_code}: {error_detail}")
return None, f"PlantNet API error: {response.status_code}", False, species_type
result = response.json()
# Log the response for debugging
print(f"[PlantNet DEBUG] Response status: {response.status_code}")
# Check if we got results
if 'results' not in result or len(result['results']) == 0:
print("[PlantNet] No matches found")
return None, "No plant matches found", False, species_type
# Get the best match
best_match = result['results'][0]
score = best_match.get('score', 0.0)
species_info = best_match.get('species', {})
# Get scientific name
scientific_name = species_info.get('scientificNameWithoutAuthor',
species_info.get('scientificName', '')).strip()
# Get common names if available
common_names = species_info.get('commonNames', [])
common_name = common_names[0] if common_names else ""
# Get family and genus
family = species_info.get('family', {}).get('scientificNameWithoutAuthor', '')
genus = species_info.get('genus', {}).get('scientificNameWithoutAuthor', '')
print(f"[PlantNet DEBUG] Best match: {scientific_name}")
print(f"[PlantNet DEBUG] Common names: {common_names[:5]}...")
print(f"[PlantNet DEBUG] Family: {family}, Genus: {genus}")
print(f"[PlantNet DEBUG] Confidence: {score:.3f}")
# Try to match with our database
print(f"[PlantNet DEBUG] Checking against {len(plant_db)} plants in local DB...")
for idx, row in plant_db.iterrows():
db_species = row['species'].lower().strip()
# Check scientific name
if scientific_name.lower() == db_species:
print(f"[PlantNet] Exact scientific name match: {row['species']}")
return idx, row['species'], True, species_type
# Check ALL common names
for c_name in common_names:
if c_name.lower() == db_species:
print(f"[PlantNet] Common name match ('{c_name}'): {row['species']}")
return idx, row['species'], True, species_type
# SUBSTRING MATCHING (New Fix)
# If DB has "Ocimum gratissimum (African basil)" and PlantNet gives "Ocimum gratissimum"
if scientific_name.lower() in db_species and len(scientific_name) > 4:
print(f"[PlantNet] Substring match (Scientific in DB): {row['species']}")
return idx, row['species'], True, species_type
# If DB has "Ocimum gratissimum (African basil)" and PlantNet gives "African basil"
for c_name in common_names:
if c_name.lower() in db_species and len(c_name) > 4:
print(f"[PlantNet] Substring match (Common '{c_name}' in DB): {row['species']}")
return idx, row['species'], True, species_type
# Try fuzzy matching with genus/species parts
if scientific_name:
for idx, row in plant_db.iterrows():
db_species = row['species'].lower().strip()
scientific_lower = scientific_name.lower()
# Check if genus matches
if genus and genus.lower() in db_species:
similarity = SequenceMatcher(None, scientific_lower, db_species).ratio()
if similarity > 0.7:
print(f"[PlantNet] Fuzzy match (genus + similarity): {row['species']} (sim: {similarity:.2f})")
return idx, row['species'], True, species_type
# Not found in our database, but we have a PlantNet identification
display_name = f"{scientific_name}" + (f" ({common_name})" if common_name else "")
print(f"[PlantNet] Identified as '{display_name}' but NOT in MCC database")
return None, display_name, False, species_type
except requests.exceptions.Timeout:
return None, "PlantNet API timeout", False, species_type
except requests.exceptions.RequestException as e:
return None, f"PlantNet request error: {str(e)}", False, species_type
except Exception as e:
return None, f"PlantNet error: {str(e)}", False, species_type
_VLM_ERROR_INDICATORS = [
"vlm returned", "api error", "error:", "not configured",
"timeout", "unexpected response", "quota exceeded", "request error"
]
def identify_with_mushroom_observer(image: Image.Image, top_candidates: list):
"""
Cross-reference top BioCLIP mushroom candidates against Mushroom Observer API.
Queries each candidate species name to find which is best documented in MO,
then matches against our local mushroom database.
Args:
image: PIL Image (not used directly — MO has no image-upload ID endpoint)
top_candidates: list of dicts with 'species' key from BioCLIP top_matches
Returns:
tuple: (species_idx, species_name, found_in_db, species_type)
"""
print("[MushroomObserver] Starting Mushroom Observer API cross-reference...")
if not top_candidates:
print("[MushroomObserver] No candidates to cross-reference")
return None, "No candidates provided", False, "mushroom"
best_idx = None
best_species = None
best_obs_count = -1
for candidate in top_candidates:
raw_name = candidate.get("species", "").strip()
# Strip trailing numbers/suffixes like "Amanita muscaria 1" → "Amanita muscaria"
species_name = " ".join(p for p in raw_name.split() if not p.isdigit()).strip()
if not species_name or "unknown" in species_name.lower():
continue
try:
resp = requests.get(
f"{MUSHROOM_OBSERVER_API_URL}/observations",
params={"name": species_name, "format": "json", "detail": "low"},
timeout=10,
)
if resp.status_code != 200:
print(f"[MushroomObserver] HTTP {resp.status_code} for '{species_name}'")
continue
data = resp.json()
obs_count = data.get("number_of_records", 0)
print(f"[MushroomObserver] '{species_name}' → {obs_count} observations")
if obs_count > best_obs_count:
# Check if this species is in our mushroom DB
for idx, row in mushroom_db.iterrows():
db_name = row["species"].lower().strip()
if species_name.lower() in db_name or db_name.startswith(species_name.lower()):
best_obs_count = obs_count
best_idx = idx
best_species = row["species"]
break
except Exception as e:
print(f"[MushroomObserver] Error querying '{species_name}': {e}")
continue
if best_idx is not None:
print(f"[MushroomObserver] Best match: {best_species} ({best_obs_count} MO observations)")
return best_idx, best_species, True, "mushroom"
print("[MushroomObserver] No confirmed match found in MO database")
return None, "No Mushroom Observer match", False, "mushroom"
def is_vlm_error(msg: str) -> bool:
"""Return True if msg is a VLM error message rather than an actual species name."""
if not msg:
return True
return any(indicator in msg.lower() for indicator in _VLM_ERROR_INDICATORS)
def identify_with_vlm(image, species_type="mushroom"):
if not OPENROUTER_API_KEY:
print("[VLM] API key not configured, skipping VLM identification")
return None, "OpenRouter API key not configured", False, species_type
print(f"[VLM] Starting VLM identification for {species_type}...")
try:
buffered = BytesIO()
image.save(buffered, format="JPEG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
# Use appropriate database based on species type
db = mushroom_db if species_type == "mushroom" else plant_db
species_list = "\n".join([f"- {s}" for s in db["species"].tolist()])
# Build messages once so they can be reused in fallback
vlm_messages = [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{img_base64}"
}
},
{
"type": "text",
"text": f"""You are an expert {'mycologist' if species_type == 'mushroom' else 'botanist'} AI assistant. Analyze this {'mushroom/fungus' if species_type == 'mushroom' else 'plant'} image carefully and identify the species.
IMPORTANT INSTRUCTIONS:
1. Look at these key features:
{'- Cap shape, color, and texture' if species_type == 'mushroom' else '- Leaf shape, arrangement, and texture'}
{'- Gill structure and color' if species_type == 'mushroom' else '- Flower characteristics (if present)'}
{'- Stem characteristics' if species_type == 'mushroom' else '- Stem/trunk characteristics'}
- Size and proportions
- Growing environment
2. Carefully match the {'mushroom' if species_type == 'mushroom' else 'plant'} to ONE species from this list:
{species_list}
3. Respond with ONLY the exact species name from the list above - use the EXACT spelling as shown.
4. Do NOT add any explanation, description, or additional text.
5. If no species matches confidently, respond with exactly: "Unknown"
Your response (exact species name only):"""
}
]
}
]
VLM_MODELS = [
"qwen/qwen2-vl-7b-instruct:free",
"qwen/qwen2.5-vl-3b-instruct:free",
"nvidia/nemotron-nano-12b-v2-vl:free",
]
content = None
for model_name in VLM_MODELS:
print(f"[VLM DEBUG] Trying model: {model_name}")
# nemotron needs more tokens because it spends tokens on internal reasoning
max_tok = 600 if "nemotron" in model_name else 150
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": model_name,
"temperature": 0.1,
"max_tokens": max_tok,
"top_p": 0.9,
"messages": vlm_messages
},
timeout=45
)
response_data = response.json()
if "error" in response_data:
error_msg = response_data["error"].get("message", "Unknown API error")
print(f"[VLM DEBUG] Model {model_name} error: {error_msg}")
continue
if "choices" not in response_data or not response_data["choices"]:
print(f"[VLM DEBUG] Model {model_name} returned no choices (keys: {list(response_data.keys())})")
continue
content = response_data["choices"][0]["message"].get("content")
finish_reason = response_data["choices"][0].get("finish_reason", "unknown")
if content:
print(f"[VLM DEBUG] Model {model_name} succeeded. finish_reason='{finish_reason}'")
break
else:
usage = response_data.get('usage', {})
print(f"[VLM DEBUG] Model {model_name} returned null content. finish_reason='{finish_reason}'. tokens={usage.get('total_tokens', '?')}")
if not content:
return None, "VLM returned empty response", False, species_type
result = content.strip()
# Log VLM response for debugging
print(f"[VLM DEBUG] Raw response: '{result}'")
# Clean up the response - remove common extra text
result = result.split('\n')[0].strip()
if '.' in result:
result = result.split('.')[0].strip()
# Remove common prefixes
prefixes_to_remove = ["species:", "answer:", "identification:", "result:"]
for prefix in prefixes_to_remove:
if result.lower().startswith(prefix):
result = result[len(prefix):].strip()
print(f"[VLM DEBUG] Cleaned response: '{result}'")
# Try exact or substring match first
for idx, species in enumerate(db["species"]):
if species.lower() == result.lower():
print(f"[VLM DEBUG] Exact match found: {species}")
return idx, species, True, species_type
if species.lower() in result.lower() or result.lower() in species.lower():
print(f"[VLM DEBUG] Substring match found: {species}")
return idx, species, True, species_type
# Try fuzzy matching with high threshold (0.85 similarity)
best_match_idx = None
best_match_score = 0.0
for idx, species in enumerate(db["species"]):
similarity = SequenceMatcher(None, species.lower(), result.lower()).ratio()
if similarity > best_match_score:
best_match_score = similarity
best_match_idx = idx
print(f"[VLM DEBUG] Best fuzzy match: {db.iloc[best_match_idx]['species'] if best_match_idx is not None else 'None'} (similarity: {best_match_score:.2f})")
# If we found a good match (85% or higher similarity)
if best_match_score >= 0.85:
matched_species = db.iloc[best_match_idx]["species"]
print(f"[VLM DEBUG] Fuzzy match accepted: {matched_species}")
return best_match_idx, matched_species, True, species_type
print(f"[VLM DEBUG] No match found, returning: {result}")
return None, result, False, species_type
except Exception as e:
return None, f"Error: {str(e)}", False, species_type
def recognize_species_internal(image: Image.Image):
# Clear any potential cached gradients (though we use no_grad, being safe)
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Step 1: General classification - check if it's a plant or mushroom
image_input = preprocess(image).unsqueeze(0)
general_text_input = tokenizer(general_labels)
with torch.no_grad():
image_features = model.encode_image(image_input)
general_text_features = model.encode_text(general_text_input)
image_features_norm = image_features / image_features.norm(dim=-1, keepdim=True)
general_text_features_norm = general_text_features / general_text_features.norm(dim=-1, keepdim=True)
general_scores = (100.0 * image_features_norm @ general_text_features_norm.T).softmax(dim=-1)
# Determine what type of species it is
general_idx = general_scores.argmax().item()
general_confidence = general_scores[0][general_idx].item()
top_prediction = general_labels[general_idx]
# Calculate combined scores for mushroom and plant categories
mushroom_indices = [i for i, label in enumerate(general_labels) if label in ["mushroom", "fungus", "toadstool"]]
plant_indices = [i for i, label in enumerate(general_labels) if label in ["plant", "flower", "tree", "leaf", "shrub", "herb", "foliage", "vegetation", "blossom", "crop", "grass"]]
mushroom_score = sum(general_scores[0][i].item() for i in mushroom_indices)
plant_score = sum(general_scores[0][i].item() for i in plant_indices)
# Debug logging
print(f"[Classification] Top prediction: {top_prediction} ({general_confidence:.3f})")
print(f"[Classification] Mushroom category score: {mushroom_score:.3f}")
print(f"[Classification] Plant category score: {plant_score:.3f}")
# Determine initial classification based on combined scores
initial_type = "mushroom" if mushroom_score > plant_score else "plant"
# If both scores are very low, it's neither a mushroom nor a plant
if max(mushroom_score, plant_score) < MUSHROOM_THRESHOLD:
return {
"success": False,
"message": f"This image appears to be a {top_prediction}, not a plant or mushroom. Please upload a plant or mushroom image.",
"detected_object": top_prediction,
"confidence": round(float(general_confidence), 3),
"top_matches": []
}
# DUAL-CHECK: Test against BOTH databases to verify classification
print(f"[Classification] Initial type: {initial_type}, performing dual-check...")
# Test against mushroom database
mushroom_text_input = tokenizer(mushroom_labels)
with torch.no_grad():
mushroom_text_features = model.encode_text(mushroom_text_input)
mushroom_text_features_norm = mushroom_text_features / mushroom_text_features.norm(dim=-1, keepdim=True)
mushroom_species_scores = (100.0 * image_features_norm @ mushroom_text_features_norm.T).softmax(dim=-1)
# Exclude the last "unknown species" label from best-match comparison
mushroom_known_scores = mushroom_species_scores[0][:-1]
mushroom_best_confidence = mushroom_known_scores.max().item()
mushroom_best_idx = mushroom_known_scores.argmax().item()
# Test against plant database
plant_text_input = tokenizer(plant_labels)
with torch.no_grad():
plant_text_features = model.encode_text(plant_text_input)
plant_text_features_norm = plant_text_features / plant_text_features.norm(dim=-1, keepdim=True)
plant_species_scores = (100.0 * image_features_norm @ plant_text_features_norm.T).softmax(dim=-1)
# Exclude the last "unknown species" label from best-match comparison
plant_known_scores = plant_species_scores[0][:-1]
plant_best_confidence = plant_known_scores.max().item()
plant_best_idx = plant_known_scores.argmax().item()
print(f"[Dual-Check] Mushroom DB best real-species confidence: {mushroom_best_confidence:.3f} (idx {mushroom_best_idx})")
print(f"[Dual-Check] Plant DB best real-species confidence: {plant_best_confidence:.3f} (idx {plant_best_idx})")
# If both databases are very uncertain (both < 0.15), trust the general classifier entirely
if mushroom_best_confidence < 0.15 and plant_best_confidence < 0.15:
species_type = initial_type
print(f"[Dual-Check] Both DBs uncertain — trusting general classifier: {species_type}")
if species_type == "mushroom":
db = mushroom_db
labels = mushroom_labels
scores = mushroom_species_scores
idx = mushroom_best_idx
else:
db = plant_db
labels = plant_labels
scores = plant_species_scores
idx = plant_best_idx
# Only override the general classifier if one DB is clearly more confident AND
# the general classifier doesn't strongly disagree (mushroom_score or plant_score > 0.5)
elif abs(mushroom_best_confidence - plant_best_confidence) > 0.15:
if plant_best_confidence > mushroom_best_confidence:
# Only override to plant if general classifier doesn't strongly say mushroom
if mushroom_score >= 0.5:
species_type = initial_type # Respect the strong general classification
print(f"[Dual-Check] Plant DB higher but general classifier strongly says mushroom ({mushroom_score:.3f}) — keeping mushroom")
db = mushroom_db
labels = mushroom_labels
scores = mushroom_species_scores
idx = mushroom_best_idx
else:
species_type = "plant"
db = plant_db
labels = plant_labels
scores = plant_species_scores
idx = plant_best_idx
print(f"[Dual-Check] Overriding to PLANT based on higher real-species confidence")
else:
# Only override to mushroom if general classifier doesn't strongly say plant
if plant_score >= 0.5:
species_type = initial_type
print(f"[Dual-Check] Mushroom DB higher but general classifier strongly says plant ({plant_score:.3f}) — keeping plant")
db = plant_db
labels = plant_labels
scores = plant_species_scores
idx = plant_best_idx
else:
species_type = "mushroom"
db = mushroom_db
labels = mushroom_labels
scores = mushroom_species_scores
idx = mushroom_best_idx
print(f"[Dual-Check] Overriding to MUSHROOM based on higher real-species confidence")
else:
# Use initial classification if confidence is similar
species_type = initial_type
if species_type == "mushroom":
db = mushroom_db
labels = mushroom_labels
scores = mushroom_species_scores
idx = mushroom_best_idx
else:
db = plant_db
labels = plant_labels
scores = plant_species_scores
idx = plant_best_idx
print(f"[Dual-Check] Using initial classification: {species_type}")
print(f"[Classification] Final selected type: {species_type}")
# Step 2: Get species-level results (already computed in dual-check)
confidence = scores[0][idx].item()
# UNCERTAINTY CHECK: If top matches are very close, it means system is uncertain
# Get top 3 scores to check spread
top_3_scores = scores[0].topk(3)[0]
if len(top_3_scores) >= 2:
score_diff = top_3_scores[0].item() - top_3_scores[1].item()
print(f"[Uncertainty Check] Top score: {top_3_scores[0].item():.3f}, 2nd: {top_3_scores[1].item():.3f}, diff: {score_diff:.3f}")
# If difference < 0.10 (10%), the model is very uncertain
if score_diff < 0.10:
print(f"[WARNING] Model is uncertain - top matches too similar (diff: {score_diff:.3f})")
confidence = confidence * 0.7 # Reduce confidence score
print(f"[Uncertainty] Adjusted confidence: {confidence:.3f}")
# Get top 5 matches
top_k = min(5, len(scores[0]))
top_scores, top_indices = scores[0].topk(top_k)
top_matches = []
for i in range(top_k):
match_idx = top_indices[i].item()
match_score = top_scores[i].item()
if match_idx < len(labels) - 1:
top_matches.append({
"species": db.iloc[match_idx]['species'],
"confidence": round(float(match_score), 3)
})
else:
top_matches.append({
"species": "Unknown species",
"confidence": round(float(match_score), 3)
})
# Check if unknown or low confidence (use different thresholds for plants vs mushrooms)
threshold_to_use = PLANT_THRESHOLD if species_type == "plant" else THRESHOLD
print(f"[BioCLIP] Best match: {labels[idx] if idx < len(labels) else 'unknown'} with confidence {confidence:.3f}")
print(f"[BioCLIP] Required threshold for {species_type}: {threshold_to_use}")
if idx == len(labels)-1 or confidence < threshold_to_use:
print(f"[BioCLIP] Low confidence ({confidence:.3f}) or unknown species detected (threshold: {threshold_to_use})")
log_recognition("Unknown", confidence, status="not_found")
# Try PlantNet for plants (if available)
if species_type == "plant" and PLANTNET_API_KEY:
print(f"[BioCLIP] Attempting PlantNet identification...")
pn_idx, pn_species, pn_found, pn_type = identify_with_plantnet(image, species_type)
if pn_idx is not None and pn_found:
print(f"[PlantNet] Successfully identified: {pn_species} (found in database)")
row = plant_db.iloc[pn_idx]
log_recognition(row['species'], 0.90, row['location'], row['lat'], row['lon'], status="plantnet_success")
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": species_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": 0.90,
"identified_by": "PlantNet API",
"top_matches": top_matches
}
elif pn_idx is None and not pn_found and "error" not in pn_species.lower() and "not configured" not in pn_species.lower():
# PlantNet identified but not in our database
print(f"[PlantNet] Identified: {pn_species} (NOT in MCC database)")
log_recognition(pn_species, 0.90, status="not_at_mcc")
return {
"success": True,
"found_in_database": False,
"identified_species": pn_species,
"species_type": species_type,
"confidence": 0.90,
"message": f"This plant ({pn_species}) is not available in the MCC campus database",
"identified_by": "PlantNet API",
"top_matches": top_matches
}
else:
print(f"[PlantNet] Failed: {pn_species}")
# Try VLM fallback if PlantNet didn't work
if OPENROUTER_API_KEY:
print(f"[BioCLIP] Attempting VLM fallback for {species_type}...")
vlm_idx, vlm_species, found_in_db, vlm_species_type = identify_with_vlm(image, species_type)
if vlm_idx is not None and found_in_db:
print(f"[VLM] Successfully identified: {vlm_species} (found in database)")
db = mushroom_db if vlm_species_type == "mushroom" else plant_db
row = db.iloc[vlm_idx]
log_recognition(row['species'], 0.85, row['location'], row['lat'], row['lon'], status="vlm_success")
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": vlm_species_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": 0.85,
"identified_by": "Nvidia Nemotron VLM",
"top_matches": top_matches
}
else:
if is_vlm_error(vlm_species):
# VLM totally failed - try PlantNet before giving up (works for plants only)
print(f"[VLM] Error response ('{vlm_species}') - trying PlantNet fallback...")
if PLANTNET_API_KEY and vlm_species_type == "plant":
pn_idx, pn_species, pn_found, pn_type = identify_with_plantnet(image, vlm_species_type)
if pn_idx is not None and pn_found:
row = plant_db.iloc[pn_idx]
print(f"[PlantNet] Fallback succeeded: {row['species']}")
log_recognition(row['species'], 0.80, row['location'], row['lat'], row['lon'], status="plantnet_vlm_fallback")
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": pn_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": 0.80,
"identified_by": "PlantNet API (VLM fallback)",
"top_matches": top_matches
}
elif pn_species and not pn_found and pn_idx is None and "error" not in pn_species.lower() and "not configured" not in pn_species.lower() and "only identifies" not in pn_species.lower():
# PlantNet identified something but it's not in our DB
print(f"[PlantNet] Fallback identified: {pn_species} (not in MCC DB)")
log_recognition(pn_species, 0.80, status="not_at_mcc")
return {
"success": True,
"found_in_database": False,
"identified_species": pn_species,
"species_type": pn_type,
"confidence": 0.80,
"message": f"This plant ({pn_species}) is not in the MCC campus database",
"identified_by": "PlantNet API (VLM fallback)",
"top_matches": top_matches
}
else:
print(f"[PlantNet] Fallback also failed: {pn_species}")
else:
if vlm_species_type == "mushroom":
# Try Mushroom Observer API for mushrooms
print("[MushroomObserver] VLM failed for mushroom - trying Mushroom Observer API...")
mo_idx, mo_species, mo_found, mo_type = identify_with_mushroom_observer(image, top_matches)
if mo_idx is not None and mo_found:
row = mushroom_db.iloc[mo_idx]
print(f"[MushroomObserver] Fallback succeeded: {row['species']}")
log_recognition(row['species'], 0.75, row['location'], row['lat'], row['lon'], status="mushroom_observer_fallback")
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": mo_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": 0.75,
"identified_by": "Mushroom Observer API",
"top_matches": top_matches
}
else:
print(f"[MushroomObserver] Fallback also failed: {mo_species}")
elif PLANTNET_API_KEY:
print("[PlantNet] Skipping PlantNet fallback - API key not configured")
else:
print(f"[PlantNet] Skipping PlantNet fallback - not applicable for {vlm_species_type}")
# All fallbacks exhausted - use BioCLIP top match as last resort
print(f"[VLM] All fallbacks failed - using BioCLIP top match as last resort")
best_guess = next(
(m["species"] for m in top_matches if "unknown" not in m["species"].lower()),
None
)
identified = best_guess if best_guess else f"Unknown {vlm_species_type} species"
log_recognition(identified, 0.30, status="uncertain")
return {
"success": True,
"found_in_database": False,
"identified_species": identified,
"species_type": vlm_species_type,
"confidence": 0.30,
"message": f"Could not confidently identify this {vlm_species_type}. Showing best guess from visual similarity.",
"identified_by": "BioCLIP (low confidence)",
"top_matches": top_matches
}
# Species identified by VLM but not in our MCC database
print(f"[VLM] Identified: {vlm_species} (NOT in MCC database)")
log_recognition(vlm_species, 0.85, status="not_at_mcc")
return {
"success": True,
"found_in_database": False,
"identified_species": vlm_species,
"species_type": vlm_species_type,
"confidence": 0.85,
"message": f"This {vlm_species_type} ({vlm_species}) is not in the MCC campus database",
"identified_by": "VLM",
"top_matches": top_matches
}
else:
print("[BioCLIP] VLM fallback skipped - API key not configured")
return {
"success": False,
"message": "Species not found in database",
"species_type": species_type,
"confidence": round(float(confidence), 3),
"top_matches": top_matches
}
# Found in database with high confidence
row = db.iloc[idx]
print(f"[BioCLIP] High confidence match: {row['species']} ({confidence:.3f})")
# For plants, use PlantNet FIRST if available, then VLM verification
if species_type == "plant":
if not OPENROUTER_API_KEY and not PLANTNET_API_KEY:
print(f"[WARNING] No PlantNet or VLM API key - plant identification may be inaccurate!")
print(f"[WARNING] BioCLIP alone is not reliable for plants. Configure PLANTNET_API_KEY or OPENROUTER_API_KEY for better accuracy.")
# Try PlantNet first (more specialized for plants)
if PLANTNET_API_KEY:
print(f"[PlantNet] Verifying BioCLIP result: {row['species']} ({confidence:.3f})")
pn_idx, pn_species, pn_found, pn_type = identify_with_plantnet(image, species_type)
if pn_idx is not None and pn_found:
bioclip_suggestion = row['species']
plantnet_suggestion = plant_db.iloc[pn_idx]['species']
print(f"[PlantNet] Result: {plantnet_suggestion}")
print(f"[BioCLIP] Result: {bioclip_suggestion}")
# If PlantNet suggests different species, trust PlantNet (it's more specialized)
if pn_idx != idx:
print(f"[CONFLICT] PlantNet and BioCLIP disagree - using PlantNet result (more specialized)")
row = plant_db.iloc[pn_idx]
confidence = 0.90
log_recognition(row['species'], confidence, row['location'], row['lat'], row['lon'], status="plantnet_verified")
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": species_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": confidence,
"identified_by": "PlantNet API (verified)",
"bioclip_suggestion": bioclip_suggestion,
"top_matches": top_matches
}
else:
print(f"[AGREEMENT] PlantNet and BioCLIP agree on: {plantnet_suggestion}")
confidence = 0.95 # Higher confidence when both agree
log_recognition(row['species'], confidence, row['location'], row['lat'], row['lon'], status="double_verified")
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": species_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": confidence,
"identified_by": "PlantNet + BioCLIP (both agree)",
"top_matches": top_matches
}
elif pn_idx is None and not pn_found and "error" not in pn_species.lower() and "not configured" not in pn_species.lower():
# PlantNet identified something NOT in our database
print(f"[PlantNet] Identified '{pn_species}' but NOT in MCC database")
print(f"[OVERRIDE] PlantNet says this plant is not in our database")
log_recognition(pn_species, 0.90, status="not_at_mcc")
return {
"success": True,
"found_in_database": False,
"identified_species": pn_species,
"species_type": species_type,
"confidence": 0.90,
"message": f"This plant ({pn_species}) is not available in the MCC campus database",
"identified_by": "PlantNet API",
"bioclip_suggestion": row['species'],
"top_matches": top_matches
}
# For plants without PlantNet, try VLM verification as before
if species_type == "plant" and OPENROUTER_API_KEY:
print(f"[BioCLIP] Plant identified: {row['species']} with {confidence:.3f} confidence")
print(f"[VLM] Mandatory verification for plant species...")
vlm_idx, vlm_species, found_in_db, vlm_species_type = identify_with_vlm(image, species_type)
if vlm_idx is not None and found_in_db:
bioclip_suggestion = row['species']
vlm_suggestion = db.iloc[vlm_idx]['species']
print(f"[VLM] Result: {vlm_suggestion}")
print(f"[BioCLIP] Result: {bioclip_suggestion}")
# If VLM suggests different species
if vlm_idx != idx:
print(f"[CONFLICT] VLM and BioCLIP disagree - using VLM result (more accurate for plants)")
row = db.iloc[vlm_idx]
confidence = 0.85
log_recognition(row['species'], confidence, row['location'], row['lat'], row['lon'], status="vlm_verified")
# Get top matches for reference
top_k = min(5, len(scores[0]))
top_scores, top_indices = scores[0].topk(top_k)
top_matches = []
for i in range(top_k):
match_idx = top_indices[i].item()
match_score = top_scores[i].item()
if match_idx < len(labels) - 1:
top_matches.append({
"species": db.iloc[match_idx]['species'],
"confidence": round(float(match_score), 3)
})
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": species_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": confidence,
"identified_by": "Nvidia Nemotron VLM (verified)",
"bioclip_suggestion": bioclip_suggestion,
"top_matches": top_matches
}
else:
print(f"[AGREEMENT] VLM and BioCLIP agree on: {vlm_suggestion}")
elif vlm_idx is None and not found_in_db:
# VLM either identified a species not in DB, or returned an error
if is_vlm_error(vlm_species):
# VLM totally failed - trust BioCLIP's high-confidence result
print(f"[VLM] Error response ('{vlm_species}') - keeping BioCLIP result: {row['species']}")
# Fall through to the BioCLIP success return at the bottom
else:
print(f"[VLM] Identified '{vlm_species}' but NOT FOUND in MCC database")
print(f"[OVERRIDE] Treating as unknown species (VLM says not in database)")
log_recognition(vlm_species, 0.85, status="not_at_mcc")
# Get top matches
top_k = min(5, len(scores[0]))
top_scores, top_indices = scores[0].topk(top_k)
top_matches = []
for i in range(top_k):
match_idx = top_indices[i].item()
match_score = top_scores[i].item()
if match_idx < len(labels) - 1:
top_matches.append({
"species": db.iloc[match_idx]['species'],
"confidence": round(float(match_score), 3)
})
return {
"success": True,
"found_in_database": False,
"identified_species": vlm_species,
"species_type": species_type,
"confidence": 0.85,
"message": f"This plant ({vlm_species}) is not in the MCC campus database",
"identified_by": "VLM",
"bioclip_suggestion": row['species'],
"top_matches": top_matches
}
# If VLM errored, fall through to BioCLIP success return below
print(f"[BioCLIP] Successfully identified: {row['species']} (confidence: {confidence:.3f})")
log_recognition(row['species'], confidence, row['location'], row['lat'], row['lon'], status="success")
# Get top 5 matches to show alternatives
top_k = min(5, len(scores[0]))
top_scores, top_indices = scores[0].topk(top_k)
top_matches = []
for i in range(top_k):
match_idx = top_indices[i].item()
match_score = top_scores[i].item()
if match_idx < len(labels) - 1:
top_matches.append({
"species": db.iloc[match_idx]['species'],
"confidence": round(float(match_score), 3)
})
return {
"success": True,
"found_in_database": True,
"species": row['species'],
"species_type": species_type,
"location": row['location'],
"latitude": float(row['lat']),
"longitude": float(row['lon']),
"confidence": round(float(confidence), 3),
"identified_by": "BioCLIP",
"top_matches": top_matches
}
@app.post("/submit-new-species")
async def submit_new_species(
species_name: str = Form(...),
location: str = Form(...),
species_type: str = Form("mushroom"),
user_id: str = Form(""),
user_email: str = Form(""),
notes: str = Form(""),
file: Optional[UploadFile] = File(None)
):
"""
Submit a new species that was not found in the MCC database and add it to the appropriate CSV
Args:
species_name: Name of the species identified
location: MCC location where found (must be one of the predefined locations)
species_type: Type of species - "plant" or "mushroom"
user_id: Optional user ID
user_email: Optional user email for follow-up
notes: Optional additional notes
file: Optional image file of the species
Returns:
JSON with submission confirmation
"""
try:
global mushroom_db, plant_db, mushroom_labels, plant_labels
# Validate location
if location not in MCC_LOCATIONS:
raise HTTPException(
status_code=400,
detail=f"Invalid location. Must be one of: {', '.join(MCC_LOCATIONS)}"
)
# Validate species type
if species_type not in ["plant", "mushroom"]:
raise HTTPException(
status_code=400,
detail="Invalid species_type. Must be 'plant' or 'mushroom'"
)
# Log the submission
submission = log_new_species_submission(
species_name=species_name,
location=location,
user_id=user_id,
user_email=user_email,
notes=notes
)
# If image is provided, save it
image_path = None
if file:
# Create submissions directory if it doesn't exist
submissions_dir = os.path.join(DATA_DIR, "submissions")
os.makedirs(submissions_dir, exist_ok=True)
# Generate unique filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_species_name = "".join(c for c in species_name if c.isalnum() or c in (' ', '_')).rstrip()
safe_species_name = safe_species_name.replace(' ', '_')
filename = f"{timestamp}_{safe_species_name}.jpg"
image_path = os.path.join(submissions_dir, filename)
# Save image
contents = await file.read()
image = Image.open(BytesIO(contents))
if image.mode != 'RGB':
image = image.convert('RGB')
image.save(image_path, 'JPEG')
# Add to database (Supabase if available, otherwise CSV)
db = mushroom_db if species_type == "mushroom" else plant_db
# Get coordinates for the location
lat, lon = MCC_LOCATION_COORDS.get(location, (12.92000, 80.12100))
# Create new entry
new_sno = len(db) + 1
# Save to Supabase if available
if USE_SUPABASE:
try:
species_data = {
"sno": new_sno,
"species_name": species_name,
"species_type": species_type,
"location": location,
"latitude": float(lat),
"longitude": float(lon),
"added_by": user_id if user_id else "anonymous",
"notes": notes
}
print(f"[DEBUG] Attempting to insert species data: {species_data}")
response = supabase.table("species").insert(species_data).execute()
# Check if the insert was successful
if not response.data or len(response.data) == 0:
error_msg = f"Insert failed - no data returned. Response: {response}"
print(f"[ERROR] {error_msg}")
raise Exception(error_msg)
print(f"[INFO] Successfully saved {species_name} to Supabase")
print(f"[DEBUG] Insert response: {response.data}")
# Update in-memory cache immediately
new_entry_dict = {
"sno": new_sno,
"species": species_name,
"location": location,
"lat": lat,
"lon": lon
}
new_row = pd.DataFrame([new_entry_dict])
if species_type == "mushroom":
mushroom_db = pd.concat([mushroom_db, new_row], ignore_index=True)
else:
plant_db = pd.concat([plant_db, new_row], ignore_index=True)
except Exception as e:
error_str = str(e)
print(f"[ERROR] Failed to save to Supabase: {error_str}")
# Check for specific error types
if "duplicate key" in error_str.lower() or "unique constraint" in error_str.lower():
raise HTTPException(
status_code=409,
detail=f"This species '{species_name}' already exists at location '{location}'. Please check the database or choose a different location."
)
elif "permission denied" in error_str.lower() or "policy" in error_str.lower():
raise HTTPException(
status_code=403,
detail=f"Permission denied. Please contact administrator. Error: {error_str}"
)
else:
raise HTTPException(
status_code=500,
detail=f"Failed to save to database: {error_str}"
)
else:
# Fallback to CSV
csv_file = MUSHROOM_CSV if species_type == "mushroom" else PLANT_CSV
new_entry = pd.DataFrame([{
"sno": new_sno,
"species": species_name,
"location": location,
"lat": lat,
"lon": lon
}])
new_entry.to_csv(csv_file, mode='a', header=False, index=False)
print(f"[INFO] Saved {species_name} to CSV")
# Regenerate labels lists
mushroom_labels = [species for species in mushroom_db["species"]]
mushroom_labels.append("unknown species")
plant_labels = [species for species in plant_db["species"]]
plant_labels.append("unknown species")
print(f"[INFO] Updated cache: {len(mushroom_db)} mushrooms, {len(plant_db)} plants")
return {
"success": True,
"message": f"Thank you! The {species_type} '{species_name}' has been added to the MCC database at {location}.",
"submission": {
"species_name": species_name,
"species_type": species_type,
"location": location,
"latitude": lat,
"longitude": lon,
"timestamp": submission["timestamp"],
"image_saved": image_path is not None,
"added_to_database": True
}
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing submission: {str(e)}")
@app.get("/")
async def root():
storage_info = "Supabase (permanent)" if USE_SUPABASE else "CSV/ephemeral"
return {
"message": "Mushroom & Plant Recognition API",
"version": "2.0.0",
"data_storage": storage_info,
"api_status": {
"bioclip": "active",
"openrouter_vlm": "active" if OPENROUTER_API_KEY else "not configured",
"plantnet": "active" if PLANTNET_API_KEY else "not configured",
"supabase": "active" if USE_SUPABASE else "not configured"
},
"database_stats": {
"mushrooms": len(mushroom_db),
"plants": len(plant_db),
"total_species": len(mushroom_db) + len(plant_db)
},
"endpoints": {
"/recognize": "POST - Upload image for species recognition",
"/submit-new-species": "POST - Submit a new species not in database",
"/health": "GET - Health check",
"/test/plantnet": "GET - Test PlantNet API connection",
"/test/supabase": "GET - Test Supabase connection"
}
}
@app.get("/health")
async def health():
return {
"status": "healthy",
"model_loaded": True,
"storage": "supabase" if USE_SUPABASE else "csv",
"apis": {
"bioclip": True,
"vlm": OPENROUTER_API_KEY != "",
"plantnet": PLANTNET_API_KEY != "",
"supabase": USE_SUPABASE
},
"species_count": {
"mushrooms": len(mushroom_db),
"plants": len(plant_db)
}
}
@app.get("/test/supabase")
async def test_supabase():
"""Test Supabase connection and show database stats"""
if not USE_SUPABASE:
return {
"success": False,
"message": "Supabase not configured",
"instructions": "Add SUPABASE_URL and SUPABASE_KEY to your .env file"
}
try:
# Get species counts
mushrooms = supabase.table("species").select("*").eq("species_type", "mushroom").execute()
plants = supabase.table("species").select("*").eq("species_type", "plant").execute()
return {
"success": True,
"message": "Supabase connection successful",
"database_stats": {
"mushrooms": len(mushrooms.data),
"plants": len(plants.data),
"total_species": len(mushrooms.data) + len(plants.data)
},
"storage_type": "permanent",
"cached_in_memory": True
}
except Exception as e:
return {
"success": False,
"message": f"Supabase connection error: {str(e)}"
}
@app.get("/test/plantnet")
async def test_plantnet():
"""Test PlantNet API connection"""
if not PLANTNET_API_KEY:
return {
"success": False,
"message": "PlantNet API key not configured",
"instructions": "Add PLANTNET_API_KEY to your .env file"
}
try:
# Test with a simple request (no image, just check auth)
api_url = f"https://my-api.plantnet.org/v2/projects"
params = {'api-key': PLANTNET_API_KEY}
response = requests.get(api_url, params=params, timeout=10)
if response.status_code == 200:
projects = response.json()
return {
"success": True,
"message": "PlantNet API key is valid",
"available_projects": projects if isinstance(projects, list) else ["all", "india", "weurope"],
"daily_limit": "500 requests (free tier)"
}
elif response.status_code == 401:
return {
"success": False,
"message": "Invalid PlantNet API key",
"instructions": "Check your PLANTNET_API_KEY in .env file"
}
elif response.status_code == 429:
return {
"success": False,
"message": "PlantNet API quota exceeded",
"instructions": "Wait 24 hours or upgrade your plan"
}
else:
return {
"success": False,
"message": f"PlantNet API error: {response.status_code}",
"details": response.text
}
except Exception as e:
return {
"success": False,
"message": f"Error testing PlantNet API: {str(e)}"
}
@app.post("/recognize")
async def recognize(file: UploadFile = File(...)):
"""
Recognize mushroom/plant species from uploaded image
Returns JSON with species information
No caching to ensure fresh predictions
"""
try:
# Read and validate image
contents = await file.read()
image = Image.open(BytesIO(contents))
# Convert to RGB if needed
if image.mode != 'RGB':
image = image.convert('RGB')
# Perform recognition (fresh computation each time)
result = recognize_species_internal(image)
# Return with no-cache headers
from fastapi import Response
from fastapi.responses import JSONResponse
response = JSONResponse(content=result)
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
|