gradio-cmat / app.py
freemt
0a6c516
"""Bootstrap."""
# pylint: disable=invalid-name
from typing import Any, List, Union
import gradio as gr
import logzero
import numpy as np
import pandas as pd
# from hf_model_s import model_s
from logzero import logger
from set_loglevel import set_loglevel
from gradio_cmat.gradio_cmat import gradio_cmat
# pd.set_option("display.precision", 3)
pd.options.display.float_format = "{:,.2f}".format
# pd.set_option('display.float_format', '{:,.0f}'.format)
logzero.loglevel(set_loglevel(10, force=True))
# model = model_s()
# def fn(text1: str, text2: str) -> np.ndarray:
# def fn(text1: str, text2: str) -> pd.DataFrame:
def fn(text1: str, text2: str) -> Union[List[Any], str]:
"""Define."""
logger.info("gradio version: %s", gr.__version__)
list1 = [elm.strip() for elm in text1.splitlines() if elm.strip()]
list2 = [elm.strip() for elm in text2.splitlines() if elm.strip()]
logger.debug("text1[:10]: %s", text1[:10])
logger.debug("text2[:10]: %s", text2[:10])
logger.info("info text1[:10]: %s", text1[:10])
logger.info("info text2[:10]: %s", text2[:10])
try:
res = gradio_cmat(list1, list2)
# res = np.array([[0.015, 0.235, 0.112], [0.015, 0.235, 0.112]])
logger.debug("res: \n%s, %s", res, res.shape)
logger.debug("type(res): %s", type(res))
# res.round(decimals=2, out=res)
# logger.debug("debug res: %s, %s", res, res.shape)
except Exception as e:
logger.error("gradio_cmat error: %s", e)
return str(e)
# raise
round2 = lambda x: round(x, 2)
vfunc = np.vectorize(round2)
df = pd.DataFrame(res)
# _ = df.style.background_gradient().set_precision(1)
# _ = df.style.background_gradient().format(precision=1)
_ = df.style.set_properties(
**{
"font-size": "10pt",
"border-color": "black",
"border": "1px black solid !important"
}
# border-color="black",
).set_table_styles([{
"selector": "", # noqs
"props": [("border", "2px black solid !important")]}] # noqs
).format(
precision=2
)
_ = _.to_html()
# return pd.DataFrame(vfunc(res), dtype="object")
# return pd.DataFrame(vfunc(res), dtype="object").to_html()
# return pd.DataFrame(res)
# return str(res.tolist())
return _
out_df = gr.outputs.Dataframe(
# headers=None,
max_rows=50, # 20
max_cols=50,
overflow_row_behaviour="paginate",
# type="auto",
type="pandas",
label="cmat",
)
out_text = gr.outputs.Textbox(label="cmat")
# _ = """
try:
interface = gr.Interface(
fn,
[
gr.inputs.Textbox(
lines=3, default="""The quick brown fox jumped over the lazy dogs.
test test
测试一下
"""
),
gr.inputs.Textbox(lines=4, default="""The fast brown fox jumps over lazy dogs.
abc
test
Dies ist ein Test
"""),
],
# out_df,
# out_text,
"html", # gr.outputs.HTML(label=None)
title="gradio-cmat",
theme="grass",
allow_flagging="never",
layout="vertical",
description="Gen correlation matrix for multlingual texts",
article="Click 'Clear' first for subsequent new texts",
examples=[
["test\nabc", "测试"],
["This is a text.\nIch liebe Dich.\nabc", "我爱你\nI love you.\n测试\nbcd"],
],
)
except Exception as exc:
logger.exception("")
logger.error("gr.Interface.load(%s): %s", "fn", exc)
raise
interface.launch()