Spaces:
Sleeping
Sleeping
File size: 25,622 Bytes
ae062d9 66f476e ae062d9 66f476e ae062d9 | 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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 | import gradio as gr
import re
import hashlib
import mysql.connector as mydb
import time
#import cohere
import os
from dotenv import load_dotenv
import numpy as np
import psycopg2
from google import genai
from google.genai import types
import uuid
import base64
import requests
import asyncio
import random
import pandas as pd
from docx import Document
from llama_parse import LlamaParse
from llama_index.core import SimpleDirectoryReader
load_dotenv(verbose=True)
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
chat_history = []
intreme = []
basic_format = ""
class DoSwitch:
def __init__(self):
# 状態(state)をインスタンス変数として保持
self.is_logged = False
self.first_exec = False
self.lastlog = ""
def log_on(self):
self.is_logged = True
def log_oout(self):
self.log_on = False
def first_executed(self):
self.first_exec = True
my_switch = DoSwitch()
def open_signup_window():
"""
gr.HTMLコンポーネントを使って、HTMLのリンクをボタンのように表示します。
"""
# HTMLのaタグを生成し、target="_blank"で新しいタブを開くように指定します。
# このリンクをCSSでボタンのようにスタイルします。
# この文字列全体がHTMLとしてGradioにレンダリングされます。
html_content = """
<div style="text-align: center; padding: 20px;">
<a href="https://accounts.google.com/v3/signin/identifier?authuser=0&continue=https://www.google.com/&ec=futura_exp_og_si_72776762_e&hl=ja&flowName=GlifWebSignIn&flowEntry=AddSession&dsh=S-1088503595%3A1757031827842666" target="_blank"
style="
display: inline-block;
padding: 15px 30px;
background-color: #4CAF50;
color: white;
text-decoration: none;
font-weight: bold;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
"
onmouseover="this.style.backgroundColor='#45a049';"
onmouseout="this.style.backgroundColor='#4CAF50';"
onclick="this.style.display='none';"
>
サインアップページを開く
</a>
</div>
"""
return gr.HTML(html_content)
def clean_text(text):
# 改行とタブを削除
return text.replace('\n', '').replace('\t', '').replace(' ', '')
def update_file_type(file):
global filepath
filepath = file
if file is not None:
# アップロードされたファイルの拡張子を取得
_, ext = os.path.splitext(file.name)
return ext
return ""
def respond(ctype, msg, username, response_check):
print("response_check:",response_check)
if response_check == True:
prompt = f"""「答え」をウェブで調べて、必ず、日本語で答えてください。
「答え」={msg}
"""
else:
prompt = f"""以下の「レポート」を「基本形」に沿って正しく明記されているかをチェックし、レポートがどれ位「基本形」に沿った形でカバーしているかを教えてください。尚、漏れている項目を表示し、その内容をウェブから検索し、アドバイスしてください。最終的に内容がわかりやすかったか否かを教えてください。「基本形」にどれ位沿っているかも教えてください。必ず、日本語で答えてください。
「レポート」={msg}
「基本形」={basic_format}
"""
gresponse = client.models.generate_content(
model="gemini-2.5-flash",
contents=[prompt]
)
summary = gresponse.text
print("summary1:",summary)
return summary
def validate_username(username):
if len(username) < 4:
return "ユーザー名は4文字以上である必要があります"
if not re.match("^[a-zA-Z0-9_]+$", username):
return "ユーザー名には文字、数字、アンダースコアのみ使用できます"
return None
def validate_email(email):
if not re.match(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", email):
return "有効なメールアドレスを入力してください"
return None
def validate_password(password):
if len(password) < 8:
return "パスワードは8文字以上でなければなりません"
if not any(char.isdigit() for char in password):
return "パスワードには少なくとも1つの数字を含める必要があります"
if not any(char.isupper() for char in password):
return "パスワードには少なくとも1つの大文字を含める必要があります"
return None
def validate_phone(phone):
if phone and not re.match(r"^\+?[0-9\s\-]+$", phone):
return "有効な電話番号を入力してください"
return None
def hash_password(password):
return hashlib.sha256(password.encode()).hexdigest()
def login_user(username, password):
conn = mydb.connect(
host='www.ryhintl.com',
port='36000',
user='smairuser',
password='smairuser',
database='smair'
)
c = conn.cursor()
hashed_pw = hash_password(password)
sqlcmd = "SELECT * FROM gyoseki_users WHERE username = '"+username+"' AND password = '"+hashed_pw+"'"
c.execute(sqlcmd)
user = c.fetchone()
conn.close()
if user:
return True, user
return False, "ユーザー名またはパスワードが無効です"
def process_logout():
time.sleep(1)
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
# Login Logic
def process_login(username, password, current_user_info_state):
username_error = validate_username(username)
password_error = validate_password(password)
if username_error:
return gr.update(value=f"<p class='error-message'>{username_error}</p>"), False, None, None, gr.update(visible=True), gr.update(visible=False)
elif password_error:
return gr.update(value=f"<p class='error-message'>{password_error}</p>"), False, None, None, gr.update(visible=True), gr.update(visible=False)
else:
success, result = login_user(username, password)
if success:
user_info = {
"id": result[0],
"username": result[1],
"email": result[2],
"phone": result[4],
"basic_format": result[5]
}
uid = result[5]
conn = mydb.connect(
host='www.ryhintl.com',
port='36000',
user='smairuser',
password='smairuser',
database='smair'
)
c = conn.cursor()
sqlcmd = "SELECT contents FROM gyoseki_basic_format WHERE id = "+str(uid)
c.execute(sqlcmd)
content = c.fetchone()
global basic_format
basic_format = content
conn.close()
return gr.update(value="<p class='success-message'></p>"), True, username, user_info, gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
#return gr.update(value="<p class='success-message'></p>"), True, username, user_info, gr.update(visible=False), gr.update(visible=True)
else:
#return gr.update(visible=False), gr.update(visible=True)
return gr.update(value=f"<p class='error-message'>{result}</p>"), False, None, None, gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
#return gr.update(value=f"<p class='error-message'>{result}</p>"), False, None, None, gr.update(visible=True), gr.update(visible=False)
def filecomp_change(prompt):
if prompt == None:
return gr.update(visible=False),gr.update(visible=True),gr.update(visible=True)
else:
return gr.update(visible=True),gr.update(visible=True),gr.update(visible=False)
def summary_change(prompt):
if len(prompt) == 0:
return gr.update(visible=False)
else:
return gr.update(visible=True)
def prompt_change(prompt):
if len(prompt["files"]) > 0:
print("cnt:",len(prompt["files"]))
for x in prompt["files"]:
file_path = prompt['files'][0]
print("file path",file_path)
return gr.update(visible=False),gr.update(visible=True),gr.update(visible=True)
else:
print("prompt:",prompt["text"])
return gr.update(visible=True),gr.update(visible=False),gr.update(visible=True)
def show_tab_1():
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
def show_tab_2():
return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
def show_tab_3():
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
def embed(texts, input_type):
# 改行または句点で分割(任意で調整可能)
if isinstance(texts, str):
inputs = [t.strip() for t in texts.split("\n") if t.strip()]
else:
inputs = texts
result = client.models.embed_content(
model="gemini-embedding-001",
contents=inputs,
config=types.EmbedContentConfig(output_dimensionality=1024)
)
# 結果を整形して表示
formatted = ""
for i, embedding in enumerate(result.embeddings):
#formatted += f"Embedding (Array{i}: {embedding.values} \n\n"
formatted += f"{embedding.values}"
return formatted
def summarize_text(long_text, username, summarize_text):
if not long_text:
return "要約するテキストがありません。"
prompt = f"次の文章をuserとassistantに分けて的確に要約してください:\n{long_text}"
gresponse = client.models.generate_content(
model="gemini-2.5-flash",
contents=[prompt]
)
summary = gresponse.text
if (summarize_text == '保存'):
response = embed(summary,"search_document")
embedding_str = response
conn = psycopg2.connect(
dbname="smair",
user="smairuser",
password="smairuser",
host="www.ryhintl.com",
port=10629
)
cur = conn.cursor()
sql = "INSERT INTO dailog_logs (userid, content, embedding) VALUES (%s, %s, %s)"
cur.execute(sql, (username, summary, f"{embedding_str}"))
conn.commit()
cur.close()
conn.close()
return summary
else:
return summary
def generate_summary(input_text, username, summary_save):
if not username:
return "ログインしてください。"
summary = summarize_text(input_text, username, summary_save)
return summary
def tnews():
res = client.models.generate_content(
model="gemini-2.5-flash",
contents=["東証のtopixに関するニュースを教えてください。必ず、日本語で答えてください。"]
)
return res.text
def generate_response(dtype, file_name, file_type, msg, username, report_check):
#if (file_name == None): # Should not happen if UI is correctly managed
if (msg == '' and file_name == ''): # Should not happen if UI is correctly managed
ret = []
ret.append(["レポートをアップロードしてください。","Please Upload report."])
yield ret
elif (msg == '' and file_name != ''):
if (my_switch.first_exec == True):
intreme.append(["レポートを処理中...",tnews()])
yield intreme
parser = LlamaParse(
api_key=os.environ.get("LLAMA_API_KEY"),
language="ja",
high_res_ocr=True,
user_prompt="提供された文書はスライドである。1ページにはファイルのタイトル、2ページは目次となっており、それ以降のページは各ページごとの副題を持つ。資料は、テキスト、図、表、グラフ、イラストを含む。",
result_type="markdown" # "markdown" または "text" が選択可能
)
file_extractor = {file_type: parser}
documents = SimpleDirectoryReader(input_files=[file_name], file_extractor=file_extractor, recursive=False).load_data()
print("documents:",documents)
texts = [doc.text for doc in documents]
print("texts:",texts)
combined_text = clean_text(texts[0])
msg = texts[0]
bot_message = respond(file_type, msg, username, report_check)
print("botmsg:",bot_message)
chat_history.append([msg, bot_message])
intreme.clear()
yield chat_history
else:
#gotresp = requests.get('')
conn = psycopg2.connect(
dbname="smair",
user="smairuser",
password="smairuser",
host="www.ryhintl.com",
port=10629
)
cur = conn.cursor()
sql = "select content from dailog_logs where userid = '"+username+"'"
cur.execute(sql)
plog = cur.fetchone()
conn.close()
my_switch.first_exec = True
my_switch.lastlog = plog
prompt = f"""「前回の会話ログ」でユーザーの予測や仮説などから結果を核にする項目があれば、確認する質問を列挙してください。例えば、ハイブリッド車の販売が堅調でコスト削減効果が期待できることに言及したが、具体的な過去のコストや利益率の推移データは提示せず、トヨタ自動車の公式財務報告書などを参照するよう促した。などについてハイブリッド車の販売好調がコスト増加抑制に寄与しているという当初の推測について、その後、何か追加で確認できた点はありますか?」のように質問を列挙してください。
「前回の会話ログ」={my_switch.lastlog}
"""
gresponse = client.models.generate_content(
model="gemini-2.5-flash",
contents=[prompt]
)
lastqa = gresponse.text
msg = lastqa
intreme.append(["レポートを処理中...",lastqa])
#yield intreme
'''parser = LlamaParse(
api_key=os.environ.get("LLAMA_API_KEY"),
language="ja",
high_res_ocr=True,
user_prompt="提供された文書はスライドである。1ページにはファイルのタイトル、2ページは目次となっており、それ以降のページは各ページごとの副題を持つ。資料は、テキスト、図、表、グラフ、イラストを含む。",
result_type="markdown" # "markdown" または "text" が選択可能
)
file_extractor = {file_type: parser}
documents = SimpleDirectoryReader(input_files=[file_name], file_extractor=file_extractor, recursive=False).load_data()
texts = [doc.text for doc in documents]
combined_text = clean_text(texts[0])
msg = texts[0]'''
#bot_message = respond(file_type, msg, username, report_check) + "\n" + lastqa
bot_message = respond(file_type, msg, username, report_check)
chat_history.append([msg, bot_message])
intreme.clear()
yield chat_history
else:
intreme.append(["レポートを処理中...",tnews])
yield intreme
bot_message = respond(file_type, msg, username, report_check)
chat_history.append([msg, bot_message])
intreme.clear()
yield chat_history
def summary_change(prompt):
if len(prompt) == 0:
return gr.update(visible=False)
else:
return gr.update(visible=True)
with gr.Blocks(title="Fund Manager Academic Buddy", css="""footer {visibility: hidden;} #header {display: flex; justify-content: space-between; align-items: center; font-size: 24px; font-weight: bold;} #logo {width: 50px; height: 50px;}
.gradio-container {
background-color: #f8f9fa;
/*width: 100%;
height: 100%;
background-image: url('https://images.unsplash.com/photo-1527181152855-fc03fc7949c8?auto=format&w=1000&dpr=2');
background-size: cover;
background-repeat: no-repeat;
background-position: center center;*/
}
.main {
background-color: #f8f9fa;
}
.logo-container {
position: absolute;
top: 1px;
left: 20px;
z-index: 1000;
}
.logo-container img {
height: 30px;
width: auto;
}
.title {
font-size: 1.5rem;
font-weight: 700;
color: #2c3e50;
text-align: center;
margin-bottom: 1.5rem;
}
.subtitle {
font-size: 0.1rem;
color: #7f8c8d;
text-align: center;
margin-bottom: 2rem;
}
.rcard {
background: #000055;
border-radius: 15px;
padding: 2rem;
box-shadow: 0 10px 20px rgba(0,0,0,0.1);
margin-bottom: 1rem;
height: 650px;
overflow: hidden;
}
.card {
background: white;
border-radius: 15px;
padding: 2rem;
box-shadow: 0 10px 20px rgba(0,0,0,0.1);
margin-bottom: 1rem;
}
.success-message {
color: #27ae60;
text-align: center;
margin-top: 1rem;
}
.error-message {
color: #e74c3c;
text-align: center;
margin-top: 1rem;
}
.footer {
text-align: center;
margin-top: 1rem;
color: #95a5a6;
font-size: 0.8rem;
}
.avatar {
width: 50px;
height: 50px;
border-radius: 50%;
margin: 0 auto 1rem auto;
display: block;
object-fit: cover;
border: 3px solid #4a90e2;
}
.avatar:hover {
transform: scale(1.2);
border: 3px solid #4a90e2;
}
.gr-button {
width: 100%;
border-radius: 10px;
padding: 10px;
background-color: #4a90e2;
color: white;
border: none;
font-weight: 500;
transition: all 0.3s;
}
.gr-button:hover {
background-color: #357abd;
color: lightyellow;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.gr-textinput, .gr-textbox {
border-radius: 10px;
padding: 10px;
border: 1px solid #ced4da;
}
.my-custom-button {
background-color: transparent !important; /* 緑色 */
color: black !important;
padding: 10px 20px !important;
border: solid thin black !important;
border-radius: 5px !important;
cursor: pointer !important;
font-size: 16px !important;
width: 100%;
transition: background-color 0.3s ease !important;
}
.my-custom-button:hover {
background-color: #fff5ee !important; /* ホバー時の色 */
}
""") as demo:
# State variables
current_username = gr.State(None)
current_user_info = gr.State(None)
logged_in_state = gr.State(False)
with gr.Sidebar(position="left", open=True):
gr.Markdown("©️ FUND MANAGER BUDDY 2025")
signin = gr.Button("サインイン", visible=True, elem_classes=["my-custom-button"], icon="https://img.icons8.com/fluency/48/azure-1.png")
query = gr.Button("クエリー", visible=False, elem_classes=["my-custom-button"], icon="https://img.icons8.com/fluency/48/orthogonal-view.png")
smry = gr.Button("ダイアログ・サマリー", visible=False, elem_classes=["my-custom-button"], icon="https://img.icons8.com/3d-fluency/48/domain.png")
#with gr.Tabs() as tabs:
# Set the first tab to be visible by default
with gr.Column("タブ1", visible=False, elem_classes="card") as b1:
signup_btn = gr.Button("サインアップ", elem_classes=["my-custom-button"], icon="https://img.icons8.com/color/48/000000/google-logo.png")
login_username = gr.Textbox(label="ユーザー名", placeholder="ユーザー名を入力してください")
login_password = gr.Textbox(label="パスワード", type="password", placeholder="パスワードを入力してください")
login_status = gr.Markdown("")
login_btn = gr.Button("サインイン")
output_html = gr.HTML()
signup_btn.click(
fn=open_signup_window,
inputs=[],
outputs=[output_html]
)
login_btn.click(
process_login,
inputs=[login_username, login_password, current_user_info],
outputs=[login_status, logged_in_state, current_username, current_user_info, signin, query, smry, b1]
)
with gr.Column("タブ2", visible=False) as b2:
with gr.TabItem("クエリー"):
logout_btn = gr.Button("ログアウト")
dialog_ctype = gr.Dropdown(["デフォルト"], label="会話形式", value="デフォルト")
with gr.Row(visible=True) as filecomp:
file_input = gr.File(label="レポートをアップロード(PDF,pptx,xlsx,docx,txt,mdなど)")
file_type = gr.Textbox(label="ファイルタイプ")
with gr.Row(visible=True) as reportcomp:
report_check = gr.Checkbox(label="レポート質問", info="レポート質問に対する答えの時にチェックしてください。")
report_content = gr.Textbox(label="レポート", lines=10, show_copy_button=True)
'''report_content = gr.MultimodalTextbox(
interactive=True,
file_count="single",
placeholder="レポートの内容や質問を入力してください",
label="レポート",
lines=10,
show_label=True,
sources=["upload", "microphone"],
)'''
dialog_output = gr.Chatbot(label="対話履歴", height=400, show_copy_all_button=True)
dialog_submit_btn = gr.Button("生成", visible=True)
file_input.change(fn=update_file_type, inputs=file_input, outputs=file_type)
#file_input.change(
#filecomp_change,
#inputs=[file_input],
#outputs=[dialog_submit_btn, filecomp, reportcomp]
#)
report_content.change(
prompt_change,
#handle_change,
inputs=[report_content],
outputs=[dialog_submit_btn, filecomp, reportcomp]
)
dialog_submit_btn.click(
generate_response,
inputs=[dialog_ctype, file_input, file_type, report_content, current_username, report_check],
outputs=[dialog_output]
)
with gr.Column("タブ3", visible=False) as b3:
with gr.TabItem("ダイアログ・サマリー"):
summary_input = gr.Textbox(label="要約したいユーザー・ダイアログを入力", lines=5)
summary_save = gr.Dropdown(["保存","保存しない"], label="DB保存", value="保存しない")
summary_output = gr.Markdown(label="要約結果", height=400, show_copy_button=True)
summary_submit_btn = gr.Button("要約", visible=False)
summary_input.change(
summary_change,
inputs=[summary_input],
outputs=[summary_submit_btn]
)
summary_submit_btn.click(
generate_summary,
inputs=[summary_input, current_username, summary_save],
outputs=summary_output
)
signin.click(show_tab_1, inputs=None, outputs=[b1, b2, b3])
query.click(show_tab_2, inputs=None, outputs=[b1, b2, b3])
smry.click(show_tab_3, inputs=None, outputs=[b1, b2, b3])
logout_btn.click(
process_logout,
inputs=[],
outputs=[signin,query,smry,b2]
)
#with gr.Sidebar(position="left"):
#gr.Markdown("## サイドバー")
#gr.Button("サインイン", elem_classes=["my-custom-button"], icon="https://img.icons8.com/fluency/48/azure-1.png").click(show_tab_1, inputs=None, outputs=[b1, b2, b3])
#query = gr.Button("クエリー", visible=False, elem_classes=["my-custom-button"], icon="https://img.icons8.com/fluency/48/orthogonal-view.png").click(show_tab_2, inputs=None, outputs=[b1, b2, b3])
#smry = gr.Button("ダイアログ・サマリー", visible=False, elem_classes=["my-custom-button"], icon="https://img.icons8.com/3d-fluency/48/domain.png").click(show_tab_3, inputs=None, outputs=[b1, b2, b3])
demo.launch()
|