Spaces:
Running
Running
Commit ·
fac8a97
1
Parent(s): e028bfd
Finalll
Browse files2 unmodified lines34567893 unmodified lines13141516171855 unmodified lines747576777879808182838485868788899091929394952 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412511 unmodified lines1371381391401412 unmodified linesimport picklefrom huggingface_hub import hf_hub_downloadfrom Nested.nn.BertSeqTagger import BertSeqTaggerapp = FastAPI()print("Version 2...")3 unmodified lines# filename="tag_vocab.pkl"# )checkpoint_path = hf_hub_download(repo_id="SinaLab/Nested",filename="checkpoints/checkpoint_2.pt"55 unmodified linesmodel = load_model_from_checkpoint(model, ckpt, strict=False)# model.eval()def predict_ner(sentence: str, model, id2label: dict, device="cpu"):model.to(device)model.eval()words = sentence.split()tokenizer = getattr(model, "tokenizer", None)if tokenizer is None:raise ValueError("Model has no tokenizer. Use AutoTokenizer and attach it or pass it explicitly.")enc = tokenizer(words,is_split_into_words=True,return_tensors="pt",truncation=True,padding=False)enc = {k: v.to(device) for k, v in enc.items()}2 unmodified linesout = model(**enc)logits = out.logits if hasattr(out, "logits") else outexcept TypeError:if not hasattr(model, "transformer") or not hasattr(model, "classification_head"):raiseh = model.transformer(**enc).last_hidden_stateh = model.dropout(h) if hasattr(model, "dropout") else hlogits = model.classification_head(h)pred_ids = logits.argmax(dim=-1).squeeze(0).tolist()word_ids = enc.get("input_ids").new_tensor([0]) # placeholder to keep structureword_ids = tokenizer(words, is_split_into_words=True).word_ids()word_labels = []used = set()for tok_i, w_i in enumerate(word_ids):if w_i is None:continueif w_i in used:continueused.add(w_i)word_labels.append((words[w_i], id2label[pred_ids[tok_i]]))return word_labelsdef find_label_vocab(vocabs):for i, v in enumerate(vocabs):11 unmodified linessentence = "ذهب احمد الى السوق"# id2label = {i: s for i, s in enumerate(label_vocab.itos)}pairs = predict_ner(sentence, model, label_vocab, device="cpu")print(pairs)2 unmodified lines34567893 unmodified lines13141516171819202155 unmodified lines7778798081828384858687888990919293942 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212311 unmodified lines1351361371381391402 unmodified linesimport picklefrom huggingface_hub import hf_hub_downloadfrom Nested.nn.BertSeqTagger import BertSeqTaggerfrom transformers import AutoTokenizerapp = FastAPI()print("Version 2...")3 unmodified lines# filename="tag_vocab.pkl"# )pretrained_path = "aubmindlab/bert-base-arabertv2" # change if different in your trainingtokenizer = AutoTokenizer.from_pretrained(pretrained_path)checkpoint_path = hf_hub_download(repo_id="SinaLab/Nested",filename="checkpoints/checkpoint_2.pt"55 unmodified linesmodel = load_model_from_checkpoint(model, ckpt, strict=False)# model.eval()def predict_ner(sentence: str, model, tokenizer, id2label: dict, device="cpu", max_length=128):model.to(device)model.eval()words = sentence.split()enc = tokenizer(words,is_split_into_words=True,return_tensors="pt",truncation=True,max_length=max_length)enc = {k: v.to(device) for k, v in enc.items()}2 unmodified linesout = model(**enc)logits = out.logits if hasattr(out, "logits") else outexcept TypeError:# fallback for your custom BertSeqTagger-like modelh = model.transformer(**enc).last_hidden_stateif hasattr(model, "dropout"):h = model.dropout(h)logits = model.classification_head(h)pred_ids = logits.argmax(dim=-1)[0].tolist()word_ids = enc["input_ids"].new_zeros(enc["input_ids"].shape[1]).tolist()word_ids = tokenizer(words, is_split_into_words=True, truncation=True, max_length=max_length).word_ids()# first subtoken per word -> labelresults = []seen = set()for tok_i, w_i in enumerate(word_ids):if w_i is None or w_i in seen:continueseen.add(w_i)results.append((words[w_i], id2label[pred_ids[tok_i]]))return resultsdef find_label_vocab(vocabs):for i, v in enumerate(vocabs):11 unmodified linessentence = "ذهب احمد الى السوق"# id2label = {i: s for i, s in enumerate(label_vocab.itos)}# pairs = predict_ner(sentence, model, label_vocab, device="cpu")pairs = predict_ner(sentence, model, tokenizer, id2label, device="cpu")print(pairs)
app.py+21-22