from transformers import pipeline import gradio as gr import os from huggingface_hub import login api_key = os.getenv("token") login(token = api_key) get_completion = pipeline("ner", model="elnasharomar2/PUNCERT_single_stages_50_epochs") label_names = ["O","QE","EX","QM","DOT","COM","SEMICOL","COL"] label_symbol = ["O",'؟!','!','؟','.','،','؛',':'] id2label = {i: label for i, label in zip(label_names,label_symbol)} def merge_tokens(tokens): merged_tokens = [] for token in tokens: if merged_tokens and token['entity'].startswith('I-') and merged_tokens[-1]['entity'].endswith(token['entity'][2:]): # If current token continues the entity of the last one, merge the two tokens last_token = merged_tokens[-1] last_token['word'] += token['word'].replace('##', '') last_token['end'] = token['end'] last_token['score'] = (last_token['score'] + token['score']) / 2 else: # Otherwise, add the token to the list merged_tokens.append(token) return merged_tokens def ner(input): output = get_completion(input) merged_tokens = merge_tokens(output) ## modification result ="" idx = 0 for i in output: result += text[idx:i["start"]] result += text[i["start"]:i["end"]] + f"{id2label[i["entity_group"]]}" idx = i["end"] result+=text[idx:] print(result) return {"text": result} # return {"text": input, "entities": merged_tokens} gr.close_all() demo = gr.Interface(fn=ner, inputs=[gr.Textbox(label="Text to find Punctuation", lines=2)], outputs=[gr.HighlightedText(label="Text with Punct")], title="Puncituation Predictor", description="Find Puncituations using the `BERT-base` model under the hood!", allow_flagging="never", examples=[]) demo.launch()