Spaces:
Running
Running
File size: 8,902 Bytes
aef0118 ca6eb6e aef0118 aa9f0d3 aef0118 598ac39 aef0118 7832a25 ca6eb6e 80dc20b e597fdc aa9f0d3 ca6eb6e e597fdc ca6eb6e aef0118 ca6eb6e aef0118 ca6eb6e 837263f ca6eb6e bfc4d6a aef0118 bfc4d6a aef0118 ca6eb6e aef0118 bfc4d6a ca6eb6e 598ac39 80dc20b 598ac39 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 e597fdc aa9f0d3 |
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 |
import torch
import json
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import openai
SYSTEM_PROMPT = (
"You are an advanced AI model specialized in extracting aspects and determining their sentiment polarity from customer reviews.\n\n"
"Instructions:\n"
"1. Extract only the aspects (nouns) mentioned in the review.\n"
"2. Assign a sentiment to each aspect: \"positive\", \"negative\", or \"neutral\".\n"
"3. Return aspects in the same language as they appear.\n"
"4. An aspect must be a noun that refers to a specific item or service the user described.\n"
"5. Ignore adjectives, general ideas, and vague topics.\n"
"6. Do NOT translate, explain, or add extra text.\n"
"7. The output must be just a valid JSON list with 'aspect' and 'sentiment'. Start with `[` and stop at `]`.\n"
"8. Do NOT output the instructions, review, or any text β only one output JSON list.\n"
"9. Just one output and one review."
)
MODEL_OPTIONS = {
"Araberta": {
"base": "asmashayea/absa-araberta",
"adapter": "asmashayea/absa-araberta"
},
"mT5": {
"base": "google/mt5-base",
"adapter": "asmashayea/mt4-absa"
},
"mBART": {
"base": "facebook/mbart-large-50-many-to-many-mmt",
"adapter": "asmashayea/mbart-absa"
},
"GPT3.5": {"base": "openai/gpt-3.5-turbo",
"model_id": "ft:gpt-3.5-turbo-0125:asma:gpt-3-5-turbo-absa:Bb6gmwkE"},
"GPT4o": {"base": "openai/gpt-4o",
"model_id": "ft:gpt-4o-mini-2024-07-18:asma:gpt4-finetune-absa:BazoEjnp"},
"ALLaM": {
"base": "ALLaM-AI/ALLaM-7B-Instruct-preview",
"adapter": "asmashayea/allam-absa"
},
"DeepSeek": {
"base": "deepseek-ai/deepseek-llm-7b-chat",
"adapter": "asmashayea/deepseek-absa"
}
}
cached_models = {}
# β
Reusable for both mT5 + mBART
def load_mt5_bart(model_key):
base_id = MODEL_OPTIONS[model_key]["base"]
adapter_id = MODEL_OPTIONS[model_key]["adapter"]
tokenizer = AutoTokenizer.from_pretrained(adapter_id)
base_model = AutoModelForSeq2SeqLM.from_pretrained(base_id)
peft_model = PeftModel.from_pretrained(base_model, adapter_id)
peft_model.eval()
cached_models[model_key] = (tokenizer, peft_model)
return tokenizer, peft_model
def infer_t5_bart(text, model_choice):
tokenizer, peft_model = load_mt5_bart(model_choice)
prompt = SYSTEM_PROMPT + f"\n\nReview: {text}"
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(peft_model.device)
with torch.no_grad():
outputs = peft_model.generate(
**inputs,
max_new_tokens=256,
num_beams=4,
do_sample=False,
temperature=0.0,
early_stopping=True,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
decoded = decoded.replace('<extra_id_0>', '').replace('</s>', '').strip()
try:
return json.loads(decoded)
except json.JSONDecodeError:
return {"raw_output": decoded, "error": "Invalid JSON"}
OPENAI_API_KEY = "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"
openai.api_key = OPENAI_API_KEY
def infer_gpt_absa(text, model_key):
MODEL_ID = MODEL_OPTIONS[model_key]["model_id"]
try:
response = openai.chat.completions.create(
model=MODEL_ID,
messages=[
{
"role": "system",
"content": SYSTEM_PROMPT
},
{
"role": "user",
"content": text
}
],
temperature=0
)
decoded = response.choices[0].message.content.strip()
return json.loads(decoded)
except Exception as e:
return {"error": str(e)}
def infer_allam(review_text):
tokenizer, model = cached_models.get("ALLaM") or load_allam()
prompt = tokenizer.apply_chat_template(
[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": review_text}
],
tokenize=False
)
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(model.device)
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=128,
do_sample=False,
temperature=0.0,
pad_token_id=tokenizer.eos_token_id
)
decoded = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
try:
parsed = json.loads(decoded)
return parsed
except Exception as e:
return {"error": str(e), "raw": decoded}
def load_allam():
base_model = AutoModelForCausalLM.from_pretrained(
MODEL_OPTIONS["ALLaM"]["base"],
device_map="auto",
torch_dtype=torch.float16,
trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_OPTIONS["ALLaM"]["adapter"],
trust_remote_code=True
)
model = PeftModel.from_pretrained(base_model, MODEL_OPTIONS["ALLaM"]["adapter"])
cached_models["ALLaM"] = (tokenizer, model)
return tokenizer, model
def load_allam():
base = AutoModelForCausalLM.from_pretrained(
MODEL_OPTIONS["ALLaM"]["base"],
torch_dtype=torch.float16,
trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_OPTIONS["ALLaM"]["adapter"], trust_remote_code=True
)
model = PeftModel.from_pretrained(base, MODEL_OPTIONS["ALLaM"]["adapter"])
cached_models["ALLaM"] = (tokenizer, model)
return tokenizer, model
def infer_allam(review):
if "ALLaM" not in cached_models:
tokenizer, model = load_allam()
else:
tokenizer, model = cached_models["ALLaM"]
prompt = tokenizer.apply_chat_template([
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": review}
], tokenize=False)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=256)
decoded = tokenizer.decode(output[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
try:
return json.loads(decoded)
except:
return decoded
def build_deepseek_prompt(review_text, output=""):
return f"""<|system|>
You are an advanced AI model specialized in extracting aspects and determining their sentiment polarity from customer reviews.
Instructions:
1. Extract only the aspects (nouns) mentioned in the review.
2. Assign a sentiment to each aspect: "positive", "negative", or "neutral".
3. Return aspects in the same language as they appear.
4. An aspect must be a noun that refers to a specific item or service the user described.
5. Ignore adjectives, general ideas, and vague topics.
6. Do NOT translate, explain, or add extra text.
7. The output must be just a valid JSON list with 'aspect' and 'sentiment'. Start with `[` and stop at `]`.
8. Do NOT output the instructions, review, or any text β only one output JSON list.
9. Just one output and one review.
<|user|>
{review_text}
<|assistant|>
{output}""" # β
include the output here
def load_deepseek():
base = AutoModelForCausalLM.from_pretrained(
MODEL_OPTIONS["DeepSeek"]["base"],
torch_dtype=torch.float16,
trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_OPTIONS["DeepSeek"]["adapter"], trust_remote_code=True
)
model = PeftModel.from_pretrained(base, MODEL_OPTIONS["DeepSeek"]["adapter"])
cached_models["DeepSeek"] = (tokenizer, model)
return tokenizer, model
def infer_deepseek(review):
if "DeepSeek" not in cached_models:
tokenizer, model = load_deepseek()
else:
tokenizer, model = cached_models["DeepSeek"]
prompt = build_deepseek_prompt(review)
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(model.device)
with torch.no_grad():
output = model.generate(
**inputs,
max_new_tokens=128,
do_sample=False,
temperature=0.0,
pad_token_id=tokenizer.eos_token_id
)
decoded = tokenizer.decode(
output[0][inputs["input_ids"].shape[1]:],
skip_special_tokens=True
).strip()
try:
return json.loads(decoded)
except Exception as e:
print(f"β DeepSeek JSON parse error: {e}")
return decoded
|