File size: 1,624 Bytes
e6d5ea5
 
 
 
 
 
c876259
 
d2540d8
63d92be
 
d2540d8
 
 
c876259
029f31f
c876259
 
d2540d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5294145
 
 
8a1cb4e
d2540d8
 
 
 
6672b93
d2540d8
 
 
 
 
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
import gradio as gr
from transformers import BertTokenizer, BertForSequenceClassification
import numpy as np
import re
import torch

tokenizer = BertTokenizer.from_pretrained(r'./model')
model = BertForSequenceClassification.from_pretrained(r'./model', num_labels = 6)

labels = ['伤感', '快乐', '励志', '宣泄', '平静', '感人']

def preprocess(temp):
    temp = re.sub(u"\n\n", "\n", temp)
    temp = re.sub(u"(^\n)|(\n$)", "", temp)
    temp = re.sub(u",", ",", temp)
    temp = re.sub(u"\?", "?", temp)
    temp = re.sub(u"!", "!", temp)
    temp = re.sub(u".", "。", temp)
    temp = re.sub('[^\u4e00-\u9fa5,。?!\n]+', '', temp)
    temp = re.sub(u"\n", ",", temp)
    for _ in range(int(len(temp) / 2)):
        temp = re.sub(u",,|!!|??|。。", ",", temp)
        temp = re.sub(u",!|!,", "!", temp)
        temp = re.sub(u",?|?,", "?", temp)
        temp = re.sub(u",。|。,", "。", temp)
    temp = temp.strip(',')

    return temp

def classify_text(inp):
    inp = preprocess(inp)
    print(inp)
    with torch.no_grad():
        logits = model(**inputs).logits
    print(logits)
    # logits = torch.nn.Softmax(dim=0)(logits)
    # print(logits)
    # return {labels[i]: float(logits[i].item()) for i in range(len(labels))}
    return {logits.argmax().item() : labels[logits.argmax().item()]}

gr.Interface(
    classify_text,
    # gr.inputs.Image(),
    gr.inputs.Textbox(lines=5,default=""),
    outputs = 'label'
    # inputs='image',
    # outputs='label',
    # examples=[["images/cheetah1.jpg"], ["images/lion.jpg"]],
).launch(debug=True)