Spaces:
Runtime error
Runtime error
Commit ·
00bd641
1
Parent(s): b70be40
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,20 +6,212 @@ print(os.environ['py_api'])
|
|
| 6 |
import json
|
| 7 |
stud_obj = json.loads(str(os.environ['py_api']))
|
| 8 |
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# ## Import Libs
|
| 11 |
|
| 12 |
# In[54]:
|
| 13 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def pygsheets_df(df,tab_name='huggingface-test',sheet_name = 'Subcategory Prediction'):
|
| 15 |
try:
|
| 16 |
-
|
| 17 |
-
sh = client.open(sheet_name)
|
| 18 |
wk = sh.worksheet_by_title(tab_name)
|
| 19 |
except:
|
| 20 |
wk = sh.add_worksheet(tab_name)
|
| 21 |
wk.set_dataframe(df,'A1')
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import json
|
| 7 |
stud_obj = json.loads(str(os.environ['py_api']))
|
| 8 |
|
| 9 |
+
##gc = pygsheets.authorize(client_secret= os.environ['py_api'])
|
| 10 |
+
gc = pygsheets.authorize(service_account_env_var = 'service_acc')
|
| 11 |
|
| 12 |
# ## Import Libs
|
| 13 |
|
| 14 |
# In[54]:
|
| 15 |
import pandas as pd
|
| 16 |
+
import sklearn
|
| 17 |
+
import numpy as np
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
import random
|
| 20 |
+
from pythainlp import word_tokenize, Tokenizer
|
| 21 |
+
import re
|
| 22 |
+
from sklearn.naive_bayes import MultinomialNB
|
| 23 |
+
|
| 24 |
+
df_product_title = pd.read_csv('product_title_100.csv')
|
| 25 |
+
df = df_product_title[df_product_title.subcategory!='อื่นๆ'].copy()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
target = df.iloc[:, 2]
|
| 29 |
+
title = df.iloc[:, 4]
|
| 30 |
+
rand = random.randint(0,len(df))
|
| 31 |
+
print('Target example:',target[rand:rand+1].values[0])
|
| 32 |
+
print('Title example:',title[rand:rand+1].values[0])
|
| 33 |
+
print('Token example:',word_tokenize(title[rand:rand+1].values[0],engine='longest'))
|
| 34 |
+
|
| 35 |
+
# In[234]:
|
| 36 |
+
|
| 37 |
+
|
| 38 |
def pygsheets_df(df,tab_name='huggingface-test',sheet_name = 'Subcategory Prediction'):
|
| 39 |
try:
|
| 40 |
+
sh = gc.open(sheet_name)
|
|
|
|
| 41 |
wk = sh.worksheet_by_title(tab_name)
|
| 42 |
except:
|
| 43 |
wk = sh.add_worksheet(tab_name)
|
| 44 |
wk.set_dataframe(df,'A1')
|
| 45 |
+
|
| 46 |
+
def token_processing(token):
|
| 47 |
+
res = re.sub(r'[^a-zก-๙1-9]', '', token.lower())
|
| 48 |
+
if res != '' :
|
| 49 |
+
return res
|
| 50 |
+
# In[234]:
|
| 51 |
+
title_split = []
|
| 52 |
+
num=1
|
| 53 |
+
for i in list(title):
|
| 54 |
+
word_split = word_tokenize(i,engine='longest')
|
| 55 |
+
title_split_temp =[]
|
| 56 |
+
for j in word_split:
|
| 57 |
+
res = token_processing(j)
|
| 58 |
+
if res != None : title_split_temp.append(res)
|
| 59 |
+
title_split.append(title_split_temp)
|
| 60 |
+
if num%1000==0 :
|
| 61 |
+
print(num,'/',len(title))
|
| 62 |
+
num+=1
|
| 63 |
+
|
| 64 |
+
# In[235]:
|
| 65 |
+
#title_split
|
| 66 |
+
all_title_split = []
|
| 67 |
+
for i in title_split:
|
| 68 |
+
for j in i :
|
| 69 |
+
res = token_processing(j)
|
| 70 |
+
if res != None : all_title_split.append(res)
|
| 71 |
+
all_char= set(all_title_split)
|
| 72 |
+
print(len(all_char))
|
| 73 |
+
char_map = dict(zip(all_char, range(len(all_char))))
|
| 74 |
+
# In[236]:
|
| 75 |
+
def count_str(string):
|
| 76 |
+
global all_char, char_map
|
| 77 |
+
result = np.zeros(len(all_char))
|
| 78 |
+
np_str = np.array(list(string))
|
| 79 |
+
str_char, str_char_count = np.unique(np_str, return_counts=True)
|
| 80 |
+
for char, count in zip(str_char, str_char_count):
|
| 81 |
+
try: result[char_map[char]] = count
|
| 82 |
+
except: pass
|
| 83 |
+
return result
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# In[239]:
|
| 87 |
+
# run on data set
|
| 88 |
+
temp = np.vectorize(count_str, otypes=[object])(title_split)
|
| 89 |
+
print('done1')
|
| 90 |
+
# In[240]:
|
| 91 |
+
test_2=[]
|
| 92 |
+
num=0
|
| 93 |
+
for sl in temp:
|
| 94 |
+
test =[]
|
| 95 |
+
for e in sl:
|
| 96 |
+
test.append(e)
|
| 97 |
+
test_2.append(test)
|
| 98 |
+
|
| 99 |
+
# In[241]:
|
| 100 |
+
x_f1 = np.array(test_2)
|
| 101 |
+
|
| 102 |
+
# In[242]:
|
| 103 |
+
model = MultinomialNB(fit_prior=False, alpha = 0.1)
|
| 104 |
+
model.fit(x_f1, target)
|
| 105 |
+
|
| 106 |
+
y_pred = model.predict(x_f1)
|
| 107 |
+
print("Model Acc. on train data %f%%"
|
| 108 |
+
% ((target == y_pred).sum() / x_f1.shape[0] * 100))
|
| 109 |
+
# In[258]:
|
| 110 |
+
## test prediictiion
|
| 111 |
+
word = 'เขียนบทความ'
|
| 112 |
+
token = word_tokenize(word,engine='longest')
|
| 113 |
+
clean_token = []
|
| 114 |
+
for i in token:
|
| 115 |
+
res = token_processing(i)
|
| 116 |
+
if res != None : clean_token.append(res)
|
| 117 |
+
## try: clean_token.remove('')
|
| 118 |
+
## except : pass
|
| 119 |
+
print('Tokenizied:',token)
|
| 120 |
+
print('Clean Tokenizied:',clean_token)
|
| 121 |
+
model.predict(count_str(clean_token).reshape(1,-1))[0]
|
| 122 |
+
|
| 123 |
+
# In[259]:
|
| 124 |
+
def predict_prob_df(word):
|
| 125 |
+
token = word_tokenize(word,engine='longest')
|
| 126 |
+
clean_token = []
|
| 127 |
+
for i in token:
|
| 128 |
+
res = token_processing(i)
|
| 129 |
+
if res != None : clean_token.append(res)
|
| 130 |
+
|
| 131 |
+
prob_each_class = (model.predict_proba(count_str(clean_token).reshape(1,-1))).tolist()[0]
|
| 132 |
+
each_class_name = model.classes_.tolist()
|
| 133 |
+
pr = pd.DataFrame(prob_each_class,each_class_name).reset_index().rename(columns={'index':'predict',0:'prob'}).sort_values('prob',ascending=False).reset_index()
|
| 134 |
+
return pr
|
| 135 |
+
|
| 136 |
+
# In[259] test 2
|
| 137 |
+
import gradio as gr
|
| 138 |
+
pd.set_option('display.float_format', lambda x: '%5f' % x)
|
| 139 |
+
demo = gr.Blocks()
|
| 140 |
+
|
| 141 |
+
def subcat_predict(word):
|
| 142 |
+
global pr, text_
|
| 143 |
+
text_ = word
|
| 144 |
+
pr = predict_prob_df(word)
|
| 145 |
+
return dict(zip(pr.loc[:2,'predict'],pr.loc[:2,'prob']))
|
| 146 |
+
log = []
|
| 147 |
+
log_correct= []
|
| 148 |
+
num = 0
|
| 149 |
+
num_2 = 0
|
| 150 |
+
def correct_number1(number):
|
| 151 |
+
global num
|
| 152 |
+
log.append([text_,'1-right',pr.loc[0,'predict'],pr.loc[0,'prob']])
|
| 153 |
+
num +=1
|
| 154 |
+
pygsheets_df(pd.DataFrame(log,columns=['title','label','sc_pred','prob']))
|
| 155 |
+
return 'thank for teaching the model'
|
| 156 |
+
|
| 157 |
+
def correct_number2(number):
|
| 158 |
+
global num
|
| 159 |
+
log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']])
|
| 160 |
+
log.append([text_,'2-right',pr.loc[1,'predict'],pr.loc[1,'prob']])
|
| 161 |
+
pygsheets_df(pd.DataFrame(log,columns=['title','label','sc_pred','prob']))
|
| 162 |
+
return 'thank for teaching the model'
|
| 163 |
+
|
| 164 |
+
def correct_number3(number):
|
| 165 |
+
global num
|
| 166 |
+
log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']])
|
| 167 |
+
log.append([text_,'2-wrong',pr.loc[1,'predict'],pr.loc[1,'prob']])
|
| 168 |
+
log.append([text_,'3-right',pr.loc[2,'predict'],pr.loc[2,'prob']])
|
| 169 |
+
|
| 170 |
+
pygsheets_df(pd.DataFrame(log,columns=['title','label','sc_pred','prob']))
|
| 171 |
+
return 'thank for teaching the model'
|
| 172 |
+
|
| 173 |
+
def feedback(correction_input,text_input):
|
| 174 |
+
global num_2
|
| 175 |
+
log.append([text_,'1-wrong',pr.loc[0,'predict'],pr.loc[0,'prob']])
|
| 176 |
+
log.append([text_,'2-wrong',pr.loc[1,'predict'],pr.loc[1,'prob']])
|
| 177 |
+
log.append([text_,'3-wrong',pr.loc[2,'predict'],pr.loc[2,'prob']])
|
| 178 |
+
log_correct.append([text_,'feedback',pr.loc[0,'predict'],pr.loc[0,'prob'],correction_input])
|
| 179 |
+
pygsheets_df(pd.DataFrame(log,columns=['title','label','sc_pred','prob']))
|
| 180 |
+
pygsheets_df(pd.DataFrame(log_correct,columns=['title','label','sc_pred','prob','real_sc']),tab_name = 'correction')
|
| 181 |
+
return 'thank for teaching the model'
|
| 182 |
+
with demo:
|
| 183 |
+
|
| 184 |
+
with gr.Row():
|
| 185 |
+
with gr.Column():
|
| 186 |
+
|
| 187 |
+
gr.Markdown("มาให้โมเดลทำนาย subcat จากชื่อ Product กันจ้า")
|
| 188 |
+
with gr.Row():
|
| 189 |
+
|
| 190 |
+
text_input = gr.Textbox(label='พิมพ์ชื่อ product แล้วกด Predict! ได้เลยจ้า')
|
| 191 |
+
predict_button = gr.Button("Predict!")
|
| 192 |
+
|
| 193 |
+
predict_button.click(subcat_predict, inputs=text_input,
|
| 194 |
+
outputs = gr.outputs.Label())
|
| 195 |
+
gr.Markdown("ถ้าโมเดลทำนายออกมาถูกแล้วช่วยกดปุ่มให้หน่อยครับว่าถูกที่อันดับไหน (1,2,3)")
|
| 196 |
+
|
| 197 |
+
with gr.Row():
|
| 198 |
+
button_1 = gr.Button("1st is correct")
|
| 199 |
+
button_2 = gr.Button("2nd is correct")
|
| 200 |
+
button_3 = gr.Button("3rd is correct")
|
| 201 |
+
|
| 202 |
+
thanks_box = gr.Textbox(label='')
|
| 203 |
+
|
| 204 |
+
button_1.click(correct_number1, inputs=text_input,outputs=thanks_box)
|
| 205 |
+
button_2.click(correct_number2, inputs=text_input,outputs=thanks_box)
|
| 206 |
+
button_3.click(correct_number3, inputs=text_input,outputs=thanks_box)
|
| 207 |
+
|
| 208 |
+
with gr.Column():
|
| 209 |
+
|
| 210 |
+
gr.Markdown("ถ้าโมเดลทำนายผิดหมด รบกวนใส่ subcat ที่ถูกให้หน่อยครัช")
|
| 211 |
+
with gr.Row():
|
| 212 |
+
|
| 213 |
+
correction_input = gr.Dropdown(df.target.unique().tolist())
|
| 214 |
+
button_feedback = gr.Button("Send Feedback")
|
| 215 |
+
button_feedback.click(feedback, inputs=[correction_input,text_input], outputs=gr.outputs.Textbox(label=''))
|
| 216 |
+
|
| 217 |
+
demo.launch(share=True)
|