modelscope / modelscope-studio

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Plotly charts

codenprogressive opened this issue · comments

Hello, this is not an issue per say, but more of suggestion to support Plotly graphs. I know recently you integrated graphs of type echarts. Since our backend app (LLM) produces Plotly graphs I was wondering if modelscope-studio can support plotly graphs.

In mean time, here is how I did it using custom_components :

image

app_plotly_bar.py

import gradio as gr
import modelscope_studio as mgr
import os

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value',
             color = 'group')
#fig.show()

#generate json of plotly Figure
json_plotly= fig.to_json()


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

custom_components_plotly = {
    "chart-plotly": {
        "props": ["options"],
        "js": chart_js_plotly,
    }
}


conversation = [[
    None, {
        "text": f"""<chart-plotly options='{json_plotly}'></chart-plotly>"""
    }
]]

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

chart_plotly.js

(props, cc, { el }) => {
    el.innerHTML = ''
    const render = () => {
      const options = JSON.parse(props.options)
      el.style.height = '500px'
      el.style.width = '700px'
      Plotly.newPlot(el, options.data, options.layout)
    }
    if (!document.querySelector('plotly-script')) {
      const script = document.createElement('script')
      script.src =
        'https://cdn.plot.ly/plotly-2.30.1.min.js'
      script.id = 'plotly-script'
      script.onload = render
      document.head.appendChild(script)
    } else {
      render()
    }
  }

@liwalayouni Thank you for your suggestion again! But for now we are not considering integrating more graph libraries, Instead we prefer developers to use custom_components to implement more custom features as you did.

By the way, I'm sorry I made a mistake before, the sample code document.querySelector('plotly-script') should be replaced with document.querySelector('#plotly-script') to capture the cache condition, hope this helps!

thanks @Col0ring for your reply and for flagging the error :)