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