modelscope / modelscope-studio

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Plotly graphs integration

liwalayouni opened this issue · comments

Hello, this is not an issue but I would like to suggest a new feature. I was wondering if you would consider integrating Plotly charts in the chatbot component. I see a huge benefit for this feature, since in many use case chatbots would generate graphs.

Thanks for your advice! We are considering integrating charts as a built-in html tag in chatbot message, and it will be coming soon. But for now, in modelscope_studio@0.1.3, you could also get the same with custom_components property.

Here is an example of integrating echarts:

image

app.py

import gradio as gr
import json
import modelscope_studio as mgr
import os

with open(os.path.join(os.path.dirname(__file__), "./chart.js"), "r") as f:
    chart_js = f.read()

custom_components = {
    "chart": {
        "props": ["options"],
        "js": chart_js,
    }
}
options = {
    "xAxis": {
        "type": 'category',
        "data": ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    },
    "yAxis": {
        "type": 'value',
    },
    "series": [
        {
            "data": [150, 230, 224, 218, 135, 147, 260],
            "type": 'line',
        },
    ],
}
conversation = [[
    None, {
        "text": f"""<chart options='{json.dumps(options)}'></chart>"""
    }
]]

with gr.Blocks() as demo:
    chatbot = mgr.Chatbot(
        value=conversation,
        height=600,
        custom_components=custom_components)
demo.queue().launch()

chart.js

(props, cc, { el }) => {
  el.innerHTML = 'Loading...'
  const render = () => {
    const options = JSON.parse(props.options)
    el.style.height = '200px'
    window.echarts.init(el).setOption(options)
  }
  if (!document.querySelector('#echarts-script')) {
    const script = document.createElement('script')
    script.src =
      'https://cdn.jsdelivr.net/npm/echarts@5.4.1/dist/echarts.min.js'
    script.id = 'echarts-script'
    script.onload = render
    document.head.appendChild(script)
  } else {
    render()
  }
}

We have integrated the chart as a build-in tag in modelscope_studio@0.1.4. You can check the docs to find more details.

Thank you @Col0ring for this very useful feature! good job!