Files changed (1) hide show
  1. app.py +380 -0
app.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from groq import Groq
3
+ import io
4
+ import numpy as np
5
+ import soundfile as sf
6
+ import requests
7
+ import cohere
8
+ import json
9
+ import os
10
+ from dotenv import load_dotenv
11
+
12
+ # Set up API keys
13
+ load_dotenv(verbose=True)
14
+ coherekey = os.environ.get("COHERE_API_KEY")
15
+ groqkey = os.environ.get("GROQ_API_KEY")
16
+ geturl = os.environ.get("SQLURL")
17
+
18
+ co = cohere.ClientV2(api_key=coherekey)
19
+
20
+ cresponse = requests.get(geturl)
21
+ cohere_doc = cresponse.json()
22
+
23
+ logged_in = None
24
+
25
+ def auth(user_name, password):
26
+ if password == user_name + str(len(user_name)):
27
+ return True # 認証成功
28
+ else:
29
+ return False # 認証失敗
30
+
31
+ def login(user_name, password):
32
+ global logged_in
33
+ sqlcmd = "https://www.ryhintl.com/dbjson/getjson?sqlcmd=select count(customername) as auth from llm_acl where customername = '"+user_name+"' and customerkey = '"+password+"'"
34
+ lresponse = requests.get(sqlcmd)
35
+ #logged = lresponse.content.decode('utf-8')
36
+ loginfo= lresponse.json()
37
+ #print(loginfo[0]['auth'])
38
+ if loginfo[0]['auth'] == "1":
39
+ logged_in = True
40
+ return True
41
+ else:
42
+ logged_in = False
43
+ return False
44
+
45
+
46
+ #def nav_to(url):
47
+ #nav_script = f"""
48
+ #<meta http-equiv="refresh" content="0; url='{url}'">
49
+ #"""
50
+ #return nav_script
51
+
52
+ js = """
53
+ function createGradioAnimation() {
54
+ var container = document.createElement('div');
55
+ container.id = 'gradio-animation';
56
+ container.style.fontSize = '2em';
57
+ container.style.fontWeight = 'bold';
58
+ container.style.textAlign = 'center';
59
+ container.style.marginBottom = '20px';
60
+
61
+ var text = 'AGENTIC RAG';
62
+ for (var i = 0; i < text.length; i++) {
63
+ (function(i){
64
+ setTimeout(function(){
65
+ var letter = document.createElement('span');
66
+ var randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
67
+ letter.style.color = randomColor;
68
+ letter.style.opacity = '0';
69
+ letter.style.transition = 'opacity 0.5s';
70
+ letter.innerText = text[i];
71
+
72
+ container.appendChild(letter);
73
+
74
+ setTimeout(function() {
75
+ letter.style.opacity = '1';
76
+ }, 50);
77
+ }, i * 250);
78
+ })(i);
79
+ }
80
+
81
+ var gradioContainer = document.querySelector('.gradio-container');
82
+ gradioContainer.insertBefore(container, gradioContainer.firstChild);
83
+
84
+ return 'Animation created';
85
+ }
86
+ """
87
+
88
+
89
+ def log_out():
90
+ return gr.HTML("""
91
+ <html>
92
+ <head>
93
+ <style>
94
+ body {
95
+ font-family: Arial, sans-serif;
96
+ background-color: #f0f0f0;
97
+ display: flex;
98
+ justify-content: center;
99
+ align-items: center;
100
+ height: 100vh;
101
+ margin: 0;
102
+ }
103
+ .container {
104
+ text-align: center;
105
+ background: white;
106
+ padding: 50px;
107
+ border-radius: 10px;
108
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
109
+ }
110
+ h1 {
111
+ color: #333;
112
+ }
113
+ p {
114
+ color: #666;
115
+ }
116
+ a {
117
+ display: inline-block;
118
+ margin-top: 20px;
119
+ padding: 10px 20px;
120
+ color: white;
121
+ /*background-color: #007bff;*/
122
+ background-color: green;
123
+ text-decoration: none;
124
+ border-radius: 5px;
125
+ }
126
+ a:hover {
127
+ background-color: #0056b3;
128
+ }
129
+ </style>
130
+ </head>
131
+ <body>
132
+ <div class="container">
133
+ <h1>正常にログアウトしました。</h1>
134
+ <p>ログアウトされました。ご訪問いただきありがとうございます!</p>
135
+ <a href="/logout" style="background-color:green; color: white;">Go to Login Page</a>
136
+ </div>
137
+ </body>
138
+ </html>
139
+ """)
140
+
141
+ def redirect():
142
+ global logged_in
143
+ logged_in = False
144
+ return gr.HTML("<meta http-equiv='refresh' content='0; url=\"https://www.ryhintl.com/fastclient/logout.html\"'>")
145
+ #return gr.HTML("<meta http-equiv='refresh' content='0; url=\"/\"'>")
146
+
147
+ def load_css():
148
+ #link = "https://www.ryhintl.com/theme.css"
149
+ #css_content1 = requests.get(link).content.decode('utf-8')
150
+ #print(css_content1)
151
+ with open('theme.css', 'r') as file:
152
+ css_content = file.read()
153
+ return css_content
154
+
155
+ def transcribe_audio(audio, api_key):
156
+ if audio is None:
157
+ return ""
158
+
159
+ # Convert audio to the format expected by the model
160
+ # The model supports mp3, mp4, mpeg, mpga, m4a, wav, and webm file types
161
+ audio_data = audio[1] # Get the numpy array from the tuple
162
+ buffer = io.BytesIO()
163
+ sf.write(buffer, audio_data, audio[0], format='mp3')
164
+ buffer.seek(0)
165
+
166
+ bytes_audio = io.BytesIO()
167
+ np.save(bytes_audio, audio_data)
168
+ bytes_audio.seek(0)
169
+
170
+ try:
171
+ client = Groq(api_key=groqkey)
172
+
173
+ # Use Distil-Whisper English powered by Groq for transcription
174
+ completion = client.audio.transcriptions.create(
175
+ #model="distil-whisper-large-v3-en",
176
+ model="whisper-large-v3-turbo",
177
+ file=("audio.mp3", buffer),
178
+ response_format="text"
179
+ )
180
+ return completion
181
+ except Exception as e:
182
+ return f"エラー: {str(e)}"
183
+
184
+
185
+ def generate_response(transcription, api_key):
186
+ if not transcription:
187
+ return "トランスクリプトが利用できません。もう一度話してみてください。"
188
+
189
+ try:
190
+ url = 'https://www.ryhintl.com/crewai/autogen?qry='+transcription
191
+ res = requests.get(url)
192
+
193
+ # Extract content of Professional_Assistant_Agent
194
+ data = res.content.decode("utf-8")
195
+ data = data.replace("null","None")
196
+ datas = eval(data)
197
+
198
+ basic_content = [entry["content"] for entry in datas["chat_history"] if entry["name"] == "Basic_Assistant_Agent"]
199
+ basic_result = ', '.join([str(x) for x in basic_content])
200
+
201
+ professional_content = [entry["content"] for entry in datas["chat_history"] if entry["name"] == "Professional_Assistant_Agent"]
202
+ professional_result = ', '.join([str(x) for x in professional_content])
203
+ #combined_list = basic_content + professional_content
204
+
205
+ final_result = "Basic_Assistant: "+basic_result+"\n\n\nProfessional_Assistant: "+professional_result
206
+
207
+ return final_result
208
+ except Exception as e:
209
+ return f"エラー: {str(e)}"
210
+
211
+
212
+ def process_audio(audio, api_key, prompt):
213
+ global logged_in
214
+
215
+ if not logged_in:
216
+ raise gr.Error("ログインセッションが存在しません。ログインし直してください。1")
217
+
218
+ if not prompt == "":
219
+ transcription = prompt
220
+ response = generate_response(transcription, api_key)
221
+ return transcription, response
222
+ else:
223
+ transcription = transcribe_audio(audio, api_key)
224
+ response = generate_response(transcription, api_key)
225
+ return transcription, response
226
+
227
+
228
+ def process_cohere(prompt):
229
+ global logged_in
230
+ if not logged_in:
231
+ raise gr.Error("ログインセッションが存在しません。ログインし直してください。2")
232
+
233
+ if prompt == "":
234
+ return "プロンプトを入力してください。", "プロンプトは必須です。"
235
+ else:
236
+ system_message = """## あなたは、LLMのスペシャリストです。"""
237
+ messages = [
238
+ {"role": "system", "content": system_message},
239
+ {"role": "user", "content": prompt},
240
+ ]
241
+
242
+ # Step 2: Tool planning and calling
243
+ response = co.chat(
244
+ model="command-r-plus-08-2024",
245
+ messages=messages,
246
+ documents=cohere_doc
247
+ )
248
+ return response.message.content[0].text
249
+
250
+ def process_eprag(prompt):
251
+ global logged_in
252
+ if not logged_in:
253
+ raise gr.Error("ログインセッションが存在しません。ログインし直してください。3")
254
+
255
+ if prompt == "":
256
+ return "プロンプトを入力してください。", "プロンプトは必須です。"
257
+ else:
258
+ url = 'http://www.ryhintl.com/eprag-be/llm?query='+prompt
259
+ res = requests.get(url)
260
+ rtn = res.content.decode('utf-8')
261
+ return rtn
262
+
263
+ # Custom CSS for the Groq badge and color scheme (feel free to edit however you wish)
264
+ custom_css = """
265
+ .gradio-container {
266
+ background-color: #f5f5f5;
267
+ }
268
+ .gr-button-primary {
269
+ background-color: #f55036 !important;
270
+ border-color: #f55036 !important;
271
+ }
272
+ .gr-button-secondary {
273
+ color: #f55036 !important;
274
+ border-color: #f55036 !important;
275
+ }
276
+ #groq-badge {
277
+ position: fixed;
278
+ bottom: 20px;
279
+ right: 20px;
280
+ z-index: 1000;
281
+ }
282
+ """
283
+
284
+ #with gr.Blocks(theme=gr.themes.Default()) as llm:
285
+ with gr.Blocks(css=load_css(),js=js) as llm:
286
+ with gr.Tab("VAR"):
287
+ gr.Markdown("# 🎙️ VOICE AGENTIC RAG")
288
+
289
+ #api_key_input = gr.Textbox(type="password", label="Groq API Keyを入力してください。", value=groqkey, visible=False)
290
+ api_key_input = groqkey
291
+
292
+ with gr.Row():
293
+ audio_input = gr.Audio(label="音声プロンプト", type="numpy")
294
+
295
+ with gr.Row():
296
+ user_input = gr.Textbox(label="プロンプト", type="text")
297
+
298
+ with gr.Row():
299
+ transcription_output = gr.Textbox(label="トランスクリプション")
300
+ response_output = gr.Textbox(label="AIアシスタントの応答")
301
+
302
+ submit_button = gr.Button("プロセス", variant="primary")
303
+
304
+ # Add the Groq badge
305
+ gr.HTML("""
306
+ <div id="groq-badge">
307
+ <div style="color: #f55036; font-weight: bold;">POWERED BY EPRAG</div>
308
+ </div>
309
+ """)
310
+
311
+ submit_button.click(
312
+ process_audio,
313
+ inputs=[audio_input, api_key_input, user_input],
314
+ outputs=[transcription_output, response_output]
315
+ )
316
+
317
+ gr.Markdown("""
318
+ ## 使い方:
319
+ 1. マイクのアイコンをクリックしてメッセージを入力するかプロンプトのプロンプトを入力してください。
320
+ 2. 音声入力する場合、マイクのアイコンをクリックしてメッセージを話してください。 サポートされている音声ファイルを提供することもできます。サポートされているオーディオ・ファイルには、mp3、mp4、mpeg、mpga、m4a、wav、webmなどがあります。
321
+ 3. [プロセス] ボタンをクリックしてスピーチを文字に起こし、AGENTIC RAG アシスタントからの応答を生成します。
322
+ 4. 文字起こしとAIアシスタントの応答がそれぞれのテキスト・ボックスに表示されます。
323
+
324
+ """)
325
+ with gr.Tab("COHERE"):
326
+ gr.Markdown("# 📂 COHERE AGENTIC RAG")
327
+ with gr.Row():
328
+ cohere_input = gr.Textbox(label="プロンプト", type="text")
329
+
330
+ with gr.Row():
331
+ cohere_output = gr.Textbox(label="AIアシスタントの応答")
332
+
333
+ submit_button = gr.Button("COHEREプロセス", variant="primary")
334
+ submit_button.click(
335
+ process_cohere,
336
+ inputs=[cohere_input],
337
+ outputs=[cohere_output]
338
+ )
339
+
340
+ with gr.Tab("EPRAG"):
341
+
342
+ gr.Markdown("# 🗞️ AGENTIC EPRAG")
343
+
344
+ with gr.Row():
345
+ eprag_input = gr.Textbox(label="プロンプト", type="text")
346
+
347
+ with gr.Row():
348
+ eprag_output = gr.Textbox(label="AIアシスタントの応答")
349
+
350
+ submit_button = gr.Button("EPRAGプロセス", variant="primary")
351
+ submit_button.click(
352
+ process_eprag,
353
+ inputs=[eprag_input],
354
+ outputs=[eprag_output]
355
+ )
356
+
357
+ with gr.Tab("アカウント"):
358
+ gr.Markdown("# 🏃🏽‍➡️ ログアウト")
359
+
360
+ with gr.Row():
361
+ #logout_output = gr.Textbox(label="AIアシスタントの応答")
362
+ logout_output = gr.HTML(label="AIアシスタントの応答")
363
+
364
+ submit_button = gr.Button("ログアウト", variant="primary")
365
+ submit_button.click(
366
+ redirect,
367
+ inputs=[],
368
+ outputs=[logout_output]
369
+ )
370
+
371
+
372
+ #with llm.route("ログアウト", "/signout"):
373
+ #log_out_button = gr.Button("ログアウト")
374
+ #output = gr.HTML()
375
+
376
+ #log_out_button.click(fn=log_out, inputs=None, outputs=output)
377
+
378
+ llm.launch(share=True)
379
+ #llm.launch(auth=[("ryhintl", "ryhintl")],share=True,pwa=True)
380
+ #llm.launch(auth=[("ryhintl", "ryhintl")],share=True,server_name="localhost", server_port=7066)