Spaces:
Sleeping
Sleeping
Download GPT_client.py from SNAKEMODEL/Snaid_Model_Backend: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/SNAKEMODEL/Snaid_Model_Backend/resolve/main/GPT_client.py
- Command line
-
hf download hf://spaces/SNAKEMODEL/Snaid_Model_Backend/GPT_client.py
-
curl -L -o GPT_client.py https://huggingface.co/spaces/SNAKEMODEL/Snaid_Model_Backend/resolve/main/GPT_client.py
11.4 kB
| import os | |
| import json | |
| import pandas as pd | |
| from openai import OpenAI | |
| # ----------------------------------- | |
| # Load API Key (Hugging Face env variable) | |
| # ----------------------------------- | |
| API_KEY = os.getenv("NVIDIA_API_KEY") | |
| if not API_KEY: | |
| print("WARNING: NVIDIA_API_KEY not found. LLM disabled.") | |
| client = None | |
| else: | |
| client = OpenAI( | |
| base_url="https://integrate.api.nvidia.com/v1", | |
| api_key=API_KEY | |
| ) | |
| # ----------------------------------- | |
| # Load Metadata CSV | |
| # ----------------------------------- | |
| metadata_path = "data/venomstatus_with_antivenom.csv" | |
| df = pd.read_csv(metadata_path) | |
| def get_snake_description(species_name: str) -> str: | |
| if client is None: | |
| return "LLM service unavailable" | |
| system_prompt = ( | |
| "You are a professional snake species expert and herpetologist. " | |
| "Provide accurate, scientific, and concise descriptions of snake species." | |
| ) | |
| user_prompt = ( | |
| f"Describe the snake species '{species_name}' including:\n" | |
| f"- Venom type and danger level\n" | |
| f"- Habitat and geographic distribution\n" | |
| f"- Behavior and typical environment\n" | |
| f"- Conservation or ecological importance\n\n" | |
| f"Provide a single short paragraph (max 20 words)." | |
| ) | |
| try: | |
| response = client.chat.completions.create( | |
| model="openai/gpt-oss-20b", | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": user_prompt} | |
| ], | |
| temperature=0.2, | |
| stream=False | |
| ) | |
| return response.choices[0].message.content.strip() | |
| except Exception as e: | |
| return f"Error generating description: {str(e)}" | |
| # ----------------------------------- | |
| # Allowed Species List | |
| # ----------------------------------- | |
| ALLOWED_SPECIES = [ | |
| "Indian Cobra", "Monocled Cobra", "King Cobra", "Common Krait", "Banded Krait", | |
| "Sind Krait", "Walls Krait", "Greater Black Krait", "Andaman Cobra", "Nicobar Cobra", | |
| "Slender Coral Snake", "Bibrons Coral Snake", "Indian Coral Snake", "Blue Coral Snake", | |
| "Black Coral Snake", "Himalayan Coral Snake", "Sea Krait", "Yellow-lipped Sea Krait", | |
| "Annulated Sea Snake", "Beaked Sea Snake", "Hook-nosed Sea Snake", "Spine-bellied Sea Snake", | |
| "Shaws Sea Snake", "Short Sea Snake", "Olive Sea Snake", "Turtle-headed Sea Snake", | |
| "Dubois Sea Snake", "Horned Sea Snake", "Dog-faced Water Snake", "Bockadam", "Russells Viper", | |
| "Saw-scaled Viper", "Hump-nosed Pit Viper", "Malabar Pit Viper", "Bamboo Pit Viper", | |
| "Himalayan Pit Viper", "Green Pit Viper", "Popes Pit Viper", "White-lipped Pit Viper", | |
| "Mountain Pit Viper", "Himalayan Green Pit Viper", "Cantors Pit Viper", "Nicobar Pit Viper", | |
| "Large-scaled Pit Viper", "Levantine Viper", "Blunt-nosed Viper", "Himalayan Leaf-nosed Pit Viper", | |
| "Eyelash Pit Viper", "Mangshan Pit Viper", "Red-necked Keelback Viper", "Indian Rat Snake", | |
| "Trinket Snake", "Common Trinket Snake", "Oriental Rat Snake", "Beauty Rat Snake", "Copper-headed Trinket Snake", | |
| "Indian Smooth Snake", "Green Keelback", "Olive Keelback", "Checkered Keelback", "Buff-striped Keelback", | |
| "Striped Keelback", "Himalayan Keelback", "Mountain Keelback", "Assam Keelback", "Yellow-spotted Keelback", | |
| "Red-necked Keelback", "Tiger Keelback", "Green Vine Snake", "Brown Vine Snake", "Long-nosed Vine Snake", | |
| "Common Bronzeback Tree Snake", "Painted Bronzeback", "Green Bronzeback", "Andaman Bronzeback", | |
| "Black-headed Royal Snake", "Indian Egg-eating Snake", "Indian Wolf Snake", "Barred Wolf Snake", | |
| "Travancore Wolf Snake", "Common Cat Snake", "Beddomes Cat Snake", "Forstens Cat Snake", "Mountain Cat Snake", | |
| "Andaman Cat Snake", "Common Kukri Snake", "Banded Kukri Snake", "Ocellated Kukri Snake", "Coral Kukri Snake", | |
| "Streaked Kukri Snake", "Black Kukri Snake", "Olive Kukri Snake", "Common Mock Viper", "Glossy Marsh Snake", | |
| "Indian Water Snake", "Rainbow Water Snake", "Asiatic Water Snake", "Fishing Snake", "Smooth Water Snake", | |
| "Black-headed Snake", "Indian Rock Python", "Burmese Python", "Reticulated Python", "Ball Python", "Sand Boa", | |
| "Red Sand Boa", "Rough-scaled Sand Boa", "Common Sand Boa", "Arabian Sand Boa", "Dumerils Boa", "Rubber Boa", | |
| "Rosy Boa", "Madurai Shieldtail", "Travancore Shieldtail", "Kerala Shieldtail", "Black Shieldtail", | |
| "Striped Shieldtail", "Kolli Hills Shieldtail", "Nilgiri Shieldtail", "Purple Shieldtail", "Coorg Shieldtail", | |
| "Karnataka Shieldtail", "White-spotted Shieldtail", "Brown Shieldtail", "Speckled Shieldtail", "Indian Worm Snake", | |
| "Brahminy Blind Snake", "Beaked Worm Snake", "Slender Worm Snake", "Thread Snake", "Blind Burrowing Snake", | |
| "Tiny Blind Snake", "Long-tailed Blind Snake", "Flowerpot Snake", "Earth Snake", "Ornate Flying Snake", | |
| "Paradise Flying Snake", "Twin-barred Tree Snake", "Golden Tree Snake", "Green Tree Snake", "Slender Tree Snake", | |
| "Forest Vine Snake", "Bamboo Tree Snake", "Spotted Tree Snake", "Bridle Snake", "Hill Tree Snake", "Flying Vine Snake", | |
| "Long-headed Tree Snake", "Forest Bronzeback", "Yellow Tree Snake", "Checkered Water Snake", "Smooth Water Snake", | |
| "Dog-faced Water Snake", "Mud Snake", "Freshwater Snake", "Reed Snake", "Marsh Snake", "Rice Paddy Snake", | |
| "Mangrove Water Snake", "River Snake", "Stream Snake", "Pond Snake", "Wetland Snake", "Coastal Water Snake", | |
| "Estuarine Snake", "Saltwater Snake", "Delta Snake", "Swamp Snake", "Water Kukri Snake", "Aquatic Keelback", | |
| "Himalayan Rat Snake", "Himalayan Trinket Snake", "Himalayan Wolf Snake", "Himalayan Cat Snake", "Himalayan Vine Snake", | |
| "Forest Cobra", "Hill Keelback", "Mountain Bronzeback", "Cloud Forest Snake", "Nilgiri Forest Snake", "Khasi Hill Snake", | |
| "Arunachal Green Snake", "Sikkim Mountain Snake", "Assam Forest Snake", "Darjeeling Snake", "Eastern Hill Snake", | |
| "Western Ghats Snake", "Evergreen Forest Snake", "Highland Bamboo Snake", "Mist Forest Snake", "Indian Dwarf Snake", | |
| "Indian Black Snake", "Brown Snake", "Speckled Brown Snake", "Black-striped Snake", "Ring-necked Snake", "Reed Snake", | |
| "Forest Ground Snake", "Spotted Ground Snake", "Burrowing Snake", "Indian Green Snake", "Long-tailed Snake", | |
| "Thick-bodied Snake", "Slender-bodied Snake", "Golden-backed Snake", "White-bellied Snake", "Red-striped Snake", | |
| "Grey Marsh Snake", "Indian Leaf Snake", "Bamboo Forest Snake", "Highland Water Snake", "Eastern Vine Snake", | |
| "Southern Cat Snake", "Northern Wolf Snake", "Indian Cliff Snake", "Coastal Forest Snake", "Dry-zone Snake", | |
| "Rainforest Snake", "Savannah Snake", "Rock-dwelling Snake", "Cave Snake", "Mossy Snake", "Leaf-litter Snake", | |
| "Jungle Ground Snake", "Streamside Snake", "Pebble Snake", "Desert Sand Snake", "Thorn Forest Snake", "Grassland Snake", | |
| "Riverbank Snake", "Woodland Snake", "Tree-hole Snake", "Plateau Snake", "Wet Forest Snake", "Black Forest Snake", | |
| "Orange-striped Snake", "Red Bamboo Snake", "Blue Forest Snake", "Narrow-headed Snake", "Thick-tailed Snake", | |
| "White-striped Snake", "Silver Snake", "Green-striped Snake", "Hill Stream Snake", "Monsoon Snake", "Valley Snake", | |
| "Forest Marsh Snake", "Small-eyed Snake", "Long-snouted Snake", "Brown Marsh Snake", "Dark Vine Snake", "Woodland Keelback", | |
| "Grass Keelback", "Hill Rat Snake", "Assam Cat Snake", "Himalayan Bronzeback", "Indian Cliff Keelback", "Forest Wolf Snake", | |
| "Bamboo Pit Snake", "Green Forest Pit Snake", "Andaman Wolf Snake", "Nicobar Wolf Snake", "Indian Reed Snake", "Black Marsh Snake", | |
| "Grey Vine Snake", "Slender Cat Snake", "Yellow Vine Snake", "Wetland Keelback", "Woodland Cat Snake", "Black Tree Snake", | |
| "Mangrove Snake", "Mud Burrowing Snake", "Eastern Ground Snake", "Western Ground Snake", "Dry Forest Snake", "Highland Pit Snake", | |
| "Small Forest Snake", "Broad-headed Snake", "Indian Hill Snake", "Mountain Reed Snake", "Deep Forest Snake", "Indian Stream Snake", | |
| "Spotted Tree Snake", "Red Forest Snake", "Narrow-striped Snake", "Indian Marsh Keelback", "Green Marsh Snake", "Black Bamboo Snake", | |
| "Grass Vine Snake", "Rain Snake", "Forest Leaf Snake", "Black Hill Snake", "Long Forest Snake", "Indian Water Keelback", | |
| "Yellow Marsh Snake", "Southern Bamboo Snake", "Coastal Ground Snake", "Indian Forest Snake", "Eastern Bamboo Snake", "Indian Reed Keelback"] | |
| # ----------------------------------- | |
| # Metadata Mapping Function | |
| # ----------------------------------- | |
| def get_snake_metadata(parsed): | |
| species_name = parsed["species_name"] | |
| row = df[df["binomial"].str.lower() == species_name.lower()] | |
| if row.empty: | |
| return { | |
| "Venomous status": "Unknown", | |
| "Recommended Antivenom": "Not Available" | |
| } | |
| row = row.iloc[0] | |
| venom_status = "Venomous" if row["venom_status"] == 1 else "Non-Venomous" | |
| antivenom = row["antivenom Name"] if row["antivenom Name"] != "Not applicable" else "None" | |
| habitat = row.get("region", "Not available") | |
| return { | |
| "species": species_name, | |
| "confidence": parsed["confidence"], | |
| "venom_status": venom_status, | |
| "antivenom": antivenom, | |
| "habitat": habitat, | |
| "about": parsed["about_snake"] | |
| } | |
| # ----------------------------------- | |
| # LLM Snake Identifier | |
| # ----------------------------------- | |
| def LLM_snake_identifier(description: str) -> dict: | |
| if client is None: | |
| return {"error": "LLM service unavailable"} | |
| system_prompt = ( | |
| "You are a professional snake taxonomy expert.\n" | |
| "You MUST choose species names strictly from the provided allowed list.\n" | |
| "Return ONLY valid JSON.\n" | |
| "Return exactly 5 most probable species names.\n" | |
| ) | |
| allowed_species_text = "\n".join(ALLOWED_SPECIES) | |
| user_prompt = f""" | |
| Allowed species list: | |
| {allowed_species_text} | |
| Return JSON in this exact format: | |
| {{ | |
| "species_names": [ | |
| "name1", | |
| "name2", | |
| "name3", | |
| "name4", | |
| "name5" | |
| ] | |
| }} | |
| Snake description: | |
| \"\"\"{description}\"\"\" | |
| """ | |
| try: | |
| response = client.chat.completions.create( | |
| model="openai/gpt-oss-20b", | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": user_prompt} | |
| ], | |
| temperature=0.1, | |
| stream=False | |
| ) | |
| raw_output = response.choices[0].message.content.strip() | |
| # Extract JSON safely | |
| start = raw_output.find("{") | |
| end = raw_output.rfind("}") + 1 | |
| if start == -1 or end == 0: | |
| raise ValueError("Invalid JSON output") | |
| parsed = json.loads(raw_output[start:end]) | |
| # Validation | |
| if "species_names" not in parsed: | |
| raise ValueError("species_names key missing") | |
| if not isinstance(parsed["species_names"], list): | |
| raise ValueError("species_names must be a list") | |
| if len(parsed["species_names"]) != 5: | |
| raise ValueError("Must return exactly 5 species") | |
| for species in parsed["species_names"]: | |
| if species not in ALLOWED_SPECIES: | |
| raise ValueError(f"Invalid Species returned: {species}") | |
| return parsed | |
| except Exception as e: | |
| return {"error": str(e)} |