Spaces:
Running
Running
File size: 46,631 Bytes
af91768 | 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 | """
VrukshaVed β Ayurvedic Plant Intelligence
FastAPI Backend with ConvNeXt-Small model + TTA inference
"""
import io
import json
import os
import sys
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as T
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import Request
from PIL import Image
# βββ Paths ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
BASE_DIR = Path(__file__).parent
MODEL_PATH = BASE_DIR / "model" / "leaf80_best_convnext_small.pth"
LABELS_PATH = BASE_DIR / "model" / "leaf80_label_to_class.json"
# βββ Model Config βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
MODEL_NAME = "convnext_small"
NUM_CLASSES = 80
IMG_SIZE = 224
DROPOUT_P = 0.4
CONFIDENCE_THRESH = 0.50
MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
# βββ TTA Transforms βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_norm = T.Normalize(MEAN, STD)
TTA_TRANSFORMS = [
T.Compose([T.Resize((IMG_SIZE, IMG_SIZE)), T.ToTensor(), _norm]),
T.Compose([T.Resize((IMG_SIZE, IMG_SIZE)), T.RandomHorizontalFlip(p=1.0), T.ToTensor(), _norm]),
T.Compose([T.Resize((256, 256)), T.CenterCrop(IMG_SIZE), T.ToTensor(), _norm]),
T.Compose([T.Resize((256, 256)), T.RandomCrop(IMG_SIZE), T.ToTensor(), _norm]),
T.Compose([T.Resize((IMG_SIZE, IMG_SIZE)),
T.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.1),
T.ToTensor(), _norm]),
]
# βββ Plant Info Database βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PLANT_DB = {
"Aloevera": {
"botanical_name": "Aloe barbadensis miller",
"ayurvedic_name": "Kumari",
"family": "Asphodelaceae",
"habitat": "Native to the Arabian Peninsula; grown worldwide in tropical and subtropical climates.",
"medicinal_uses": ["Soothes burns and wounds", "Treats digestive disorders", "Laxative properties", "Skin moisturiser and anti-ageing", "Reduces blood sugar levels"],
"active_compounds": ["Aloin", "Acemannan", "Anthraquinones", "Barbaloin", "Emodin"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Kashaya", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Fresh gel: 10β15 ml twice daily. Juice: 20β30 ml before meals.",
"parts_used": ["Leaf gel", "Latex", "Whole leaf"],
"precautions": "Avoid during pregnancy. Can cause diarrhoea in excess. Not recommended for children under 12."
},
"Amla": {
"botanical_name": "Phyllanthus emblica",
"ayurvedic_name": "Amalaki",
"family": "Phyllanthaceae",
"habitat": "Tropical and subtropical Asia; widely cultivated in India.",
"medicinal_uses": ["Potent antioxidant", "Improves immunity", "Hair nourishment and growth", "Manages diabetes", "Improves digestion and liver function"],
"active_compounds": ["Emblicanin A & B", "Punigluconin", "Vitamin C", "Tannins", "Gallic acid"],
"rasa_guna": {"Rasa (Taste)": "All six tastes (mainly sour)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Powder: 3β6g with water or honey. Fresh fruit juice: 10β20 ml twice daily.",
"parts_used": ["Fruit", "Seeds", "Bark"],
"precautions": "Consult physician if on anticoagulant medications. Excess may cause dryness."
},
"Neem": {
"botanical_name": "Azadirachta indica",
"ayurvedic_name": "Nimba",
"family": "Meliaceae",
"habitat": "Native to the Indian subcontinent; grows in tropical and semi-arid regions.",
"medicinal_uses": ["Powerful antibacterial and antifungal", "Treats skin diseases", "Blood purifier", "Dental hygiene", "Antidiabetic properties", "Insect repellent"],
"active_compounds": ["Nimbin", "Nimbidin", "Azadirachtin", "Quercetin", "Limonoids"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Leaf juice: 10β20 ml once daily. Powder: 2β4g with warm water.",
"parts_used": ["Leaves", "Bark", "Seeds", "Twigs", "Flowers"],
"precautions": "Not recommended during pregnancy or while trying to conceive. Avoid in very young children."
},
"Tulsi": {
"botanical_name": "Ocimum tenuiflorum",
"ayurvedic_name": "Tulasi",
"family": "Lamiaceae",
"habitat": "Native to tropical Asia; widely cultivated across India as a sacred plant.",
"medicinal_uses": ["Adaptogen (stress relief)", "Treats respiratory disorders", "Anti-inflammatory", "Improves immunity", "Antimicrobial properties", "Reduces fever"],
"active_compounds": ["Eugenol", "Ursolic acid", "Rosmarinic acid", "Caryophyllene", "Apigenin"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent), Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Leaf juice: 10β20 ml with honey. Tea: 5β10 fresh leaves boiled in water twice daily.",
"parts_used": ["Leaves", "Seeds", "Roots"],
"precautions": "Avoid excessive use during pregnancy. May interact with blood-thinning medications."
},
"Turmeric": {
"botanical_name": "Curcuma longa",
"ayurvedic_name": "Haridra",
"family": "Zingiberaceae",
"habitat": "Native to tropical South Asia; widely cultivated throughout India.",
"medicinal_uses": ["Powerful anti-inflammatory", "Antioxidant properties", "Wound healing", "Supports liver function", "Improves digestion", "Antimicrobial"],
"active_compounds": ["Curcumin", "Bisdemethoxycurcumin", "Turmerone", "Ar-turmerone", "Curdione"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Katu (Pungent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Powder: 1β3g with warm milk or water. Fresh juice: 10β20 ml daily.",
"parts_used": ["Rhizome", "Leaves"],
"precautions": "High doses may cause stomach upset. Avoid in gallbladder disease. Consult before use in pregnancy."
},
"Ginger": {
"botanical_name": "Zingiber officinale",
"ayurvedic_name": "Shunti / Ardraka",
"family": "Zingiberaceae",
"habitat": "Tropical Asia; cultivated throughout India, especially in Kerala and Karnataka.",
"medicinal_uses": ["Relieves nausea and vomiting", "Anti-inflammatory", "Digestive stimulant", "Reduces pain", "Improves circulation"],
"active_compounds": ["Gingerol", "Shogaol", "Zingerone", "Zingiberene", "Paradols"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent)", "Guna (Quality)": "Laghu, Snigdha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Fresh juice: 5β10 ml with honey. Dry powder: 1β3g with warm water.",
"parts_used": ["Rhizome"],
"precautions": "Avoid in high pitta conditions. Not recommended in large doses during pregnancy."
},
"Mint": {
"botanical_name": "Mentha spicata / Mentha piperita",
"ayurvedic_name": "Pudina",
"family": "Lamiaceae",
"habitat": "Temperate regions worldwide; cultivated across India.",
"medicinal_uses": ["Relieves indigestion and bloating", "Treats headaches", "Cooling effect on body", "Antispasmodic", "Improves breath and oral health"],
"active_compounds": ["Menthol", "Menthone", "Menthyl acetate", "Rosmarinic acid", "Flavonoids"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent), Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Fresh juice: 10β15 ml with water. Tea: 5β10 leaves brewed in hot water.",
"parts_used": ["Leaves", "Stems"],
"precautions": "Not suitable for infants. Menthol may cause breathing difficulties in very young children."
},
"Curry": {
"botanical_name": "Murraya koenigii",
"ayurvedic_name": "Surabhi",
"family": "Rutaceae",
"habitat": "Native to India and Sri Lanka; grows in tropical and subtropical regions.",
"medicinal_uses": ["Treats digestive disorders", "Anti-diabetic properties", "Hair loss prevention", "Antioxidant", "Reduces nausea"],
"active_compounds": ["Carbazole alkaloids", "Mahanimbine", "Girinimbine", "Murrayamine", "Linalool"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Katu (Pungent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Fresh leaves: 8β10 leaves chewed in morning. Powder: 2β3g with buttermilk.",
"parts_used": ["Leaves", "Bark", "Roots"],
"precautions": "Generally safe as a spice. Medicinal doses should be discussed with a practitioner."
},
"Guava": {
"botanical_name": "Psidium guajava",
"ayurvedic_name": "Amrud / Peru",
"family": "Myrtaceae",
"habitat": "Tropical and subtropical regions; widely grown throughout India.",
"medicinal_uses": ["Antidiarrheal properties", "Rich in Vitamin C", "Controls blood sugar", "Reduces cholesterol", "Anti-inflammatory"],
"active_compounds": ["Quercetin", "Guajaverin", "Lycopene", "Vitamin C", "Tannins"],
"rasa_guna": {"Rasa (Taste)": "Kashaya (Astringent), Madhura (Sweet)", "Guna (Quality)": "Guru, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Leaf decoction: 50 ml twice daily for diarrhoea. Fruit: eaten fresh.",
"parts_used": ["Leaves", "Fruit", "Bark"],
"precautions": "Seeds may cause constipation if eaten in excess. Avoid in irritable bowel syndrome."
},
"Hibiscus": {
"botanical_name": "Hibiscus rosa-sinensis",
"ayurvedic_name": "Japa / China Rose",
"family": "Malvaceae",
"habitat": "Tropical and subtropical Asia; widely cultivated across India.",
"medicinal_uses": ["Lowers blood pressure", "Promotes hair growth", "Liver protection", "Antioxidant", "Treats urinary tract infections"],
"active_compounds": ["Anthocyanins", "Quercetin", "Chlorogenic acid", "Hibiscetin", "Protocatechuic acid"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet), Tikta (Bitter)", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Flower decoction: 50 ml twice daily. Flower paste applied topically for hair care.",
"parts_used": ["Flowers", "Leaves", "Roots"],
"precautions": "May lower blood pressure significantly. Avoid concurrent use with antihypertensive drugs."
},
"Lemon": {
"botanical_name": "Citrus limon",
"ayurvedic_name": "Nimbuka",
"family": "Rutaceae",
"habitat": "Native to South Asia; cultivated throughout India.",
"medicinal_uses": ["Rich source of Vitamin C", "Aids digestion", "Alkalises blood pH", "Prevents kidney stones", "Antibacterial"],
"active_compounds": ["Vitamin C", "Citric acid", "Limonene", "Flavonoids", "Pectin"],
"rasa_guna": {"Rasa (Taste)": "Amla (Sour)", "Guna (Quality)": "Laghu, Snigdha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Amla (Sour)"},
"dosage_form": "Fresh juice: 20β30 ml with warm water in the morning.",
"parts_used": ["Fruit", "Juice", "Peel"],
"precautions": "Avoid on empty stomach if prone to acidity. Excess can erode tooth enamel."
},
"Mango": {
"botanical_name": "Mangifera indica",
"ayurvedic_name": "Amra",
"family": "Anacardiaceae",
"habitat": "Native to India; grown throughout tropical regions.",
"medicinal_uses": ["Digestive tonic", "Rich in vitamins A, C, E", "Antioxidant", "Boosts immunity", "Supports eye health"],
"active_compounds": ["Mangiferin", "Quercetin", "Beta-carotene", "Gallic acid", "Vitamin C"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet), Amla (Sour)", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Leaf powder: 2β3g with water. Bark decoction: 50 ml for diarrhoea.",
"parts_used": ["Fruit", "Leaves", "Bark", "Seeds"],
"precautions": "Unripe mango in excess may cause throat irritation and indigestion."
},
"Papaya": {
"botanical_name": "Carica papaya",
"ayurvedic_name": "Papita / Erand Karkati",
"family": "Caricaceae",
"habitat": "Tropical regions; widely grown throughout India.",
"medicinal_uses": ["Digestive enzyme source", "Treats dengue fever (leaf extract)", "Anti-inflammatory", "Wound healing", "Anthelmintic"],
"active_compounds": ["Papain", "Chymopapain", "Lycopene", "Beta-carotene", "Carpaine"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet), Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Leaf juice: 10β20 ml twice daily. Ripe fruit: eaten fresh.",
"parts_used": ["Fruit", "Leaves", "Seeds", "Latex"],
"precautions": "Avoid raw papaya and seeds during pregnancy (abortifacient). Latex may cause allergic reactions."
},
"Jasmine": {
"botanical_name": "Jasminum officinale",
"ayurvedic_name": "Jati / Mallika",
"family": "Oleaceae",
"habitat": "Native to South and West Asia; widely cultivated in India.",
"medicinal_uses": ["Antidepressant (aromatherapy)", "Improves skin health", "Antiseptic", "Reduces anxiety", "Enhances libido"],
"active_compounds": ["Benzyl acetate", "Linalool", "Methyl jasmonate", "Jasmonates", "Indole"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Katu (Pungent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Flower infusion: as tea or aromatherapy. Leaf paste applied topically.",
"parts_used": ["Flowers", "Leaves"],
"precautions": "Essential oil should be diluted before topical use. Not recommended in large quantities internally."
},
"Drumstick": {
"botanical_name": "Moringa oleifera",
"ayurvedic_name": "Shigru / Sahijana",
"family": "Moringaceae",
"habitat": "Native to the sub-Himalayan tracts; cultivated across India.",
"medicinal_uses": ["Highly nutritious superfood", "Lowers blood sugar", "Reduces inflammation", "Lowers cholesterol", "Boosts immunity"],
"active_compounds": ["Isothiocyanates", "Moringin", "Beta-carotene", "Quercetin", "Chlorogenic acid"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent), Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Leaf powder: 2β5g daily. Fresh leaves in food. Pod vegetable: eaten cooked.",
"parts_used": ["Leaves", "Pods", "Seeds", "Roots"],
"precautions": "Root bark may be toxic in large amounts. Avoid during pregnancy (root/bark extracts)."
},
"Tamarind": {
"botanical_name": "Tamarindus indica",
"ayurvedic_name": "Amli / Chincha",
"family": "Fabaceae",
"habitat": "Native to tropical Africa; naturalised throughout India.",
"medicinal_uses": ["Treats constipation", "Bile stimulant", "Antioxidant", "Cooling in fever", "Anti-inflammatory"],
"active_compounds": ["Tartaric acid", "Malic acid", "Potassium bitartrate", "Lupeol", "Catechins"],
"rasa_guna": {"Rasa (Taste)": "Amla (Sour)", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Amla (Sour)"},
"dosage_form": "Pulp: 10β15g soaked in water. Leaf decoction: 50 ml for fever.",
"parts_used": ["Fruit pulp", "Leaves", "Seeds", "Bark"],
"precautions": "Avoid in excess if prone to acidity. May interfere with aspirin absorption."
},
"Tomato": {
"botanical_name": "Solanum lycopersicum",
"ayurvedic_name": "Tamatar",
"family": "Solanaceae",
"habitat": "Originally from South America; widely cultivated throughout India.",
"medicinal_uses": ["Rich in lycopene (anti-cancer)", "Cardiovascular health", "Antioxidant", "Improves skin", "Bone health"],
"active_compounds": ["Lycopene", "Beta-carotene", "Vitamin C", "Naringenin", "Chlorogenic acid"],
"rasa_guna": {"Rasa (Taste)": "Amla (Sour), Madhura (Sweet)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Amla (Sour)"},
"dosage_form": "Fresh fruit: consumed in diet. Juice: 100β200 ml daily.",
"parts_used": ["Fruit"],
"precautions": "Avoid in excess if you have arthritis (nightshade family). Unripe fruit contains solanine."
},
"Coriender": {
"botanical_name": "Coriandrum sativum",
"ayurvedic_name": "Dhanyaka / Dhaniya",
"family": "Apiaceae",
"habitat": "Cultivated throughout India as a culinary herb.",
"medicinal_uses": ["Digestive stimulant", "Reduces blood sugar", "Anti-inflammatory", "Antibacterial", "Lowers cholesterol"],
"active_compounds": ["Linalool", "Borneol", "Geraniol", "Quercetin", "Rutin"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Katu (Pungent)", "Guna (Quality)": "Laghu, Snigdha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Seed decoction: 50 ml twice daily. Fresh leaf juice: 10β15 ml.",
"parts_used": ["Leaves", "Seeds"],
"precautions": "Allergy rare but possible. Excessive use may lower blood sugar too much in diabetics on medication."
},
"Lemongrass": {
"botanical_name": "Cymbopogon citratus",
"ayurvedic_name": "Bhustrina",
"family": "Poaceae",
"habitat": "Tropical and subtropical regions; cultivated in India for essential oil.",
"medicinal_uses": ["Reduces anxiety", "Lowers blood pressure", "Antimicrobial", "Analgesic", "Digestive tonic"],
"active_compounds": ["Citral", "Geraniol", "Limonene", "Myrcene", "Linalool"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent), Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Tea: 2β3 stalks brewed in hot water. Essential oil: diluted for topical use.",
"parts_used": ["Stems", "Leaves"],
"precautions": "Essential oil should not be taken internally. Avoid during pregnancy in medicinal doses."
},
"Eucalyptus": {
"botanical_name": "Eucalyptus globulus",
"ayurvedic_name": "Tailaparna",
"family": "Myrtaceae",
"habitat": "Native to Australia; widely planted in India for timber and essential oil.",
"medicinal_uses": ["Treats respiratory conditions", "Decongestant", "Antiseptic", "Insect repellent", "Pain relief"],
"active_compounds": ["1,8-Cineole (Eucalyptol)", "Alpha-pinene", "Limonene", "Terpineol", "Globulol"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent), Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Steam inhalation: 3β5 drops oil in hot water. Topical oil: diluted with carrier oil.",
"parts_used": ["Leaves", "Essential oil"],
"precautions": "Internal use of essential oil is toxic. Not suitable for young children. Avoid near face of infants."
},
"Rose": {
"botanical_name": "Rosa damascena / Rosa indica",
"ayurvedic_name": "Taruni / Shatapatra",
"family": "Rosaceae",
"habitat": "Temperate regions; cultivated throughout India.",
"medicinal_uses": ["Treats skin conditions", "Anti-inflammatory", "Stress reduction", "Digestive tonic", "Antimicrobial"],
"active_compounds": ["Citronellol", "Geraniol", "Nerol", "Kaempferol", "Quercetin"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet), Kashaya (Astringent)", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Rose water: used topically. Petal jam (Gulkand): 5β10g daily. Infusion: as tea.",
"parts_used": ["Petals", "Hips", "Leaves"],
"precautions": "Allergy possible in sensitive individuals. Avoid wilted or chemically treated flowers."
},
"Jackfruit": {
"botanical_name": "Artocarpus heterophyllus",
"ayurvedic_name": "Panasa",
"family": "Moraceae",
"habitat": "Native to the Western Ghats; grown throughout tropical India.",
"medicinal_uses": ["Boosts immunity", "Improves digestion", "Anti-ulcer properties", "Antioxidant", "Controls blood pressure"],
"active_compounds": ["Artocarpin", "Morusin", "Norartocarpin", "Vitamin C", "Flavonoids"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet)", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Leaf decoction: 50 ml twice daily. Fruit: eaten fresh or cooked.",
"parts_used": ["Fruit", "Seeds", "Leaves", "Bark"],
"precautions": "Excess consumption may cause digestive discomfort. Avoid if allergic to latex (cross-reactivity possible)."
},
"Castor": {
"botanical_name": "Ricinus communis",
"ayurvedic_name": "Eranda",
"family": "Euphorbiaceae",
"habitat": "Tropical and subtropical regions; widely grown in India.",
"medicinal_uses": ["Laxative (castor oil)", "Anti-inflammatory", "Skin conditions", "Arthritis pain relief", "Induces labour (under supervision)"],
"active_compounds": ["Ricinoleic acid", "Ricin (toxic in seeds)", "Undecylenic acid", "Tocopherols", "Flavonoids"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet), Katu (Pungent)", "Guna (Quality)": "Guru, Snigdha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Castor oil: 10β15 ml at bedtime as laxative. Leaf poultice for topical use.",
"parts_used": ["Seeds (oil)", "Leaves", "Roots"],
"precautions": "Seeds are extremely toxic (contain ricin). Only use processed castor oil. Not for internal use during pregnancy."
},
"Betel": {
"botanical_name": "Piper betle",
"ayurvedic_name": "Nagavalli / Tambula",
"family": "Piperaceae",
"habitat": "Tropical Asia; cultivated throughout India.",
"medicinal_uses": ["Digestive stimulant", "Antiseptic", "Treats mouth ulcers", "Anti-inflammatory", "Stimulates salivation"],
"active_compounds": ["Chavicol", "Eugenol", "Beta-sitosterol", "Tannins", "Safrole"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent), Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Fresh leaf paste: applied externally. Leaf juice: 5β10 ml for mouth conditions.",
"parts_used": ["Leaves"],
"precautions": "Do NOT chew with tobacco or areca nut β carcinogenic combination. Leaf alone is medicinal in limited quantities."
},
"Catharanthus": {
"botanical_name": "Catharanthus roseus",
"ayurvedic_name": "Sadabahar / Nityakalyani",
"family": "Apocynaceae",
"habitat": "Native to Madagascar; naturalised throughout India.",
"medicinal_uses": ["Anti-diabetic properties", "Cancer treatment (alkaloids)", "Lowers blood pressure", "Wound healing", "Antibacterial"],
"active_compounds": ["Vincristine", "Vinblastine", "Catharanthine", "Vindoline", "Ajmalicine"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Kashaya (Astringent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Leaf extract: only under medical supervision. Folk use: 5β10 flowers in water for diabetes.",
"parts_used": ["Leaves", "Flowers", "Roots"],
"precautions": "Highly toxic in large doses. Pharmaceutical alkaloids (vincristine/vinblastine) only used medically. Do NOT self-medicate."
},
"Henna": {
"botanical_name": "Lawsonia inermis",
"ayurvedic_name": "Mehndi / Madayantika",
"family": "Lythraceae",
"habitat": "Arid and semi-arid regions; cultivated throughout India.",
"medicinal_uses": ["Hair conditioning and colouring", "Treats skin infections", "Reduces fever", "Anti-inflammatory", "Headache relief"],
"active_compounds": ["Lawsone", "Gallic acid", "Glucose", "Mannitol", "Tannins"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Kashaya (Astringent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Leaf paste applied topically. Powder in hair conditioning packs.",
"parts_used": ["Leaves", "Seeds", "Bark"],
"precautions": "Black henna may contain PPD (para-phenylenediamine) β causes severe allergic reactions. Use only natural henna."
},
"Marigold": {
"botanical_name": "Tagetes erecta / Calendula officinalis",
"ayurvedic_name": "Sthulapushpa / Gendha",
"family": "Asteraceae",
"habitat": "Tropical America; widely cultivated throughout India.",
"medicinal_uses": ["Wound healing", "Anti-inflammatory", "Antifungal", "Eye health", "Antiseptic"],
"active_compounds": ["Lutein", "Zeaxanthin", "Quercetin", "Isorhamnetin", "Terpenoids"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Katu (Pungent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Flower petal infusion: 50 ml daily. Petal cream applied topically.",
"parts_used": ["Flowers", "Leaves"],
"precautions": "May cause allergic contact dermatitis in Asteraceae-sensitive individuals."
},
"Bamboo": {
"botanical_name": "Bambusa vulgaris / Dendrocalamus sp.",
"ayurvedic_name": "Vanshalochan / Tvak",
"family": "Poaceae",
"habitat": "Tropical and subtropical Asia; widely found in India.",
"medicinal_uses": ["Respiratory tonic", "Treats bleeding disorders", "Rich in silica for bone health", "Anti-ulcer", "Cooling properties"],
"active_compounds": ["Silica", "Bamboo silica (Tabasheer)", "Flavonoids", "Chlorophyll", "Lignin"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet), Kashaya (Astringent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Bamboo manna (Tabasheer): 1β2g with honey. Young shoots: eaten as vegetable.",
"parts_used": ["Young shoots", "Internodal silica (Tabasheer)", "Leaves"],
"precautions": "Some species contain taxiphyllin (cyanogenic glycoside) in young shoots β must be cooked before eating."
},
"Pepper": {
"botanical_name": "Piper nigrum",
"ayurvedic_name": "Maricha",
"family": "Piperaceae",
"habitat": "Native to Kerala; cultivated in tropical India.",
"medicinal_uses": ["Digestive stimulant", "Improves bioavailability of nutrients", "Anti-inflammatory", "Antibacterial", "Expectorant"],
"active_compounds": ["Piperine", "Piperic acid", "Safrole", "Beta-caryophyllene", "Linalool"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent)", "Guna (Quality)": "Laghu, Ruksha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Powder: 500mgβ1g with honey or milk. Added to food as spice.",
"parts_used": ["Fruit (peppercorns)", "Leaves"],
"precautions": "Avoid large doses in gastritis or ulcer patients. May interact with certain drugs by increasing their absorption."
},
"Coffee": {
"botanical_name": "Coffea arabica",
"ayurvedic_name": "Kapi",
"family": "Rubiaceae",
"habitat": "Native to Ethiopia; major cultivation in Karnataka, Kerala, Tamil Nadu.",
"medicinal_uses": ["CNS stimulant", "Reduces fatigue", "Antioxidant properties", "Improves cognitive function", "Reduces risk of Parkinson's disease"],
"active_compounds": ["Caffeine", "Chlorogenic acid", "Cafestol", "Kahweol", "Diterpenes"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter)", "Guna (Quality)": "Laghu, Ruksha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Moderate consumption: 1β3 cups daily. Green coffee extract: 200β400 mg daily.",
"parts_used": ["Seeds (beans)", "Leaves"],
"precautions": "Excessive consumption causes anxiety, insomnia, palpitations. Avoid in pregnancy and hypertension."
},
"Pumpkin": {
"botanical_name": "Cucurbita pepo",
"ayurvedic_name": "Kushmanda",
"family": "Cucurbitaceae",
"habitat": "Widely cultivated throughout India as a vegetable.",
"medicinal_uses": ["Antiulcer properties", "Diuretic", "Antidepressant (seeds)", "Anthelmintic", "Nutritive tonic"],
"active_compounds": ["Cucurbitacins", "Beta-carotene", "Zinc", "Vitamin E", "Lignans"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet)", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Fresh juice: 50β100 ml daily. Seeds: 30g for deworming. Vegetable cooked.",
"parts_used": ["Fruit", "Seeds", "Leaves", "Flowers"],
"precautions": "Excessive use of seeds may cause stomach discomfort. Cucurbitacin content may be toxic in wild varieties."
},
"Onion": {
"botanical_name": "Allium cepa",
"ayurvedic_name": "Palandu",
"family": "Amaryllidaceae",
"habitat": "Cultivated throughout India as a staple vegetable.",
"medicinal_uses": ["Antibacterial", "Reduces blood sugar", "Improves heart health", "Antiparasitic", "Treats cough and cold"],
"active_compounds": ["Quercetin", "Allicin", "Diallyl disulfide", "Fisetin", "Chromium"],
"rasa_guna": {"Rasa (Taste)": "Katu (Pungent)", "Guna (Quality)": "Guru, Snigdha, Tikshna", "Virya (Potency)": "Ushna (Hot)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Raw juice: 10β20 ml. Fresh onion in daily diet. Roasted onion for earache.",
"parts_used": ["Bulb", "Leaves"],
"precautions": "Raw onion may cause heartburn. May enhance the effect of blood-thinning medications."
},
"Pomegranate": {
"botanical_name": "Punica granatum",
"ayurvedic_name": "Dadima",
"family": "Lythraceae",
"habitat": "Native to Iran and northern India; widely cultivated in Rajasthan, Maharashtra, Gujarat.",
"medicinal_uses": ["Powerful antioxidant", "Heart health", "Anti-inflammatory", "Anti-cancer properties", "Treats anaemia"],
"active_compounds": ["Punicalagin", "Ellagic acid", "Anthocyanins", "Punicic acid", "Quercetin"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet), Amla (Sour), Kashaya (Astringent)", "Guna (Quality)": "Laghu, Snigdha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Fresh juice: 100β200 ml daily. Fruit: eaten fresh. Bark decoction: for parasites.",
"parts_used": ["Fruit", "Peel", "Seeds", "Bark"],
"precautions": "Pomegranate juice may interact with certain medications (similar to grapefruit). Consult doctor if on prescription drugs."
},
"Pea": {
"botanical_name": "Pisum sativum",
"ayurvedic_name": "Harit Shimbhi",
"family": "Fabaceae",
"habitat": "Temperate regions; cultivated throughout India.",
"medicinal_uses": ["Rich in protein and fibre", "Supports digestion", "Lowers cholesterol", "Manages blood sugar", "Promotes bone health"],
"active_compounds": ["Pisumsaponins", "Coumestrol", "Ferulic acid", "Carotenoids", "Vitamin K"],
"rasa_guna": {"Rasa (Taste)": "Madhura (Sweet)", "Guna (Quality)": "Guru, Snigdha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Madhura (Sweet)"},
"dosage_form": "Fresh peas in diet. Dried pea flour: 20β30g in preparations.",
"parts_used": ["Seeds", "Pods", "Leaves"],
"precautions": "May cause bloating and gas in some individuals. Avoid excess in those with uric acid/gout issues."
},
"Insulin": {
"botanical_name": "Costus igneus",
"ayurvedic_name": "Insulin plant / Keukand",
"family": "Costaceae",
"habitat": "Native to tropical America; cultivated in South India.",
"medicinal_uses": ["Manages type 2 diabetes", "Lowers blood glucose", "Antioxidant", "Kidney protection", "Anti-inflammatory"],
"active_compounds": ["Diosgenin", "Corosolic acid", "Quercetin", "Kaempferol", "Luteolin"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Kashaya (Astringent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Fresh leaf: chew 1β2 leaves before meals. Leaf juice: 10β20 ml twice daily.",
"parts_used": ["Leaves"],
"precautions": "Do not stop prescribed diabetes medications without doctor's advice. Monitor blood sugar carefully."
},
"Malabar_Nut": {
"botanical_name": "Justicia adhatoda",
"ayurvedic_name": "Vasa / Adusa",
"family": "Acanthaceae",
"habitat": "Sub-Himalayan tracts and throughout India's plains.",
"medicinal_uses": ["Treats respiratory diseases (asthma, bronchitis)", "Expectorant", "Antispasmodic", "Antitubercular", "Hemostatic"],
"active_compounds": ["Vasicine", "Vasicinone", "Adhatodic acid", "Beta-sitosterol", "Quinazoline alkaloids"],
"rasa_guna": {"Rasa (Taste)": "Tikta (Bitter), Kashaya (Astringent)", "Guna (Quality)": "Laghu, Ruksha", "Virya (Potency)": "Sheet (Cold)", "Vipaka (Post-digestion)": "Katu (Pungent)"},
"dosage_form": "Leaf decoction: 50 ml 2β3 times daily. Leaf juice: 10β15 ml with honey.",
"parts_used": ["Leaves", "Roots", "Flowers"],
"precautions": "Can cause abortion β STRICTLY avoid during pregnancy. Vasicine is a known uterine stimulant."
},
}
# Generate generic data for plants not in the detailed DB
def _generic_plant_info(name: str) -> dict:
clean = name.replace("_", " ").replace("1", "")
return {
"botanical_name": f"{clean} sp.",
"ayurvedic_name": clean,
"family": "Medicinal Plant",
"habitat": f"{clean} is found in tropical and subtropical regions of India, commonly growing in gardens, forests, and cultivated fields.",
"medicinal_uses": [
f"Traditional Ayurvedic medicine uses {clean} as a healing herb",
"Anti-inflammatory and antioxidant properties",
"Supports digestive health",
"Boosts immune function",
"Used in traditional formulations for general wellness"
],
"active_compounds": ["Flavonoids", "Tannins", "Alkaloids", "Terpenoids", "Phenolic compounds"],
"rasa_guna": {
"Rasa (Taste)": "Tikta (Bitter), Kashaya (Astringent)",
"Guna (Quality)": "Laghu, Ruksha",
"Virya (Potency)": "Ushna (Hot)",
"Vipaka (Post-digestion)": "Katu (Pungent)"
},
"dosage_form": f"Traditional preparations of {clean} include decoctions (50 ml twice daily), powders (2β5g), and fresh juice (10β20 ml). Consult an Ayurvedic practitioner for personalised dosage.",
"parts_used": ["Leaves", "Roots", "Bark"],
"precautions": f"Consult a qualified Ayurvedic practitioner before using {clean} medicinally. Keep out of reach of children. Avoid during pregnancy unless advised by a physician."
}
def get_plant_info(name: str) -> dict:
"""Return plant info from DB or generate generic entry."""
# Normalise lookup
for key in PLANT_DB:
if key.lower() == name.lower().replace(" ", "_"):
return PLANT_DB[key]
# Also try direct match
if name in PLANT_DB:
return PLANT_DB[name]
return _generic_plant_info(name)
# βββ Load Model + Labels βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
print(f"[VrukshaVed] Loading model from {MODEL_PATH} on {DEVICE}...")
try:
from huggingface_hub import hf_hub_download
HAS_HF_HUB = True
except ImportError:
HAS_HF_HUB = False
DEFAULT_HF_REPOS = [
os.getenv("HF_MODEL_REPO", ""),
"omkhk/vrukshaved-convnext",
"omkhk/vrukshaved-ayurvedic-plant-convnext",
]
DEFAULT_HF_REPOS = [r for r in DEFAULT_HF_REPOS if r]
def is_valid_weight_file(path: Path) -> bool:
return path.exists() and path.stat().st_size > 1_000_000
resolved_model_path = MODEL_PATH
resolved_labels_path = LABELS_PATH
if not is_valid_weight_file(MODEL_PATH) and HAS_HF_HUB:
print("[VrukshaVed] NOTICE: Local model missing or LFS pointer. Attempting HF Hub download...", file=sys.stderr)
for repo_id in DEFAULT_HF_REPOS:
try:
dl_path = hf_hub_download(repo_id=repo_id, filename="leaf80_best_convnext_small.pth")
resolved_model_path = Path(dl_path)
print(f"[VrukshaVed] SUCCESS: Downloaded model from HF Hub: {repo_id}")
break
except Exception as err:
print(f"[VrukshaVed] Could not download model from {repo_id}: {err}", file=sys.stderr)
if not LABELS_PATH.exists() and HAS_HF_HUB:
for repo_id in DEFAULT_HF_REPOS:
try:
dl_path = hf_hub_download(repo_id=repo_id, filename="leaf80_label_to_class.json")
resolved_labels_path = Path(dl_path)
print(f"[VrukshaVed] SUCCESS: Downloaded labels from HF Hub: {repo_id}")
break
except Exception:
pass
if resolved_labels_path.exists():
try:
with open(resolved_labels_path, encoding="utf-8") as f:
label_to_class: dict = json.load(f)
CLASS_NAMES = [label_to_class[str(i)] for i in range(NUM_CLASSES)]
except Exception as e:
print(f"[ERROR] Could not parse labels JSON: {e}", file=sys.stderr)
CLASS_NAMES = [f"Class_{i}" for i in range(NUM_CLASSES)]
else:
CLASS_NAMES = [f"Class_{i}" for i in range(NUM_CLASSES)]
model = None
MODEL_LOADED = False
try:
if not is_valid_weight_file(resolved_model_path):
raise FileNotFoundError(f"Model file invalid or missing at {resolved_model_path}")
_model = models.convnext_small(weights=None)
in_f = _model.classifier[2].in_features
_model.classifier[2] = nn.Sequential(
nn.Dropout(p=DROPOUT_P),
nn.Linear(in_f, NUM_CLASSES)
)
_model.load_state_dict(torch.load(resolved_model_path, map_location=DEVICE))
_model = _model.to(DEVICE).eval()
model = _model
MODEL_LOADED = True
except Exception as e:
print(f"[VrukshaVed] WARNING: Model NOT loaded: {e}", file=sys.stderr)
print("[VrukshaVed] Server will start in DEMO mode.", file=sys.stderr)
if MODEL_LOADED:
print(f"[VrukshaVed] SUCCESS: Model loaded. Running on {DEVICE}.")
# βββ Predict Function ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def predict_leaf(pil_image: Image.Image, threshold: float = CONFIDENCE_THRESH, top_k: int = 5) -> dict:
if not MODEL_LOADED or model is None:
# Demo mode β return plausible fake results
import random
random.seed(42)
picks = random.sample(range(NUM_CLASSES), top_k)
weights = sorted([random.uniform(0.05, 0.85) for _ in range(top_k)], reverse=True)
total = sum(weights)
weights = [w / total for w in weights]
top_k_list = [(CLASS_NAMES[picks[i]], weights[i]) for i in range(top_k)]
best_cls, best_conf = top_k_list[0]
return {
"predicted": best_cls if best_conf >= threshold else "Unknown",
"confidence": best_conf,
"top_k": top_k_list,
"status": "ok" if best_conf >= threshold else "low_confidence",
"demo_mode": True,
"message": f"DEMO MODE β place real model in model/ folder"
}
img = pil_image.convert("RGB")
prob_sum = np.zeros(NUM_CLASSES)
with torch.no_grad():
for tfm in TTA_TRANSFORMS:
t = tfm(img).unsqueeze(0).to(DEVICE)
prob_sum += torch.softmax(model(t), dim=1).cpu().numpy()[0]
avg = prob_sum / len(TTA_TRANSFORMS)
top_i = avg.argsort()[::-1][:top_k]
top_k_list = [(CLASS_NAMES[i], float(avg[i])) for i in top_i]
best_cls, best_conf = top_k_list[0]
if best_conf < threshold:
return {
"predicted": "Unknown",
"confidence": best_conf,
"top_k": top_k_list,
"status": "low_confidence",
"demo_mode": False,
"message": f"Best='{best_cls}' ({best_conf*100:.1f}%) < {threshold*100:.0f}% threshold"
}
return {
"predicted": best_cls,
"confidence": best_conf,
"top_k": top_k_list,
"status": "ok",
"demo_mode": False,
"message": f"{best_cls} ({best_conf*100:.1f}%)"
}
# βββ FastAPI App βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(title="VrukshaVed β Ayurvedic Plant Intelligence", version="3.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")
templates = Jinja2Templates(directory=BASE_DIR / "templates")
# βββ Routes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse(request, "index.html")
@app.post("/api/predict")
async def predict(file: UploadFile = File(...)):
"""Main prediction endpoint. Accepts image file, returns prediction + plant info."""
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image (JPG, PNG, WEBP).")
contents = await file.read()
if len(contents) > 15 * 1024 * 1024:
raise HTTPException(status_code=413, detail="Image too large. Max 15 MB.")
try:
img = Image.open(io.BytesIO(contents)).convert("RGB")
except Exception:
raise HTTPException(status_code=400, detail="Could not open image. Please upload a valid image file.")
result = predict_leaf(img)
plant_name = result["predicted"]
plant_info = get_plant_info(plant_name) if plant_name != "Unknown" else {}
return JSONResponse({
"status": result["status"],
"demo_mode": result.get("demo_mode", False),
"top_prediction": {
"plant_name": plant_name,
"confidence": result["confidence"],
"confidence_pct": f"{result['confidence']*100:.1f}%",
},
"all_predictions": [
{"plant": name, "confidence": conf}
for name, conf in result["top_k"]
],
"plant_info": plant_info,
"tta_passes": len(TTA_TRANSFORMS),
"threshold": CONFIDENCE_THRESH,
"model": MODEL_NAME,
})
@app.get("/api/plants")
async def list_plants():
"""List all 80 supported plant species."""
return JSONResponse({
"total": len(CLASS_NAMES),
"plants": sorted(CLASS_NAMES),
"model_loaded": MODEL_LOADED,
})
@app.get("/api/plant/{name}")
async def plant_detail(name: str):
"""Get detailed information for a specific plant."""
info = get_plant_info(name)
return JSONResponse({
"found": True,
"name": name,
"info": info,
})
@app.get("/api/health")
async def health():
"""Health check endpoint."""
return JSONResponse({
"status": "ok",
"model_loaded": MODEL_LOADED,
"device": str(DEVICE),
"num_classes": NUM_CLASSES,
"tta_passes": len(TTA_TRANSFORMS),
"confidence_threshold": CONFIDENCE_THRESH,
})
# βββ Entry Point βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", "7860"))
uvicorn.run("app:app", host="0.0.0.0", port=port, reload=False)
|