Corame commited on
Commit
74aceb5
·
verified ·
1 Parent(s): 46709b1

Upload gradio_final.py

Browse files
Files changed (1) hide show
  1. gradio_final.py +305 -0
gradio_final.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ # In[1]:
5
+
6
+
7
+ get_ipython().run_line_magic('load_ext', 'gradio')
8
+
9
+
10
+ # In[48]:
11
+
12
+
13
+ import gradio as gr
14
+ from llama_cpp import Llama
15
+ from langchain_community.llms import LlamaCpp
16
+ from langchain.prompts import PromptTemplate
17
+ import llama_cpp
18
+ from langchain.callbacks.manager import CallbackManager
19
+ from sentence_transformers import SentenceTransformer
20
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
21
+ import numpy as np
22
+ import pandas as pd
23
+ import re
24
+ import os
25
+ from sklearn.metrics.pairwise import cosine_similarity
26
+
27
+ model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-mpnet-base-v2',device='cpu')
28
+
29
+
30
+ # llm = LlamaCpp(
31
+ # model_path=r"C:\Users\Cora\.cache\lm-studio\models\YC-Chen\Breeze-7B-Instruct-v1_0-GGUF\breeze-7b-instruct-v1_0-q4_k_m.gguf",
32
+ # n_gpu_layers=100,
33
+ # n_batch=512,
34
+ # n_ctx=3000,
35
+ # f16_kv=True,
36
+ # callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),
37
+ # verbose=False,
38
+ # )
39
+
40
+ llm = LlamaCpp(
41
+ model_path=r"C:\Users\user\breeze-7b-instruct-v1_0-q4_k_m.gguf",
42
+ n_gpu_layers=100,
43
+ n_batch=512,
44
+ n_ctx=3000,
45
+ f16_kv=True,
46
+ callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),
47
+ verbose=False,
48
+ )
49
+
50
+ embedd_bk=pd.read_pickle(r"C:\Users\user\推薦系統實作\bk_description1_角色形容詞_677.pkl")
51
+ df_bk=pd.read_excel(r"C:\Users\user\推薦系統實作\bk_description1_角色形容詞短文.xlsx")
52
+
53
+ def invoke_with_temperature(prompt, temperature=0.4):
54
+ return llm.invoke(prompt, temperature=temperature)
55
+
56
+ def process_user_input(message):
57
+ user_mental_state4= PromptTemplate(
58
+ input_variables=["input"],
59
+ template="""[INST]<<SYS>>你是一位具有同理心的專業心理諮商師,沒有性別歧視,你可以客觀的根據談話內容的描述,判斷說話的人的心理困擾<</SYS>>
60
+ 請根據{input}描述三個最有可能心理困擾,輸出只包含三個心理困擾,回答格式只採用CSV格式,分隔符號使用逗號,參考以下範例:名詞1,名詞2,名詞3。[/INST]"""
61
+ )
62
+
63
+ user_character= PromptTemplate(
64
+ input_variables=["input"],
65
+ template="""[INST]<<SYS>>你是一位具有同理心的專業心理諮商師,沒有性別歧視,你可以客觀的根據談話內容的描述,判斷說話的大學生,在生活中的多重角色身分<</SYS>>
66
+ 請你根據談話內容{input},客觀的判斷說話的大學生,在談話內容中的角色,以及他生活中其他角色的身分,提供三個最有可能的角色身分名詞,
67
+ 輸出只包含三個身分名詞,回答格式只採用CSV格式,分隔符號使用逗號,參考以下範例:名詞1,名詞2,名詞3。[/INST]"""
68
+ )
69
+
70
+
71
+ df_user=pd.DataFrame(columns=["輸入內容","形容詞1", "形容詞2", "形容詞3", "角色1", "角色2", "角色3"])
72
+ #df_user_record=pd.read_excel(r"C:\Users\Cora\推薦系統實作\gradio系統歷史紀錄.xlsx")
73
+
74
+
75
+ prompt_value1=user_mental_state4.invoke({"input":message})
76
+ string=invoke_with_temperature(prompt_value1)
77
+ #print("\n")
78
+
79
+ # 將字符串分割為名詞
80
+ adjectives = [adj.strip() for adj in re.split('[,、,]', string)]
81
+
82
+ index=len(df_user)
83
+ df_user.loc[index, '輸入內容'] = message
84
+
85
+ # 確保形容詞數量符合欄位數量
86
+ if len(adjectives) == 3:
87
+ df_user.loc[index, '形容詞1'] = adjectives[0]
88
+ df_user.loc[index, '形容詞2'] = adjectives[1]
89
+ df_user.loc[index, '形容詞3'] = adjectives[2]
90
+
91
+ prompt_value2=user_character.invoke({"input":message})
92
+ string=invoke_with_temperature(prompt_value2)
93
+ #print("\n")
94
+
95
+ # 將字符串分割為名詞
96
+ character = [adj.strip() for adj in re.split('[,、,]', string)]
97
+ for i in range(min(len(character), 3)):
98
+ df_user.loc[index, f'角色{i+1}'] = character[i]
99
+ # if len(character) == 3:
100
+ # df_user.loc[index, '角色1'] = character[0]
101
+ # df_user.loc[index, '角色2'] = character[1]
102
+ # df_user.loc[index, '角色3'] = character[2]
103
+ df_user.to_excel("user_gradio系統.xlsx")
104
+ return df_user
105
+ #return message
106
+
107
+ def embedd_df_user(df_user):
108
+
109
+ columns_to_encode=df_user.loc[:,["形容詞1", "形容詞2", "形容詞3"]]
110
+
111
+ # 初始化一個空的 DataFrame,用來存儲向量化結果
112
+ embedd_user=df_user[["輸入內容"]]
113
+ #user_em= user_em.assign(形容詞1=None, 形容詞2=None, 形容詞3=None,角色1=None,角色2=None,角色3=None)
114
+ embedd_user= embedd_user.assign(形容詞1=None, 形容詞2=None, 形容詞3=None)
115
+
116
+
117
+ # 遍歷每一個單元格,將結果存入新的 DataFrame 中
118
+ i=len(df_user)-1
119
+ for col in columns_to_encode:
120
+ #print(i,col)
121
+ # 將每個單元格的內容進行向量化
122
+ embedd_user.at[i, col] = model.encode(df_user.at[i, col])
123
+
124
+ embedd_user.to_pickle(r"C:\Users\user\推薦系統實作\user_gradio系統.pkl")
125
+
126
+ return embedd_user
127
+ #word="happy"
128
+ #return word
129
+
130
+ def top_n_books_by_average(df, n=3):
131
+
132
+ # 根据 `average` 列降序排序
133
+ sorted_df = df.sort_values(by='average', ascending=False)
134
+
135
+ # 选择前 N 行
136
+ top_n_df = sorted_df.head(n)
137
+
138
+ # 提取书名列
139
+ top_books = top_n_df['書名'].tolist()
140
+
141
+ return top_books,sorted_df
142
+
143
+ def similarity(embedd_user,embedd_bk,df_bk):
144
+ df_similarity= pd.DataFrame(df_bk[['書名','短文','URL',"形容詞1", "形容詞2", "形容詞3", '角色1', '角色2', '角色3']])
145
+ df_similarity['average'] = np.nan
146
+ #for p in range(len(embedd_user)):
147
+ index=len(embedd_user)-1
148
+ for k in range(len(embedd_bk)):
149
+ list=[]
150
+ for i in range(1,4):
151
+ for j in range(3,6):
152
+ vec1=embedd_user.iloc[index,i]#i是第i個形容詞,index是第幾個是使用者輸入
153
+ vec2=embedd_bk.iloc[k,j]
154
+ similarity = cosine_similarity([vec1], [vec2])
155
+ list.append(similarity[0][0])
156
+ # 计算总和
157
+ total_sum = sum(list)
158
+ # 计算数量
159
+ count = len(list)
160
+ # 计算平均值
161
+ average = total_sum / count
162
+ df_similarity.loc[k,'average']=average
163
+
164
+ top_books,sorted_df = top_n_books_by_average(df_similarity)
165
+ return sorted_df
166
+
167
+ def filter(sorted_df,df_user):
168
+ filter_prompt4 = PromptTemplate(
169
+ input_variables=["mental_issue", "user_identity"," book","book_reader", "book_description"],
170
+ template="""[INST]<<SYS>>你是專業的心理諮商師和書籍推薦專家,擅長根據使用者的心理問題、身份特質,以及書名、書籍針對的主題和適合的讀者,判斷書籍是否適合推薦給使用者。
171
+
172
+ 你的目的是幫助讀者找到可以緩解心理問題的書籍。請注意:
173
+ 1. 若書籍針對的問題與使用者的心理問題有關聯,即使書籍適合的讀者群與使用者身份沒有直接關聯,應偏向推薦。
174
+ 2. 若使用者身份的需求與書籍針對的問題有潛在關聯,應偏向推薦。
175
+ 3. 若書籍適合的讀者與使用者身份特質有任何關聯,應傾向推薦。
176
+ 4. 若書名跟使用者的心理問題或身分特質有任何關聯,應偏向推薦<</SYS>>
177
+
178
+ 使用者提供的資訊如下:
179
+ 使用者身份是「{user_identity}」,其心理問題是「{mental_issue}」。書名是{book},書籍適合的讀者群為「{book_reader}」,書籍針對的問題是「{book_description}」。
180
+
181
+ 請根據以上資訊判斷這本書是否適合推薦給該使用者。
182
+ 僅輸出「是」或「否」,輸出後即停止。[/INST]"""
183
+ )
184
+ df_filter=sorted_df.iloc[:20,:]
185
+ df_filter = df_filter.reset_index(drop=True)
186
+ df_filter=df_filter.assign(推薦=None)
187
+
188
+
189
+ p=len(df_user)-1
190
+ sum_for_bk=0
191
+ # 提取角色內容
192
+ role1 = df_user["角色1"].iloc[p] if pd.notnull(df_user["角色1"].iloc[p]) else ""
193
+ role2 = df_user["角色2"].iloc[p] if pd.notnull(df_user["角色2"].iloc[p]) else ""
194
+ role3 = df_user["角色3"].iloc[p] if pd.notnull(df_user["角色3"].iloc[p]) else ""
195
+
196
+ # 用"、"連接不為空的角色
197
+ user_identity = "、".join([role for role in [role1, role2, role3] if role]) # 只加入有內容的角色
198
+
199
+ #user_identity = df_user["角色1"].iloc[p]+"、"+df_user["角色2"].iloc[p]+"、"+df_user["角色3"].iloc[p]
200
+ mental_issue=df_user["形容詞1"].iloc[p]+"、"+df_user["形容詞2"].iloc[p]+"、"+df_user["形容詞3"].iloc[p]
201
+ for k in range(len(df_filter)):
202
+ #word=df_user["輸入內容"].iloc[p]
203
+ #book_reader = df_filter["角色1"].iloc[p] + "or" + df_filter["角色2"].iloc[p] + "or" + df_filter["角色3"].iloc[p]
204
+ book=df_filter["書名"].iloc[k]
205
+ book_reader = df_filter["角色1"].iloc[k]
206
+ # user_identity = df_user["角色1"].iloc[p]+"、"+df_user["角色2"].iloc[p]+"、"+df_user["角色3"].iloc[p]
207
+ # mental_issue=df_user["形容詞1"].iloc[p]+"、"+df_user["形容詞2"].iloc[p]+"、"+df_user["形容詞3"].iloc[p]
208
+ book_description=df_filter["形容詞1"].iloc[k]+"、"+df_filter["形容詞2"].iloc[k]+"、"+df_filter["形容詞3"].iloc[k]
209
+ print(book_reader)
210
+ print(user_identity)
211
+ #output = filter_prompt1.invoke({"user_identity": user_identity, "book_reader": book_reader})
212
+ output = filter_prompt4.invoke({"mental_issue":mental_issue,"user_identity": user_identity, "book":book,"book_description":book_description,"book_reader": book_reader})
213
+ string2=invoke_with_temperature(output)
214
+ df_filter.loc[k, '推薦'] =string2
215
+ if string2.strip()=="是":
216
+ sum_for_bk+=1
217
+ if(sum_for_bk==3):
218
+ break
219
+ df_recommend=df_filter[df_filter["推薦"].str.strip() == "是"]
220
+
221
+ return df_recommend
222
+
223
+ def output_content(df_recommend):
224
+
225
+ title = {}
226
+ URL = {}
227
+ summary = {}
228
+
229
+ for i in range(3):
230
+ title[f'title_{i}'] = df_recommend.iloc[i, 0] # Using iloc instead of loc
231
+ URL[f'URL_{i}'] = df_recommend.iloc[i, 2]
232
+ summary[f'summary_{i}'] = df_recommend.iloc[i, 1]
233
+
234
+ output = f"""根據您的狀態,這裡提供三本書供您參考\n
235
+ <第一本>
236
+ 書名:{title['title_0']}\n
237
+ 本書介紹:{summary['summary_0']}\n
238
+ 購書網址:{URL['URL_0']}\n
239
+ <第二本>
240
+ 書名:{title['title_1']}\n
241
+ 本書介紹:{summary['summary_1']}\n
242
+ 購書網址:{URL['URL_1']}\n
243
+ <第三本>
244
+ 書名:{title['title_2']}\n
245
+ 本書介紹:{summary['summary_2']}\n
246
+ 購書網址:{URL['URL_2']}\n
247
+ 希望對您有所幫助"""
248
+ return output
249
+
250
+ def main_pipeline(message,history):
251
+
252
+ df_user=process_user_input(message)
253
+ embedd_user=embedd_df_user(df_user)
254
+ sorted_df=similarity(embedd_user,embedd_bk,df_bk)
255
+ df_filter=filter(sorted_df,df_user)
256
+ final=output_content(df_filter)
257
+ return final
258
+
259
+ css = """
260
+ .chatbox .message-box {
261
+ height: 500px !important; # 設定訊息框的高度
262
+ width: 100%
263
+ overflow-y: auto; # 如果內容超出高度則顯示滾動條
264
+ text-rendering: optimizeLegibility; # 啟用抗鋸齒渲染
265
+ }
266
+
267
+
268
+ """
269
+
270
+ theme=gr.themes.Default(primary_hue=gr.themes.colors.red, secondary_hue=gr.themes.colors.pink,font=[gr.themes.GoogleFont("LXGW WenKai Mono TC")]).set(
271
+ body_background_fill='#FFF5EE'
272
+ )
273
+
274
+ with gr.Blocks(theme=theme) as demo:
275
+ with gr.Row():
276
+ with gr.Column():
277
+ gr.Markdown("""
278
+ <div style="text-align: center;">
279
+ <h1 style="display: inline; vertical-align: middle;">
280
+ <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_Rj6Add1OjrIeVXL4z84YzG4QIEuM4ptvvQ&s"
281
+ width="100" height="100" style="display: inline; vertical-align: middle; margin-right: 10px;">
282
+ 心理書籍推薦系統
283
+ <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_Rj6Add1OjrIeVXL4z84YzG4QIEuM4ptvvQ&s"
284
+ width="100" height="100" style="display: inline; vertical-align: middle; margin-left: 10px;">
285
+ </h1>
286
+ </div>
287
+ """)
288
+
289
+ gr.ChatInterface(
290
+ main_pipeline,
291
+ type="messages",
292
+ title="", # title 設為空,使用自定義 Markdown 標題
293
+ description='<div style="text-align: center;font-size:16px">這是個讓人放鬆的網站,希望透過讓人抒發心情表達現在面臨的狀況與挑戰,從書裡獲得解答。</div><div style="text-align: center;font-size: 16px;">-你可以告訴我們最近的心情和想法,放心我們不會儲存任何紀錄-</div>',
294
+ css=css
295
+ )
296
+
297
+ if __name__ == "__main__":
298
+ demo.launch(share=True)
299
+
300
+
301
+ # In[ ]:
302
+
303
+
304
+
305
+