k3ybladewielder commited on
Commit
06001d1
1 Parent(s): 788312d
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+
3
+ get_completion = pipeline("ner", model="dslim/bert-base-NER")
4
+
5
+ def ner(input):
6
+ output = get_completion(input)
7
+ return {"text": input, "entities": output}
8
+
9
+ def merge_tokens(tokens):
10
+ '''
11
+ WHAT: Faz um loop entre os tokens para concatenar os tokens
12
+ com entidades I-* (intermediate token) aos B-* (begining token).
13
+
14
+ '''
15
+ merged_tokens = []
16
+ for token in tokens:
17
+ if merged_tokens and token['entity'].startswith('I-') and merged_tokens[-1]['entity'].endswith(token['entity'][2:]):
18
+ # Se a lista merged_tokens não estiver vazia.
19
+ # o token atual for um token intermediário (começa com 'I-').
20
+ # a entidade do último token processado terminar com a mesma entidade do token atual, excluindo o prefixo 'I-'.
21
+
22
+ last_token = merged_tokens[-1]
23
+ last_token['word'] += token['word'].replace('##', '')
24
+ last_token['end'] = token['end']
25
+ last_token['score'] = (last_token['score'] + token['score']) / 2
26
+ else:
27
+ merged_tokens.append(token)
28
+
29
+ return merged_tokens
30
+
31
+ def ner(input):
32
+ """
33
+ WHAT: Aplica a task de NER com o hugginface pipeline e concatena os tokens com a mesma entidade.
34
+ RETURN: retorna um dicionário com o token e suas entidades.
35
+ """
36
+ output = get_completion(input)
37
+ merged_tokens = merge_tokens(output)
38
+ return {"text": input, "entities": merged_tokens}
39
+
40
+ gr.close_all()
41
+ demo = gr.Interface(fn=ner,
42
+ inputs=[gr.Textbox(label="Text to find entities", lines=2)],
43
+ outputs=[gr.HighlightedText(label="Text with entities")],
44
+ title="NER with dslim/bert-base-NER",
45
+ description="Find entities using the `dslim/bert-base-NER` model under the hood!",
46
+ allow_flagging="never",
47
+ examples=["My name is Andrew, I'm building DeeplearningAI and I live in California", "My name is Poli, I live in Vienna and work at HuggingFace"])
48
+
49
+ demo.launch()