compute_metrics.py
# %%
#!pip install -U ibm_watson_openscale
#!pip install -U "ibm-metrics-plugin[generative-ai-quality]~=3.0.11"
# %%
#import spacy
#spacy.cli.download("en_core_web_sm")
#spacy.cli.download("ja_core_news_sm")
#!python -m nltk.downloader punkt
# %%
#!pip install python-dotenv
#!pip install certifi
# %%
from dotenv import load_dotenv
load_dotenv(override=True)
# %%
import os
CPD_URL = os.environ.get("CPD_URL")
CPD_USERNAME = os.environ.get("CPD_USERNAME")
CPD_API_KEY = os.environ.get("CPD_API_KEY")
# %%
from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator
from ibm_watson_openscale import *
from ibm_watson_openscale.supporting_classes.enums import *
from ibm_watson_openscale.supporting_classes import *
authenticator = CloudPakForDataAuthenticator(
url=CPD_URL,
username=CPD_USERNAME,
apikey=CPD_API_KEY,
disable_ssl_verification=True
)
wos_client = APIClient(
service_url=CPD_URL,
authenticator=authenticator,
)
data_mart_id = wos_client.service_instance_id
print(data_mart_id)
print(wos_client.version)
# %%
language_code = "ja"
configuration = {
"configuration": {
"record_level":False,
"context_columns":["contexts"],
"question_column": "question",
"retrieval_augmented_generation": {
"hap_score": {},
"pii": {
"language_code" : language_code
}
},
"language_code" : language_code
}
}
# %%
#import pandas as pd
#import json
#filepath = "test.json"
#with open(filepath, mode="r", encoding="utf-8") as f:
# data = json.load(f)
#df = pd.json_normalize(data)
# %%
#df["i_question"] = df.index.astype(str) + ":" + df["question"]
# %%
#question = "4:担当者に連絡するにはどうすればいい?"
#i = df.index[df["i_question"] == question].tolist()
# %%
#context = "|".join(df["context"].iloc[i].astype(str))
#generated_text = "|".join(df["generated_text"].iloc[i].astype(str))
#reference_text = "|".join(df["reference_text"].iloc[i].astype(str))
# %%
#sources = df.iloc[i][["context", "question"]].copy()
#predictions = df.iloc[i][["generated_text"]].copy()
#references = df.iloc[i][["reference_text"]].copy()
# %%
#result = wos_client.llm_metrics.compute_metrics(configuration, sources, predictions, references)
#metrics = wos_client.llm_metrics.get_metrics_result(configuration, result)
# %%
#while "in_progress" in json.dumps(metrics):
# print("in_progress")
# metrics = wos_client.llm_metrics.get_metrics_result(configuration, result)
#metrics
# %%
app.py
# %%
#!pip install gradio
# %%
import gradio as gr
import pandas as pd
import json
from compute_metrics import configuration, wos_client
# %%
def json2questions(filepath):
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
df = pd.json_normalize(data)
df["i_question"] = df.index.astype(str) + ":" + df["question"]
questions = df["i_question"].tolist()
return gr.update(choices=questions, value=questions[0])
except Exception as e:
print(f"{e}")
return gr.update(choices=[f"{e}"], value=f"{e}")
def rag(filepath, question):
try:
with open(filepath, mode="r", encoding="utf-8") as f:
data = json.load(f)
df = pd.json_normalize(data)
df["i_question"] = df.index.astype(str) + ":" + df["question"]
i = df.index[df["i_question"] == question].tolist()
context = "|".join(df["context"].iloc[i].astype(str))
generated_text = "|".join(df["generated_text"].iloc[i].astype(str))
reference_text = "|".join(df["reference_text"].iloc[i].astype(str))
sources = df.iloc[i][["context", "question"]].copy()
predictions = df.iloc[i][["generated_text"]].copy()
references = df.iloc[i][["reference_text"]].copy()
result = wos_client.llm_metrics.compute_metrics(configuration, sources, predictions, references)
metrics = wos_client.llm_metrics.get_metrics_result(configuration, result)
while "in_progress" in json.dumps(metrics):
print("in_progress")
metrics = wos_client.llm_metrics.get_metrics_result(configuration, result)
return context, generated_text, reference_text, metrics
except Exception as e:
context = f"{e}"
generated_text = f"{e}"
reference_text = f"{e}"
metrics = [{}]
return context, generated_text, reference_text, metrics
with gr.Blocks() as app:
filepath = gr.File(label="json", file_types=[".json"])
question = gr.Dropdown(label="question", choices=[])
button = gr.Button()
context = gr.Textbox(label="context")
generated_text = gr.Textbox(label="generated_text")
reference_text = gr.Textbox(label="reference_text")
metrics = gr.Json(label="metrics")
filepath.change(fn=json2questions, inputs=[filepath], outputs=[question])
button.click(fn=rag, inputs=[filepath, question], outputs=[context, generated_text, reference_text, metrics])
app.launch(server_name="0.0.0.0")
# %%
test.json
[
{
"question": "保険の申し込み方法を教えてください。",
"context": "保険に加入するには、申込書への記入と本人確認書類の提出が必要です。",
"generated_text": "保険の申し込みには、申込書の記入と本人確認書類の提出が必要です。",
"reference_text": "保険の申し込みは、申込書の記入と必要書類の提出によって完了します。"
},
{
"question": "保険金の請求には何が必要ですか?",
"context": "保険金請求には、請求書と診断書などの証明書類が必要です。",
"generated_text": "保険金の請求には、必要な書類の提出が求められます。",
"reference_text": "請求書や診断書などの証明書類を提出することで、保険金請求が可能です。"
},
{
"question": "保険を解約するにはどうすればよいですか?",
"context": "解約は、契約者本人による書面での手続きが必要です。",
"generated_text": "保険の解約は、書面での申請が必要です。",
"reference_text": "契約者本人が所定の手続きを行うことで、保険を解約できます。"
},
{
"question": "保険料の支払い方法は変更できますか?",
"context": "支払い方法は、口座振替やクレジットカードなどから選択可能です。",
"generated_text": "はい、支払い方法は変更可能です。手続きが必要です。",
"reference_text": "お手続きにより、保険料の支払い方法を変更できます。"
},
{
"question": "担当者に連絡するにはどうすればいい?",
"context": "連絡先は契約時に発行された書類に記載されています。",
"generated_text": "担当者の連絡先は、契約時の資料をご確認ください。",
"reference_text": "ご契約時にお渡しした書類に、担当者の連絡先が記載されています。"
},
{
"question": "補償内容の確認方法を教えてください。",
"context": "補償内容は契約書やマイページで確認できます。",
"generated_text": "契約内容は、契約書またはオンラインで確認できます。",
"reference_text": "ご契約の補償内容は、契約書やマイページ上でご確認いただけます。"
},
{
"question": "申込に必要な書類は何ですか?",
"context": "本人確認書類と申込書の提出が必要です。",
"generated_text": "本人確認書類と申込書が必要になります。",
"reference_text": "申込の際には、本人確認書類と申込書をご提出いただきます。"
},
{
"question": "契約内容を変更したいときはどうすれば?",
"context": "契約内容の変更は、カスタマーサポートを通じて可能です。",
"generated_text": "契約の変更は、カスタマーサポートにご連絡ください。",
"reference_text": "変更をご希望の場合は、カスタマーサポートまでご連絡ください。"
},
{
"question": "保険の対象にペットは含まれますか?",
"context": "一部のプランではペット保険も提供されています。",
"generated_text": "はい、プランによってはペットも対象となる場合があります。",
"reference_text": "ご加入のプランによっては、ペットも補償対象になる場合があります。"
},
{
"question": "保険証券を紛失した場合はどうすればいい?",
"context": "紛失時は再発行の手続きを行う必要があります。",
"generated_text": "保険証券を紛失した場合は、再発行の手続きをしてください。",
"reference_text": "保険証券の紛失時には、再発行のお手続きが必要です。"
}
]