File size: 7,024 Bytes
0a3f537
 
0d7e2a6
b80ac7f
a600a71
 
 
64d148d
a600a71
ffdc25d
a600a71
895038b
0a3f537
 
 
 
00bd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a600a71
 
 
00bd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f762f0
 
a600a71
00bd641
8f762f0
 
00bd641
8f762f0
 
00bd641
 
 
8f762f0
00bd641
 
8f762f0
 
00bd641
 
 
 
 
 
 
8f762f0
 
00bd641
 
 
8f762f0
 
00bd641
 
 
 
8f762f0
 
00bd641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d00726f
236c9cf
8b0dc3c
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python
# coding: utf-8
import os 
import pygsheets
#print(os.environ['py_api'])
#import json
#stud_obj = json.loads(str(os.environ['py_api']))

#gc = pygsheets.authorize(client_secret= stud_obj )
#gc = pygsheets.authorize(client_secret= os.environ['py_api'])
gc = pygsheets.authorize(service_account_env_var = 'service_acc')

# ## Import Libs

# In[54]:
import pandas as pd 
import sklearn
import numpy as np
import matplotlib.pyplot as plt
import random 
from pythainlp import word_tokenize, Tokenizer
import re
from sklearn.naive_bayes import MultinomialNB

df_product_title = pd.read_csv('product_title_100.csv')
df = df_product_title[df_product_title.subcategory!='อื่นๆ'].copy()

target = df.iloc[:, 2]
title = df.iloc[:, 4]
rand = random.randint(0,len(df))
print('Target example:',target[rand:rand+1].values[0])
print('Title example:',title[rand:rand+1].values[0])
print('Token example:',word_tokenize(title[rand:rand+1].values[0],engine='longest'))

# In[234]:
sh = gc.open('Subcategory Prediction')
wk = sh.worksheet_by_title('huggingface-test')
wk2 = sh.worksheet_by_title('correction')

def token_processing(token): 
    res = re.sub(r'[^a-zก-๙1-9]', '', token.lower())
    if res != '' :
        return res 
# In[234]:
title_split = []
num=1
for i in list(title):
    word_split = word_tokenize(i,engine='longest')
    title_split_temp =[]
    for j in word_split:
        res = token_processing(j)
        if res != None : title_split_temp.append(res)
    title_split.append(title_split_temp) 
    if num%1000==0 : 
        print(num,'/',len(title))
    num+=1

# In[235]:
#title_split
all_title_split = []
for i in title_split:
    for j in i :
        res = token_processing(j)
        if res != None : all_title_split.append(res)
all_char= set(all_title_split)
print(len(all_char))
char_map = dict(zip(all_char, range(len(all_char))))
# In[236]:
def count_str(string):
    global all_char, char_map
    result = np.zeros(len(all_char))
    np_str = np.array(list(string))
    str_char, str_char_count = np.unique(np_str, return_counts=True)
    for char, count in zip(str_char, str_char_count):
        try: result[char_map[char]] = count
        except: pass
    return result

# In[239]:
# run on data set
temp = np.vectorize(count_str, otypes=[object])(title_split)
print('done1')
# In[240]:
test_2=[]
num=0
for sl in temp:
    test =[]
    for e in sl:
        test.append(e)
    test_2.append(test)
x_f1 = np.array(test_2)

# In[242]:
model = MultinomialNB(fit_prior=False, alpha = 0.1)
model.fit(x_f1, target)

y_pred = model.predict(x_f1)
print("Model Acc. on train data %f%%"
       % ((target == y_pred).sum() / x_f1.shape[0] * 100))
# In[259]:
def predict_prob_df(word):
    token = word_tokenize(word,engine='longest')
    clean_token = []
    for i in token: 
        res = token_processing(i)
        if res != None : clean_token.append(res)
    
    prob_each_class = (model.predict_proba(count_str(clean_token).reshape(1,-1))).tolist()[0]
    each_class_name = model.classes_.tolist()
    pr = pd.DataFrame(prob_each_class,each_class_name).reset_index().rename(columns={'index':'predict',0:'prob'}).sort_values('prob',ascending=False).reset_index()
    return pr

# In[259] test 2 
import gradio as gr
pd.set_option('display.float_format', lambda x: '%5f' % x)
demo = gr.Blocks()

def subcat_predict(word):
    global pr, text_
    text_ = word
    pr = predict_prob_df(word)
    return dict(zip(pr.loc[:2,'predict'],pr.loc[:2,'prob']))
log = []
log_correct= []
num = 0 
num_2 = 0

def correct_number1(number):
    global num 
    num+=1
    log.append([text_,'1-right',pr.loc[0,'predict'],pr.loc[0,'prob']])
    if (num % 10 == 0) :
        wk.set_dataframe(pd.DataFrame(log,columns=['title','label','sc_pred','prob']),'A1')
    return 'thank for teaching the model'

def correct_number2(number):
    global num 
    log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']])
    log.append([text_,'2-right',pr.loc[1,'predict'],pr.loc[1,'prob']])
    if (num % 10 == 0) :
        wk.set_dataframe(pd.DataFrame(log,columns=['title','label','sc_pred','prob']),'A1')
    return 'thank for teaching the model'

def correct_number3(number):
    global num
    log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']])
    log.append([text_,'2-wrong',pr.loc[1,'predict'],pr.loc[1,'prob']])    
    log.append([text_,'3-right',pr.loc[2,'predict'],pr.loc[2,'prob']]) 
    if (num % 10 == 0) :
        wk.set_dataframe(pd.DataFrame(log,columns=['title','label','sc_pred','prob']),'A1')
    return 'thank for teaching the model'
    
def feedback(correction_input,text_input):
    global num , num_2

    log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']])
    log.append([text_,'2-wrong',pr.loc[1,'predict'],pr.loc[1,'prob']])    
    log.append([text_,'3-wrong',pr.loc[2,'predict'],pr.loc[2,'prob']])    
    log_correct.append([text_,'feedback',pr.loc[0,'predict'],pr.loc[0,'prob'],correction_input])
    if (num_2 % 5 == 0 ):
        wk2.set_dataframe(pd.DataFrame(log_correct,columns=['title','label','sc_pred','prob','real_sc']),'A1')
    return 'thank for teaching the model'
with demo:
    with gr.Row():
        with gr.Column():

            gr.Markdown("มาให้โมเดลทำนาย subcat จากชื่อ Product กันจ้า")
            with gr.Row():
                
                text_input = gr.Textbox(label='พิมพ์ชื่อ product แล้วกด Predict! ได้เลยจ้า')
                predict_button = gr.Button("Predict!")
         
            predict_button.click(subcat_predict, inputs=text_input, 
                                 outputs = gr.outputs.Label())
            gr.Markdown("ถ้าโมเดลทำนายออกมาถูกแล้วช่วยกดปุ่มให้หน่อยครับว่าถูกที่อันดับไหน (1,2,3)")
        
            with gr.Row():
                button_1 = gr.Button("1st is correct")
                button_2 = gr.Button("2nd is correct")
                button_3 = gr.Button("3rd is correct")
            
            thanks_box = gr.Textbox(label='')
                
            button_1.click(correct_number1, inputs=text_input,outputs=thanks_box)
            button_2.click(correct_number2, inputs=text_input,outputs=thanks_box)
            button_3.click(correct_number3, inputs=text_input,outputs=thanks_box)

        with gr.Column():
        
            gr.Markdown("ถ้าโมเดลทำนายผิดหมด รบกวนใส่ subcat ที่ถูกให้หน่อยครัช")
            with gr.Row():
            
                correction_input = gr.Dropdown(df.target.unique().tolist())
                button_feedback = gr.Button("Send Feedback")
            button_feedback.click(feedback, inputs=[correction_input,text_input], outputs=gr.outputs.Textbox(label=''))
    
demo.launch(share=True)