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