kenken999 commited on
Commit
5c375a8
1 Parent(s): 179e954
Files changed (2) hide show
  1. refresh_app/webhook.py +340 -0
  2. routers/webhook.py +0 -40
refresh_app/webhook.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import sys
4
+ import subprocess
5
+ import logging
6
+ from fastapi import FastAPI, Request, HTTPException,APIRouter
7
+ import requests
8
+ import json
9
+ from datetime import datetime
10
+ import importlib
11
+ import pkgutil
12
+ from mysite.libs.utilities import validate_signature, no_process_file
13
+ #from mysite.database.database import ride,create_ride
14
+ from routers.gra_04_database.rides import test_set_lide
15
+ from mysite.interpreter.prompt import prompt_genalate,test_prompt
16
+ from mysite.interpreter.google_chat import send_google_chat_card,send_google_chat_card_thread,send_google_chat_wav
17
+ #from mysite.interpreter.interpreter import chat_with_interpreter
18
+ from routers.gra_02_openInterpreter.OpenInterpreter import chat_with_interpreter_no_stream
19
+ from mysite.appsheet.appsheet import get_senario
20
+ import asyncio
21
+ from prompts.promps import prompt_for_create_system,prompt,get_prompt
22
+ from command.line_get_user_profile import get_user_profile
23
+ from command.n8n import post_data,post_data_line
24
+ import time
25
+ import traceback
26
+ from pathlib import Path
27
+
28
+ logger = logging.getLogger(__name__)
29
+ ##
30
+ #router = APIRouter()
31
+ router = APIRouter()
32
+ #@router.get("/route/webhooks")
33
+
34
+ @router.post("/webhook")
35
+ async def webhook(request: Request):
36
+ import os
37
+ DEBUG=0
38
+ #return
39
+ #logger.info("[Start] ====== LINE webhook ======")
40
+ body = await request.body()
41
+ received_headers = dict(request.headers)
42
+ body_str = body.decode("utf-8")
43
+ logger.info("Received Body: %s", body_str)
44
+ body_json = json.loads(body_str)
45
+ events = body_json.get("events", [])
46
+
47
+ webhook_url = os.getenv("chat_url")
48
+ token = os.getenv("token")
49
+ ChannelAccessToken = os.getenv('ChannelAccessToken')
50
+ n8nurl = os.getenv("n8nhook")
51
+
52
+ thread_name=""
53
+ ###return
54
+ #url = github(token,foldername)
55
+ try:
56
+
57
+ for event in events:
58
+ if event["type"] == "message" and event["message"]["type"] == "text":
59
+ user_id = event["source"]["userId"]
60
+ text = event["message"]["text"]
61
+ event_type = event.get('type')
62
+ webhook_event_id = event.get('webhookEventId')
63
+ delivery_context = event.get('deliveryContext', {})
64
+ timestamp = event.get('timestamp')
65
+ mode = event.get('mode')
66
+
67
+ # メッセージ情報を取得
68
+ message = event.get('message', {})
69
+ message_type = message.get('type')
70
+ message_id = message.get('id')
71
+ message_text = message.get('text')
72
+ quote_token = message.get('quoteToken')
73
+ chat_id = event.get('source', {}).get('chatId')
74
+ # ソース情報を取得
75
+ source = event.get('source', {})
76
+ source_type = source.get('type')
77
+ user_id = source.get('userId')
78
+
79
+ # 応答トークンを取得
80
+ reply_token = event.get('replyToken')
81
+
82
+ user_name,thmbnail = get_user_profile(user_id,ChannelAccessToken)
83
+
84
+ logger.info("Received Headers: %s", user_name)
85
+ logger.info("Received Headers: %s", thmbnail)
86
+
87
+ #logger.info("------------------------------------------")
88
+ first_line = text.split('\n')[0]
89
+ #logger.info(f"User ID: {user_id}, Text: {text}")
90
+ #########################################################################
91
+ # 査定用のプロンプト
92
+ promps,prompt_res = prompt_genalate("返信は日本語で答えて下さい "+text,get_prompt(text))
93
+
94
+ #test_set_lide(text,"a1")
95
+ #no_process_file(text, "ai")
96
+ #\r\m
97
+ #########################################################################
98
+ #user_name,thmbnail#
99
+ title = f""" {user_name}様から下記の質問があります"""
100
+
101
+ subtitle = f"""<b>ユーザーID</b> {user_id}\r\n <b>質問内容</b>\r\n{message_id} {text}"""
102
+
103
+ ##
104
+ subtitle = f"""
105
+ <b>ユーザーID:</b>
106
+ {user_id}
107
+ <b>質問内容:</b>
108
+ {text}
109
+
110
+ """
111
+ #<b>Webhook Event ID:</b> {webhook_event_id}<br>
112
+ #<b>Delivery Context:</b> {json.dumps(delivery_context)}<br>
113
+ #<b>Timestamp:</b> {timestamp}<br>
114
+ #<b>Mode:</b> {mode}<br>
115
+ #<b>Message Type:</b> {message_type}<br>
116
+ #<b>Message ID:</b> {message_id}<br>
117
+ #<b>Message Text:</b> {message_text}<br>
118
+ #<b>Quote Token:</b> {quote_token}<br>
119
+ #<b>Source Type:</b> {source_type}<br>
120
+ #<b>Reply Token:</b> {reply_token}<br>
121
+ link_text = "\r\n<b>チャットボット設定用シート</b>\r\n シート用のアプリはチャットから\r\n @リファペディア\r\n と打ち込むと開きます"
122
+ link_url = "https://docs.google.com/spreadsheets/d/13pqP-Ywo5eRlZBsYX2m3ChARG38EoIYOowFd3cWij1c/edit?gid=283940886#gid=283940886"
123
+ #test_set_lide(subtitle, text)
124
+ #thread_name = send_google_chat_card(webhook_url, title, subtitle, link_text, link_url,thmbnail)
125
+
126
+ import requests
127
+ import os
128
+
129
+ # テキストを定義
130
+ # texts = (text)
131
+
132
+ # テキストをファイルに保存
133
+ text_file_path = 'text.txt'
134
+ with open(text_file_path, 'w', encoding='utf-8') as file:
135
+ file.write(text)
136
+
137
+ # 音声合成のクエリを取得
138
+ with open(text_file_path, 'r', encoding='utf-8') as file:
139
+ response = requests.post(
140
+ "https://kenken999-voicebox.hf.space/audio_query?speaker=1",
141
+ params={'text': file.read()}
142
+ )
143
+
144
+ query_json = response.json()
145
+
146
+ # 音声合成の実行
147
+ response = requests.post(
148
+ "https://kenken999-voicebox.hf.space/synthesis?speaker=2",
149
+ headers={"Content-Type": "application/json"},
150
+ json=query_json
151
+ )
152
+
153
+ # staticフォルダに音声ファイルを保存
154
+ os.makedirs('staticfiles', exist_ok=True)
155
+ timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
156
+ audio_file_name = f"audio_{timestamp}.wav"
157
+ audio_file_path = os.path.join('staticfiles', audio_file_name)
158
+ with open(audio_file_path, 'wb') as file:
159
+ file.write(response.content)
160
+ ##audio send add
161
+ print(f"Audio saved as {audio_file_path}")
162
+ wavurl = "https://kenken999-fastapi-django-main.hf.space/static/"+audio_file_name
163
+ #thread_name = send_google_chat_wav(webhook_url, "youtube audiofile", wavurl, link_text, link_url,thmbnail)#thread_name)
164
+ thread_name = send_google_chat_card(webhook_url, title, subtitle, link_text, link_url,thmbnail,wavurl)
165
+
166
+
167
+
168
+ #########################################################################
169
+ ### n8n WorkFlowStart
170
+ #########################################################################
171
+ line_signature = received_headers.get("x-line-signature")
172
+ ####$for debug
173
+ headers = {
174
+ "Content-Type": "application/json",
175
+ "X-Line-Signature": line_signature,
176
+ "Authorization": f"Bearer vzn2zssSEtHb/IVgMbgY1KxLQUfmUXRuiQiQkZLRVsHOeQBp9KsU5/M0i/2XKtw1K+eXN4PyjHQKcG5Vj5l+4e5CGAOQa/veKWdn83UPJQJU17FC9ONucjc84gvNFcRAy4IZcFcMky2PTzazf0KGiFGUYhWQfeY8sLGRXgo3xvw=",
177
+ "user_id":user_id,
178
+ }
179
+ #/webhook-test/d2d0af6e-5c42-45b6-a923-3bd2d8520e3f
180
+ #d2d0af6e-5c42-45b6-a923-3bd2d8520e3d
181
+ post_data("https://kenken999-nodex-n8n.hf.space/webhook-test/d2d0af6e-5c42-45b6-a923-3bd2d8520e3f",text,thread_name,headers)
182
+ #http://localhost:7860/webhook-test/d2d0af6e-5c42-45b6-a923-3bd2d8520e3f
183
+ post_data_line("https://kenken999-nodex-n8n.hf.space/webhook-test/d2d0af6e-5c42-45b6-a923-3bd2d8520e3d",body,headers)
184
+ #http://localhost:7860/webhook/d2d0af6e-5c42-45b6-a923-3bd2d8520e3d
185
+ post_data_line("https://kenken999-nodex-n8n.hf.space/webhook/d2d0af6e-5c42-45b6-a923-3bd2d8520e3d",body,headers)
186
+ #post_data_line("https://kenken999-nodex-n8n.hf.space/webhook/d2d0af6e-5c42-45b6-a923-3bd2d8520e3f",body,headers)
187
+
188
+ #return
189
+
190
+
191
+ post_data(n8nurl,text,thread_name,headers)
192
+ time.sleep(10)
193
+ #########################################################################
194
+ title = f""" プロンプト作成 {promps}"""
195
+ subtitle = f"""userid {user_id}\r\n chatid {thread_name}\r\n{prompt_res}"""
196
+ link_text = "データを確認する"
197
+ link_url = "https://kenken999-php.hf.space/diamondprice_list.php"
198
+ #test_set_lide(subtitle, text)
199
+ if DEBUG==1:
200
+ thread_name = send_google_chat_card_thread(webhook_url, title, subtitle, link_text, link_url,thread_name)
201
+
202
+ #thread_name = send_google_chat_card_thread(webhook_url, title, subtitle, link_text, link_url,thread_name)
203
+ #return
204
+ #test case
205
+ #########################################################################
206
+ first_line = text.split('\n')[0]
207
+ #test_prompt
208
+ res = test_prompt("返信は必ず日本語でして下さい \r\n"+prompt_res,text)
209
+
210
+ if DEBUG==1:
211
+ thread_name = send_google_chat_card_thread(webhook_url, "プロンプトテスト "+first_line, str(res), link_text, link_url,thread_name)
212
+
213
+ #thread_name = send_google_chat_card_thread(webhook_url, title, subtitle, link_text, link_url,thread_name)
214
+ now = datetime.now()
215
+ yyyymmddhis = now.strftime('%Y%m%d%H%M%S')
216
+
217
+
218
+ #########################################################################
219
+ ## excute create program
220
+ if DEBUG==1:
221
+ res_no_process = no_process_file(prompt_for_create_system+res, "gpt_enginner"+ yyyymmddhis,thread_name)
222
+ # execute open interpreter
223
+ #########################################################################
224
+ if DEBUG==1:
225
+ full_response,history = chat_with_interpreter_no_stream(prompt_for_create_system+"\r\n"+res)
226
+ if DEBUG==1:
227
+ thread_name = send_google_chat_card_thread(webhook_url, f"自動設定開始 {res}", str(full_response), link_text, link_url,thread_name)
228
+ ####################################################################
229
+ #ダイヤ金額計算
230
+ from babyagi.classesa.diamond import calculate
231
+ if DEBUG==1:
232
+ title = f""" ダイヤ予測計算の実行 類似5件表示 {text}
233
+ id,price,carat, cut, color, clarity, depth, diamondprice.table, x, y, z 類似度"""
234
+ #ベクトルインデックス
235
+ res_calculate = calculate(text)
236
+ subtitle = res_calculate
237
+ link_text = "データを確認する"
238
+ link_url = "https://kenken999-php.hf.space/diamondprice_list.php"
239
+ #########################################################################
240
+ #test_set_lide(subtitle, text)
241
+
242
+ #if DEBUG==0:
243
+ thread_name = send_google_chat_card_thread(webhook_url, title, subtitle, link_text, link_url,thread_name)
244
+ #########################################################################
245
+ from babyagi.babyagi import completion
246
+ #import tempfile
247
+ text = text.replace("\r\n","")
248
+ # コマンドを構築
249
+ command = f"""make runbabyagi "{text}に対して、より良いチャットボットでのQAプランデータ設定の提案を日本語で作成してください" {thread_name}"""
250
+ if DEBUG==1:
251
+ with open('/home/user/app/babyagi/prompt.txt', 'w') as file:
252
+ file.write(f"""{text}の質問 についてチャットボットでよりよく対応するプランを日本語で作成して""")
253
+
254
+ ######################################################################
255
+ if DEBUG==1:
256
+ proc = subprocess.Popen(
257
+ ["make", "runbabyagi", thread_name],
258
+ stdin=subprocess.PIPE,
259
+ stdout=subprocess.PIPE,
260
+ stderr=subprocess.PIPE,
261
+ text=True,
262
+ )
263
+
264
+ logger.info("Received Headers: %s", received_headers)
265
+ logger.info("Received Body: %s", body.decode("utf-8"))
266
+ ###############################################################################
267
+ #send to appsheet
268
+ get_senario("user_id",str(body))
269
+ #apps script send
270
+ headers = {
271
+ "Content-Type": "application/json",
272
+ }
273
+ logger.info("Received Body: %s", "send data to appsheet ")
274
+ #response = requests.post(os.getenv("WEBHOOK_URL"), headers=headers, data=body)
275
+ # check signature
276
+ line_signature = received_headers.get("x-line-signature")
277
+ logger.info("Received Body: %s", "start send messages ")
278
+ #headers = {
279
+ # "Content-Type": "application/json",
280
+ # "X-Line-Signature": line_signature,
281
+ # "Authorization": f"Bearer {os.getenv('ChannelAccessToken')}",
282
+ # }
283
+ #r#esponse = requests.post(os.getenv("WEBHOOK_URL"), headers=headers, data=body)
284
+
285
+ if not line_signature:
286
+ raise HTTPException(status_code=400, detail="X-Line-Signature header is missing.")
287
+
288
+ if not validate_signature(body.decode("utf-8"), line_signature, os.getenv("ChannelSecret")):
289
+ raise HTTPException(status_code=400, detail="Invalid signature.")
290
+
291
+ if not os.getenv("WEBHOOK_URL") or not os.getenv("WEBHOOK_URL").startswith("https://"):
292
+ raise HTTPException(status_code=400, detail="Invalid webhook URL")
293
+
294
+ headers = {
295
+ "Content-Type": "application/json",
296
+ "X-Line-Signature": line_signature,
297
+ "Authorization": f"Bearer {os.getenv('ChannelAccessToken')}",
298
+ }
299
+
300
+ logger.info("Forwarding to URL: %s", os.getenv("WEBHOOK_URL"))
301
+ logger.info("Forwarding Headers: %s", headers)
302
+ logger.info("Forwarding Body: %s", body.decode("utf-8"))
303
+
304
+ response = requests.post(os.getenv("WEBHOOK_URL"), headers=headers, data=body)
305
+ responses = requests.post(os.getenv("WEBHOOK_GAS"), headers=headers, data=body)
306
+ logger.info("Response Code: %s", response.status_code)
307
+ logger.info("Response Content: %s", response.text)
308
+ logger.info("Response Headers: %s", response.headers)
309
+
310
+ return {"status": "success", "response_content": response.text}#, response.status_code
311
+
312
+ except Exception as e:
313
+ error_file = os.path.basename(__file__) # ファイル名を取得
314
+ error_line = sys._getframe(1).f_lineno # 行番号を取得
315
+ print(f"Error occurred at file {error_file} on line {error_line}: {str(e)}")
316
+ # スタックトレースの詳細を取得
317
+ exc_type, exc_value, exc_tb = sys.exc_info()
318
+ tb_info = traceback.extract_tb(exc_tb)[-1] # 最後のトレースバック情報を取得
319
+ error_file = tb_info.filename # エラーが発生したファイル
320
+ error_line = tb_info.lineno # エラーが発生した行
321
+ error_trace = traceback.format_exc() # スタックトレース全体を取得
322
+ #エラー内容の分析
323
+ promps,res = prompt_genalate(str(e))
324
+ #test_set_lide(text,"a1")
325
+ #no_process_file(text, "ai")
326
+ custormer_supportpage = "\r\n カスタマーサポートはこちらから \r\n https://bpmboxesscom-46463613.hubspotpagebuilder.com/ja \r\n "
327
+ title = f"""Error occurred at file {error_file} on line {error_line}: {str(e)}\n{error_trace}エラーが起こりました -+errer file is {error_file} error line is {error_line} {str(e)} 自動修復の開始 """
328
+ subtitle = custormer_supportpage+res
329
+ link_text = "test"
330
+ link_url = "url"
331
+ #test_set_lide(subtitle, text)
332
+ logger.error(res)
333
+ #send error to google chat
334
+ ###
335
+ #send_google_chat_card_thread(webhook_url, title, subtitle, link_text, link_url,thread_name)
336
+
337
+ logger.error("Error: %s", str(e))
338
+ #raise するとシステムとまるのでアンコメント
339
+ #raise HTTPException(status_code=500, detail=str(e))
340
+ return {"status": "success", "response_content": str(e)}#, response.status_code
routers/webhook.py CHANGED
@@ -123,46 +123,6 @@ async def webhook(request: Request):
123
  #test_set_lide(subtitle, text)
124
  #thread_name = send_google_chat_card(webhook_url, title, subtitle, link_text, link_url,thmbnail)
125
 
126
- import requests
127
- import os
128
-
129
- # テキストを定義
130
- # texts = (text)
131
-
132
- # テキストをファイルに保存
133
- text_file_path = 'text.txt'
134
- with open(text_file_path, 'w', encoding='utf-8') as file:
135
- file.write(text)
136
-
137
- # 音声合成のクエリを取得
138
- with open(text_file_path, 'r', encoding='utf-8') as file:
139
- response = requests.post(
140
- "https://kenken999-voicebox.hf.space/audio_query?speaker=1",
141
- params={'text': file.read()}
142
- )
143
-
144
- query_json = response.json()
145
-
146
- # 音声合成の実行
147
- response = requests.post(
148
- "https://kenken999-voicebox.hf.space/synthesis?speaker=2",
149
- headers={"Content-Type": "application/json"},
150
- json=query_json
151
- )
152
-
153
- # staticフォルダに音声ファイルを保存
154
- os.makedirs('staticfiles', exist_ok=True)
155
- timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
156
- audio_file_name = f"audio_{timestamp}.wav"
157
- audio_file_path = os.path.join('staticfiles', audio_file_name)
158
- with open(audio_file_path, 'wb') as file:
159
- file.write(response.content)
160
- ##audio send add
161
- print(f"Audio saved as {audio_file_path}")
162
- wavurl = "https://kenken999-fastapi-django-main.hf.space/static/"+audio_file_name
163
- #thread_name = send_google_chat_wav(webhook_url, "youtube audiofile", wavurl, link_text, link_url,thmbnail)#thread_name)
164
- thread_name = send_google_chat_card(webhook_url, title, subtitle, link_text, link_url,thmbnail,wavurl)
165
-
166
 
167
 
168
  #########################################################################
 
123
  #test_set_lide(subtitle, text)
124
  #thread_name = send_google_chat_card(webhook_url, title, subtitle, link_text, link_url,thmbnail)
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
 
128
  #########################################################################