File size: 4,437 Bytes
90084cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app/models/llm.py

import re
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from app.utils.config import DEVICE, QWEN_MODEL_ID




tokenizer = AutoTokenizer.from_pretrained(
    QWEN_MODEL_ID,
    trust_remote_code=True
)

model = AutoModelForCausalLM.from_pretrained(
    QWEN_MODEL_ID,
    device_map="auto" if DEVICE == "cuda" else None,
    torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
    trust_remote_code=True
)
model.eval()



def strip_markdown(text: str) -> str:
    text = re.sub(r"\*\*(.*?)\*\*", r"\1", text)
    text = re.sub(r"\*(.*?)\*", r"\1", text)
    text = re.sub(r"#+\s*", "", text)
    text = re.sub(r"-\s+", "", text)
    text = re.sub(r"`+", "", text)
    text = text.replace("---", "")
    return text.strip()




@torch.no_grad()
def infer_common_name(
    species: str,
    domain: str,
    max_tokens: int = 16,
) -> str | None:
    """
    Uses LLM to infer the most widely accepted English common name.
    Returns None if no common name exists.
    """

    messages = [
        {
            "role": "system",
            "content": (
                "You are a taxonomy assistant. "
                "Return ONLY the most widely used English common name "
                "for the given scientific name. "
                "Do not explain or add extra text."
                "dont respond null for common name make sure u provide a common name"
            )
        },
        {
            "role": "user",
            "content": f"Scientific name: {species} ({domain})"
        }
    ]

    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    inputs = tokenizer([text], return_tensors="pt").to(model.device)

    outputs = model.generate(
        **inputs,
        max_new_tokens=max_tokens,
        do_sample=False,
        temperature=0.0,
        pad_token_id=tokenizer.eos_token_id,
    )

    generated_ids = outputs[:, inputs.input_ids.shape[1]:]
    response = tokenizer.decode(
        generated_ids[0],
        skip_special_tokens=True
    ).strip()

    if not response or response.lower() == "none":
        return None

    return response




def _build_messages(
    species: str,
    confidence: float,
    domain: str,
    top_k: list | None = None,
):
    alternatives = ""
    if top_k:
        alternatives = "\n".join(
            [f"{x['species']} ({x['similarity']:.2f})" for x in top_k[1:]]
        )

    system_message = (
        "You are a scientific biodiversity assistant. "
        "Provide factual, neutral descriptions of species. "
        "Do not mention instructions, rules, or formatting. "
        "Do not use markdown or bullet points."
    )

    user_message = (
        f"Species: {species}\n"
        f"Confidence: {confidence:.2f}\n\n"
        f"Alternative candidates:\n"
        f"{alternatives if alternatives else 'None'}\n\n"
        "Provide a factual description covering physical traits, "
        "natural habitat and distribution, diet or ecological role, "
        "conservation status, and relevant human interactions. "
        
    )

    return [
        {"role": "system", "content": system_message},
        {"role": "user", "content": user_message},
    ]



@torch.no_grad()
def explain_species(
    species: str,
    confidence: float,
    domain: str,
    top_k: list | None = None,
    max_tokens: int = 512,
):
    """
    Returns:
    {
        "common_name": str | None,
        "description": str
    }
    """

    COMMON_NAME_MIN_CONFIDENCE = 0.01
    common_name = None

    if confidence >= COMMON_NAME_MIN_CONFIDENCE:
        common_name = infer_common_name(species, domain)

    messages = _build_messages(species, confidence, domain, top_k)

    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    model_inputs = tokenizer([text], return_tensors="pt").to(model.device)

    outputs = model.generate(
        **model_inputs,
        max_new_tokens=max_tokens,
        do_sample=False,
        temperature=0.0,
        pad_token_id=tokenizer.eos_token_id,
    )

    generated_ids = outputs[:, model_inputs.input_ids.shape[1]:]
    response = tokenizer.decode(
        generated_ids[0],
        skip_special_tokens=True
    )

    return {
        "common_name": common_name,
        "description": strip_markdown(response),
    }