Spaces:
Sleeping
Sleeping
Commit ·
7ebac28
1
Parent(s): 6d91ffe
Files changed (2)
- app.py+1-1
- inference.py+30-33
11 unmodified lines1213141516171811 unmodified linesfn=run_absa,inputs=[gr.Textbox(label="Arabic Review"),gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), label="Choose Model", value="mT5")],outputs=gr.Textbox(label="Extracted Aspect-Sentiment-Opinion Triplets"),title="Arabic ABSA (Aspect-Based Sentiment Analysis)",11 unmodified lines1213141516171811 unmodified linesfn=run_absa,inputs=[gr.Textbox(label="Arabic Review"),gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), label="Choose Model", value="Araberta")],outputs=gr.Textbox(label="Extracted Aspect-Sentiment-Opinion Triplets"),title="Arabic ABSA (Aspect-Based Sentiment Analysis)",
7 unmodified lines8910111213147 unmodified lines222324252627282930313233343536373839404142434445464748495051525 unmodified lines585960616263646566677 unmodified lines75767778798081828384858687888911 unmodified lines1011021031041051061071081096 unmodified lines1161171181191201211221 unmodified line1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561577 unmodified lines# Define supported models and their adapter IDsMODEL_OPTIONS = {"Araberta": {"base": "asmashayea/absa-araberta","adapter": "asmashayea/absa-araberta"7 unmodified lines"adapter": "asmashayea/mbart-absa"},"GPT3.5": {"base": "bigscience/bloom-560m", # example, not ideal for ABSA"adapter": "asmashayea/gpt-absa"},"GPT4o": {"base": "bigscience/bloom-560m", # example, not ideal for ABSA"adapter": "asmashayea/gpt-absa"}}cached_models = {}def load_araberta():path = "asmashayea/absa-arabert"tokenizer = AutoTokenizer.from_pretrained(path)base_model = AutoModel.from_pretrained(path)lora_config = LoraConfig.from_pretrained(path)lora_model = get_peft_model(base_model, lora_config)local_pt = hf_hub_download(repo_id="asmashayea/absa-arabert", filename="bilstm_crf_head.pt")config = AutoConfig.from_pretrained(path)model = BERT_BiLSTM_CRF(lora_model, config)model.load_state_dict(torch.load(local_pt))model.eval()cached_models["Araberta"] = (tokenizer, model)return tokenizer, model5 unmodified lineselse:tokenizer, model = cached_models["Araberta"]device = next(model.parameters()).deviceinputs = tokenizer(text, return_tensors='pt', truncation=True, padding='max_length', max_length=128)input_ids = inputs['input_ids'].to(device)attention_mask = inputs['attention_mask'].to(device)7 unmodified linesclean_tokens = [t for t in tokens if t not in tokenizer.all_special_tokens]clean_labels = [l for t, l in zip(tokens, predicted_labels) if t not in tokenizer.all_special_tokens]# Horizontal outputpairs = [f"{token}: {label}" for token, label in zip(clean_tokens, clean_labels)]horizontal_output = " | ".join(pairs)# Group by aspect spanaspects = []current_tokens = []current_sentiment = Nonefor token, label in zip(clean_tokens, clean_labels):if label.startswith("B-"):if current_tokens:11 unmodified lines"aspect": " ".join(current_tokens).replace("##", ""),"sentiment": current_sentiment})current_tokens = []current_sentiment = Noneif current_tokens:aspects.append({"aspect": " ".join(current_tokens).replace("##", ""),6 unmodified lines}def load_model(model_key):if model_key in cached_models:return cached_models[model_key]1 unmodified linebase_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)model = PeftModel.from_pretrained(base_model, adapter_id)model.eval()cached_models[model_key] = (tokenizer, model)return tokenizer, modeldef predict_absa(text, model_choice):if model_choice in ['mT5', 'mBART']:tokenizer, model = load_model(model_choice)decoded = infer_t5_prompt(text, tokenizer, model)elif model_choice == 'Araberta':decoded = infer_araberta(text)# prompt = f"استخرج الجوانب والآراء والمشاعر من النص التالي:\n{text}"# inputs = tokenizer(prompt, return_tensors="pt", truncation=True)# with torch.no_grad():# outputs = model.generate(**inputs, max_new_tokens=128)# decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)return decoded7 unmodified lines89101112137 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758595 unmodified lines6566676869707172737475767778797 unmodified lines8788899091929394959697989911 unmodified lines1111121131141151161176 unmodified lines1241251261271281291 unmodified line1311321331341351361371381391401411421431441451461471481491501511521531547 unmodified lines# Define supported models and their adapter IDsMODEL_OPTIONS = {"Araberta": {"base": "asmashayea/absa-araberta","adapter": "asmashayea/absa-araberta"7 unmodified lines"adapter": "asmashayea/mbart-absa"},"GPT3.5": {"base": "bigscience/bloom-560m", # placeholder"adapter": "asmashayea/gpt-absa"},"GPT4o": {"base": "bigscience/bloom-560m", # placeholder"adapter": "asmashayea/gpt-absa"}}cached_models = {}def load_araberta():path = "asmashayea/absa-arabert"device = "cuda" if torch.cuda.is_available() else "cpu"tokenizer = AutoTokenizer.from_pretrained(path)base_model = AutoModel.from_pretrained(path)# Load LoRA adapterlora_config = LoraConfig.from_pretrained(path)lora_model = get_peft_model(base_model, lora_config)# Download CRF head from Hublocal_pt = hf_hub_download(repo_id=path, filename="bilstm_crf_head.pt")config = AutoConfig.from_pretrained(path)model = BERT_BiLSTM_CRF(lora_model, config)# Always map to current devicestate_dict = torch.load(local_pt, map_location=torch.device(device))model.load_state_dict(state_dict)model.to(device).eval()cached_models["Araberta"] = (tokenizer, model)return tokenizer, model5 unmodified lineselse:tokenizer, model = cached_models["Araberta"]device = next(model.parameters()).deviceinputs = tokenizer(text,return_tensors='pt',truncation=True,padding='max_length',max_length=128)input_ids = inputs['input_ids'].to(device)attention_mask = inputs['attention_mask'].to(device)7 unmodified linesclean_tokens = [t for t in tokens if t not in tokenizer.all_special_tokens]clean_labels = [l for t, l in zip(tokens, predicted_labels) if t not in tokenizer.all_special_tokens]# Horizontal token:label pairspairs = [f"{token}: {label}" for token, label in zip(clean_tokens, clean_labels)]horizontal_output = " | ".join(pairs)# Group into aspect spansaspects = []current_tokens, current_sentiment = [], Nonefor token, label in zip(clean_tokens, clean_labels):if label.startswith("B-"):if current_tokens:11 unmodified lines"aspect": " ".join(current_tokens).replace("##", ""),"sentiment": current_sentiment})current_tokens, current_sentiment = [], Noneif current_tokens:aspects.append({"aspect": " ".join(current_tokens).replace("##", ""),6 unmodified lines}def load_model(model_key):if model_key in cached_models:return cached_models[model_key]1 unmodified linebase_id = MODEL_OPTIONS[model_key]["base"]adapter_id = MODEL_OPTIONS[model_key]["adapter"]device = "cuda" if torch.cuda.is_available() else "cpu"tokenizer = AutoTokenizer.from_pretrained(adapter_id)base_model = AutoModelForSeq2SeqLM.from_pretrained(base_id).to(device)model = PeftModel.from_pretrained(base_model, adapter_id).to(device)model.eval()cached_models[model_key] = (tokenizer, model)return tokenizer, modeldef predict_absa(text, model_choice):if model_choice in ['mT5', 'mBART']:tokenizer, model = load_model(model_choice)decoded = infer_t5_prompt(text, tokenizer, model)elif model_choice == 'Araberta':decoded = infer_araberta(text)else:decoded = {"error": f"Model {model_choice} not supported"}return decoded
app.py+1-1
inference.py+30-33