AI应用任何PDF转换为交互式仪表盘

文摘   2024-08-19 07:20   云南  

 

背景   


 

     在不到一分钟的时间内将任何 PDF 转换为交互式仪表板(下面的提示词 ): 这适用于所有可以正确编码的 AI 聊天机器人,例如 ChatGPT 4o、Mistral Large 2、Claude Sonnet 3.5、Llama 405b 等大模型。

ChatGPT 4.0:
开发商: OpenAI
类型: 生成式预训练Transformer模型
特点:
强大的文本生成能力,可以进行对话、写作、翻译等多种任务。
具备一定的推理和逻辑能力,可以回答复杂问题并进行简单的逻辑推演。
拥有丰富的知识储备,可以提供各种信息和知识。

Mistral Large 2:
开发商: Mistral AI
类型: 生成式预训练Transformer模型
特点:
专注于效率和可解释性,旨在提供更轻量级、更易于部署的模型。
拥有较高的推理能力,可以进行更复杂的逻辑推演。
强调安全性和可控性,减少模型输出的风险。

Claude Sonnet 3.5:
开发商: Anthropic
类型: 生成式预训练Transformer模型
特点:
注重安全性和道德规范,旨在构建更负责任的 AI 模型。
拥有较强的对话能力,可以进行自然流畅的对话。
强调模型的可控性,允许用户设定模型的行为规范。

Llama 405b:
开发商: Meta
类型: 生成式预训练Transformer模型
特点:
拥有庞大的参数规模,可以处理更复杂的任务。
具备强大的文本生成能力,可以生成高质量的文本内容。
强调模型的开放性和可访问性,鼓励研究和应用。


 

1. 写这段提示词


 

"You're a Python developer with experience in creating data-driven visualizations. Develop a Python script to build a very modern looking (clean fonts, colors), interactive dashboard that: - Displays the evolution of the key figures in this PDF document with appropriate type of charts, filters, etc.

- Create as many charts as necessary, one below the other.
- Don't hesitate to compare current figures with previous periods
- Use Plotly Dash for the dashboard.
- Ensure the code is compatible with Replit.
The dashboard should include dynamic features like hover effects, filters by year, and interactive legends. Format the script with comments explaining key sections and use a clear, professional tone throughout the code. Think step by step to avoid code errors. Just write the full script."

“您是一名 Python 开发人员,在创建数据驱动的可视化方面具有丰富的经验。开发一个 Python 脚本来构建一个非常现代的外观(干净的字体、颜色)的交互式仪表板,该仪表板:

- 显示此 PDF 文档中关键指标的演变,并带有适当类型的图表、过滤器等。 - 根据需要创建尽可能多的图表,一个在另一个下方。

- 不要犹豫,将当前数据与以前的时期进行比较 - 使用 Plotly Dash 作为仪表板。

- 确保代码与 Replit 兼容。

仪表板应包含动态功能,例如悬停效果、按年份筛选和交互式图例。使用解释关键部分的注释来设置脚本的格式,并在整个代码中使用清晰、专业的语。循序渐进地思考,以避免代码错误。只需编写完整的脚本代码即可。”



 

2. 上传数据文件


 

您的文件 在发送提示之前,请上传包含您的数据的文件。 这也适用于 XLSX、CSV 和更多文件。

这里我们使用是2023年微软的年度报告,是docx文件,下载下来我们先转pdf

https://c.s-microsoft.com/en-us/CMSFiles/2023_Annual_Report.docx?version=dfd6ff7f-0999-881d-bedf-c6d9dadab40b



 

详细回复内容生成如下:

To create the Python script for a modern-looking interactive dashboard using Plotly Dash, I'll start by extracting the key figures from the provided PDF document. Then, I'll guide you through the script that builds the dashboard. Let's start by examining the PDF to identify the key figures for visualization.

I'll begin by extracting the text from the PDF to identify relevant data.

Let me do that first.

The extracted text from the PDF appears to contain introductory and narrative sections, which don't directly reveal numerical data or key figures. To find relevant data such as financial metrics, tables, or charts, I'll need to perform a more detailed analysis of the text or specific pages.

I'll refine my approach to extract potential financial figures or key statistics by searching for terms like "revenue," "income," "profit," "expense," "growth," or other similar keywords within the document.

Let me perform this search now.

The search returned some relevant snippets, especially around the term "revenue." Here's a key excerpt:

  • Revenue:

    • Productivity and Business Processes: $69.274 billion (2023) vs. $63.364 billion (2022), a 9% increase.

    • Intelligent Cloud: $87.907 billion (2023) vs. $74.965 billion (2022), a 17% increase.

The document contains financial metrics that can be used to create a dashboard displaying revenue growth in different segments. To proceed, I'll outline and develop a Python script using Plotly Dash that visualizes these figures.

Key Steps in the Script:
  1. Setup & Initialization:

  • Import necessary libraries and initialize the Dash app.

  • Data Preparation:

    • Structure the financial data from the report into a DataFrame for easy manipulation.

  • Layout Creation:

    • Define the layout of the dashboard, including different charts for revenue streams.

  • Chart Creation:

    • Create individual charts (e.g., line charts) to show revenue over the years for different segments.

  • Interactivity:

    • Add interactivity like hover effects, filters by year, and interactive legends.

  • Running the App:

    • Configure the app to run on Replit.

    Now, I'll write the full script for this dashboard:

    # Import necessary libraries
    import dash
    from dash import dcc, html
    import plotly.graph_objs as go
    import pandas as pd

    # Initialize the Dash app
    app = dash.Dash(__name__)

    # Data Preparation
    # Creating a DataFrame with the key figures extracted from the PDF
    data = {
    "Year": [2022, 2023],
    "Productivity and Business Processes (Billion $)": [63.364, 69.274],
    "Intelligent Cloud (Billion $)": [74.965, 87.907]
    }

    df = pd.DataFrame(data)

    # Layout creation
    app.layout = html.Div([
    html.H1("Annual Report Dashboard", style={'text-align': 'center', 'font-family': 'Arial, sans-serif', 'color': '#4a4a4a'}),

    # Line chart for Productivity and Business Processes
    dcc.Graph(
    id='prod-business-processes',
    figure={
    'data': [
    go.Scatter(
    x=df['Year'],
    y=df['Productivity and Business Processes (Billion $)'],
    mode='lines+markers',
    name='Productivity and Business Processes',
    line=dict(color='blue'),
    marker=dict(size=8)
    )
    ],
    'layout': go.Layout(
    title="Productivity and Business Processes Revenue Over Years",
    xaxis={'title': 'Year'},
    yaxis={'title': 'Revenue (Billion $)'},
    hovermode='closest'
    )
    }
    ),

    # Line chart for Intelligent Cloud
    dcc.Graph(
    id='intelligent-cloud',
    figure={
    'data': [
    go.Scatter(
    x=df['Year'],
    y=df['Intelligent Cloud (Billion $)'],
    mode='lines+markers',
    name='Intelligent Cloud',
    line=dict(color='green'),
    marker=dict(size=8)
    )
    ],
    'layout': go.Layout(
    title="Intelligent Cloud Revenue Over Years",
    xaxis={'title': 'Year'},
    yaxis={'title': 'Revenue (Billion $)'},
    hovermode='closest'
    )
    }
    ),

    # Filter by year
    html.Label("Filter by Year", style={'font-family': 'Arial, sans-serif', 'color': '#4a4a4a'}),
    dcc.Slider(
    id='year-slider',
    min=df['Year'].min(),
    max=df['Year'].max(),
    value=df['Year'].max(),
    marks={str(year): str(year) for year in df['Year']},
    step=None
    )
    ])

    # Interactivity callback for year slider
    @app.callback(
    [dash.dependencies.Output(
    'prod-business-processes', 'figure'
    ),
    dash.dependencies.Output(
    'intelligent-cloud', 'figure'
    )],
    [dash.dependencies.Input(
    'year-slider', 'value'
    )]
    )
    def update_charts(selected_year):
    filtered_df = df[df['Year'] <= selected_year]

    # Update Productivity and Business Processes chart
    prod_fig = go.Figure(
    data=[
    go.Scatter(
    x=filtered_df['Year'],
    y=filtered_df['Productivity and Business Processes (Billion $)'],
    mode='lines+markers',
    name='Productivity and Business Processes',
    line=dict(color='blue'),
    marker=dict(size=8)
    )
    ],
    layout=go.Layout(
    title="Productivity and Business Processes Revenue Over Years",
    xaxis={'title': 'Year'},
    yaxis={'title': 'Revenue (Billion $)'},
    hovermode='closest'
    )
    )

    # Update Intelligent Cloud chart
    cloud_fig = go.Figure(
    data=[
    go.Scatter(
    x=filtered_df['Year'],
    y=filtered_df['Intelligent Cloud (Billion $)'],
    mode='lines+markers',
    name='Intelligent Cloud',
    line=dict(color='green'),
    marker=dict(size=8)
    )
    ],
    layout=go.Layout(
    title="Intelligent Cloud Revenue Over Years",
    xaxis={'title': 'Year'},
    yaxis={'title': 'Revenue (Billion $)'},
    hovermode='closest'
    )
    )

    return prod_fig, cloud_fig

    # Run the app (ensure it runs in Replit)
    if __name__ == '__main__':
    app.run_server(debug=True, host='0.0.0.0', port=8080)


    Explanation:
    • Imports: The script imports dashdcchtml, and plotly.graph_objs for creating interactive components and visualizations.

    • Data Preparation: A DataFrame is created with the key revenue figures extracted from the report.

    • Layout: The layout contains two line charts, one for "Productivity and Business Processes" and another for "Intelligent Cloud." A slider allows filtering by year.

    • Callbacks: Interactivity is achieved using a callback function that updates the charts based on the year selected in the slider.

    • Running on Replit: The script includes configuration to run on Replit, specifying the host and port.

    This script is a solid foundation for building a more complex dashboard if more data is extracted. You can enhance it further by adding additional financial metrics and comparison features.


    3. 将代码复制到 Replit在线编译

         如果您还没有帐户,请在 replit.com 上创建一个帐户。 创建一个新的 Python template,粘贴 AI 生成的代码,然后单击“运行”。 几秒钟后,您将能够将仪表板全屏显示并与之交互!

    注意:您还可以部署此仪表板以通过简单链接共享它。如下:


     

    测试@Llama-3-70b-Groq


     

    测试的PDF 

     https://sedl.org/afterschool/toolkits/science/pdf/ast_sci_data_tables_sample.pdf

    生成代码

    import dashfrom dash import dcc, htmlfrom dash.dependencies import Input, Outputimport plotly.graph_objs as goimport plotly.express as pximport pandas as pd# Initialize the Dash appapp = dash.Dash(__name__)# Define the datapet_survey = pd.DataFrame({     'Pet': ['Lizard', 'Dog', 'Cat', 'Bird', 'Guinea pig', 'Hamster', 'Fish', 'Ferret'],     'Count': [25, 250, 115, 50, 30, 45, 75, 10]})electromagnet_data = pd.DataFrame({     'Coils': [5, 10, 15, 20],     'Trial1': [3, 7, 11, 15],     'Trial2': [5, 8, 10, 13],     'Trial3': [4, 6, 12, 14]})ph_data = pd.DataFrame({     'Substance': ['Lemon juice', 'Baking soda in Water'],     'pH1': [2.4, 8.4],     'pH2': [2.0, 8.3],     'pH3': [2.2, 8.7]})# Define the layoutapp.layout = html.Div([     html.H1("Science Data Dashboard", style={'textAlign': 'center'}),         # Pet Survey Chart     html.Div([         html.H2("Pet Survey Results"),         dcc.Graph(id='pet-survey-chart')     ]),         # Electromagnet Chart     html.Div([         html.H2("Electromagnet Experiment"),         dcc.Graph(id='electromagnet-chart')     ]),         # pH Chart     html.Div([         html.H2("pH of Household Substances"),         dcc.Graph(id='ph-chart')     ])])# Callbacks for each chart@app.callback(     Output('pet-survey-chart', 'figure'),     Input('pet-survey-chart', 'id'))def update_pet_survey_chart(_):     fig = px.bar(pet_survey, x='Pet', y='Count', title='Pet Survey Results')     fig.update_layout(transition_duration=500)     return fig@app.callback(     Output('electromagnet-chart', 'figure'),     Input('electromagnet-chart', 'id'))def update_electromagnet_chart(_):     fig = go.Figure()     for trial in ['Trial1', 'Trial2', 'Trial3']:         fig.add_trace(go.Scatter(x=electromagnet_data['Coils'], y=electromagnet_data[trial],                                  mode='lines+markers', name=f'{trial}'))     fig.update_layout(title='Electromagnet Experiment: Number of Paperclips vs Coils',                       xaxis_title='Number of Coils', yaxis_title='Number of Paperclips')     return fig@app.callback(     Output('ph-chart', 'figure'),     Input('ph-chart', 'id'))def update_ph_chart(_):     ph_data['Average_pH'] = ph_data[['pH1', 'pH2', 'pH3']].mean(axis=1)     fig = px.bar(ph_data, x='Substance', y='Average_pH', title='Average pH of Household Substances')     fig.update_layout(xaxis={'categoryorder':'total ascending'})     return fig# Run the appif __name__ == '__main__':     app.run_server(debug=True)



     

    测试@Claude-3.5-Sonnet


     

     

    生成代码如下
    import dashfrom dash import dcc, htmlfrom dash.dependencies import Input, Outputimport plotly.graph_objs as goimport plotly.express as pximport pandas as pd# Initialize the Dash appapp = dash.Dash(     __name__,     meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],)
    def load_data(): """Load and prepare data for the dashboard.""" try: pet_survey = pd.DataFrame( { "Pet": [ "Lizard", "Dog", "Cat", "Bird", "Guinea pig", "Hamster", "Fish", "Ferret", ], "Count": [25, 250, 115, 50, 30, 45, 75, 10], } ) electromagnet_data = pd.DataFrame( { "Coils": [5, 10, 15, 20], "Trial1": [3, 7, 11, 15], "Trial2": [5, 8, 10, 13], "Trial3": [4, 6, 12, 14], } ) ph_data = pd.DataFrame( { "Substance": [ "Lemon juice", "Baking soda in Water", "Orange juice", "Battery acid", "Apples", "Tomatoes", "Bottled water", "Milk of magnesia", "Liquid hand soap", "Vinegar", "Household bleach", "Milk", "Household ammonia", "Lye", "Sodium hydroxide", "Anti-freeze", "Windex", "Liquid detergent", "Cola", ], "pH1": [ 2.4, 8.4, 3.5, 1.0, 3.0, 4.5, 6.7, 10.5, 9.0, 2.2, 12.5, 6.6, 11.5, 13.0, 14.0, 10.1, 9.9, 10.5, 3.0, ], "pH2": [ 2.0, 8.3, 4.0, 0.7, 3.2, 4.2, 7.0, 10.3, 10.0, 2.9, 12.5, 6.5, 11.0, 13.5, 14.0, 10.9, 10.2, 10.0, 2.5, ], "pH3": [ 2.2, 8.7, 3.4, 0.5, 3.5, 4.0, 7.2, 10.6, 9.5, 3.0, 12.7, 6.4, 11.5, 13.4, 13.9, 9.7, 9.5, 10.3, 3.2, ], } ) ph_data["Average_pH"] = ph_data[["pH1", "pH2", "pH3"]].mean(axis=1) return pet_survey, electromagnet_data, ph_data except Exception as e: print(f"Error loading data: {e}") return None, None, None
    pet_survey, electromagnet_data, ph_data = load_data()
    def create_layout(): """Create the layout for the dashboard.""" return html.Div( [ html.H1("Science Data Dashboard", style={"textAlign": "center"}), # Pet Survey Chart html.Div( [html.H2("Pet Survey Results"), dcc.Graph(id="pet-survey-chart")], className="chart-container", ), # Electromagnet Chart html.Div( [ html.H2("Electromagnet Experiment"), dcc.Graph(id="electromagnet-chart"), dcc.Slider( id="coil-slider", min=electromagnet_data["Coils"].min(), max=electromagnet_data["Coils"].max(), step=5, value=electromagnet_data["Coils"].max(), marks={ str(coil): str(coil) for coil in electromagnet_data["Coils"] }, ), ], className="chart-container", ), # pH Chart html.Div( [ html.H2("pH of Household Substances"), dcc.Graph(id="ph-chart"), dcc.Dropdown( id="ph-dropdown", options=[ {"label": substance, "value": substance} for substance in ph_data["Substance"] ], value=ph_data["Substance"].tolist(), multi=True, ), ], className="chart-container", ), ] )
    app.layout = create_layout()
    @app.callback(Output("pet-survey-chart", "figure"), Input("pet-survey-chart", "id"))def update_pet_survey_chart(_): fig = px.bar(pet_survey, x="Pet", y="Count", title="Pet Survey Results") fig.update_layout(transition_duration=500) return fig
    @app.callback(Output("electromagnet-chart", "figure"), Input("coil-slider", "value"))def update_electromagnet_chart(max_coils): filtered_data = electromagnet_data[electromagnet_data["Coils"] <= max_coils] fig = go.Figure() for trial in ["Trial1", "Trial2", "Trial3"]: fig.add_trace( go.Scatter( x=filtered_data["Coils"], y=filtered_data[trial], mode="lines+markers", name=f"{trial}", ) ) fig.update_layout( title="Electromagnet Experiment: Number of Paperclips vs Coils", xaxis_title="Number of Coils", yaxis_title="Number of Paperclips", ) return fig
    @app.callback(Output("ph-chart", "figure"), Input("ph-dropdown", "value"))def update_ph_chart(selected_substances): filtered_data = ph_data[ph_data["Substance"].isin(selected_substances)] fig = px.bar( filtered_data, x="Substance", y="Average_pH", title="Average pH of Household Substances", color="Average_pH", color_continuous_scale="RdBu_r", ) fig.update_layout(xaxis={"categoryorder": "total ascending"}) return fig
    if __name__ == "__main__": app.run_server(debug=True)

    生成了更详尽的图的代码

     

    @ChatGPT-4o 生成的代码


     

    import dashfrom dash import dcc, htmlfrom dash.dependencies import Input, Outputimport plotly.graph_objs as goimport plotly.express as pximport pandas as pd# Initialize the Dash app with responsive meta tagsapp = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}])def load_data():     """Load and prepare data for the dashboard."""     try:         # Pet Survey Data         pet_survey = pd.DataFrame({             'Pet': ['Lizard', 'Dog', 'Cat', 'Bird', 'Guinea pig', 'Hamster', 'Fish', 'Ferret'],             'Count': [25, 250, 115, 50, 30, 45, 75, 10]         })        # Electromagnet Experiment Data         electromagnet_data = pd.DataFrame({             'Coils': [5, 10, 15, 20],             'Trial1': [3, 7, 11, 15],             'Trial2': [5, 8, 10, 13],             'Trial3': [4, 6, 12, 14]         })        # pH Data for Household Substances         ph_data = pd.DataFrame({             'Substance': ['Lemon juice', 'Baking soda in Water', 'Orange juice', 'Battery acid', 'Apples',                           'Tomatoes', 'Bottled water', 'Milk of magnesia', 'Liquid hand soap', 'Vinegar',                           'Household bleach', 'Milk', 'Household ammonia', 'Lye', 'Sodium hydroxide',                           'Anti-freeze', 'Windex', 'Liquid detergent', 'Cola'],             'pH1': [2.4, 8.4, 3.5, 1.0, 3.0, 4.5, 6.7, 10.5, 9.0, 2.2, 12.5, 6.6, 11.5, 13.0, 14.0, 10.1, 9.9, 10.5, 3.0],             'pH2': [2.0, 8.3, 4.0, 0.7, 3.2, 4.2, 7.0, 10.3, 10.0, 2.9, 12.5, 6.5, 11.0, 13.5, 14.0, 10.9, 10.2, 10.0, 2.5],             'pH3': [2.2, 8.7, 3.4, 0.5, 3.5, 4.0, 7.2, 10.6, 9.5, 3.0, 12.7, 6.4, 11.5, 13.4, 13.9, 9.7, 9.5, 10.3, 3.2]         })         ph_data['Average_pH'] = ph_data[['pH1', 'pH2', 'pH3']].mean(axis=1)        return pet_survey, electromagnet_data, ph_data     except Exception as e:         print(f"Error loading data: {e}")         return None, None, None# Load datapet_survey, electromagnet_data, ph_data = load_data()def create_layout():     """Create the layout for the dashboard."""     return html.Div([         html.H1("Science Data Dashboard", style={'textAlign': 'center'}),                 # Pet Survey Chart         html.Div([             html.H2("Pet Survey Results"),             dcc.Graph(id='pet-survey-chart')         ], className='chart-container'),                 # Electromagnet Chart         html.Div([             html.H2("Electromagnet Experiment"),             dcc.Graph(id='electromagnet-chart'),             dcc.Slider(                 id='coil-slider',                 min=electromagnet_data['Coils'].min(),                 max=electromagnet_data['Coils'].max(),                 step=5,                 value=electromagnet_data['Coils'].max(),                 marks={str(coil): str(coil) for coil in electromagnet_data['Coils']}             )         ], className='chart-container'),                 # pH Chart         html.Div([             html.H2("pH of Household Substances"),             dcc.Graph(id='ph-chart'),             dcc.Dropdown(                 id='ph-dropdown',                 options=[{'label': substance, 'value': substance} for substance in ph_data['Substance']],                 value=ph_data['Substance'].tolist(),                 multi=True             )         ], className='chart-container')     ])app.layout = create_layout()@app.callback(     Output('pet-survey-chart', 'figure'),     Input('pet-survey-chart', 'id'))def update_pet_survey_chart(_):     fig = px.bar(pet_survey, x='Pet', y='Count', title='Pet Survey Results')     fig.update_layout(transition_duration=500)     return fig@app.callback(     Output('electromagnet-chart', 'figure'),     Input('coil-slider', 'value'))def update_electromagnet_chart(max_coils):     filtered_data = electromagnet_data[electromagnet_data['Coils'] <= max_coils]     fig = go.Figure()     for trial in ['Trial1', 'Trial2', 'Trial3']:         fig.add_trace(go.Scatter(x=filtered_data['Coils'], y=filtered_data[trial],                                  mode='lines+markers', name=f'{trial}'))     fig.update_layout(title='Electromagnet Experiment: Number of Paperclips vs Coils',                       xaxis_title='Number of Coils', yaxis_title='Number of Paperclips')     return fig@app.callback(     Output('ph-chart', 'figure'),     Input('ph-dropdown', 'value'))def update_ph_chart(selected_substances):     filtered_data = ph_data[ph_data['Substance'].isin(selected_substances)]     fig = px.bar(filtered_data, x='Substance', y='Average_pH', title='Average pH of Household Substances',                  color='Average_pH', color_continuous_scale='RdBu_r')     fig.update_layout(xaxis={'categoryorder':'total ascending'})     return figif __name__ == '__main__':     app.run_server(debug=True)

     

    测试@Gemini-1.5-Flash


     

    生成的代码

    import dashfrom dash import dcc, htmlfrom dash.dependencies import Input, Outputimport plotly.graph_objs as goimport plotly.express as pximport pandas as pd# Initialize the Dash appapp = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}])def load_data():     """Load and prepare data for the dashboard, with validation checks."""     try:         pet_survey = pd.DataFrame({             'Pet': ['Lizard', 'Dog', 'Cat', 'Bird', 'Guinea pig', 'Hamster', 'Fish', 'Ferret'],             'Count': [25, 250, 115, 50, 30, 45, 75, 10]         })                 # Validate pet_survey data         if not all(isinstance(count, (int, float)) for count in pet_survey['Count']):             raise ValueError("Invalid data type in 'Count' column of pet_survey DataFrame.")        electromagnet_data = pd.DataFrame({             'Coils': [5, 10, 15, 20],             'Trial1': [3, 7, 11, 15],             'Trial2': [5, 8, 10, 13],             'Trial3': [4, 6, 12, 14]         })        ph_data = pd.DataFrame({             'Substance': ['Lemon juice', 'Baking soda in Water', 'Orange juice', 'Battery acid', 'Apples',                           'Tomatoes', 'Bottled water', 'Milk of magnesia', 'Liquid hand soap', 'Vinegar',                           'Household bleach', 'Milk', 'Household ammonia', 'Lye', 'Sodium hydroxide',                           'Anti-freeze', 'Windex', 'Liquid detergent', 'Cola'],             'pH1': [2.4, 8.4, 3.5, 1.0, 3.0, 4.5, 6.7, 10.5, 9.0, 2.2, 12.5, 6.6, 11.5, 13.0, 14.0, 10.1, 9.9, 10.5, 3.0],             'pH2': [2.0, 8.3, 4.0, 0.7, 3.2, 4.2, 7.0, 10.3, 10.0, 2.9, 12.5, 6.5, 11.0, 13.5, 14.0, 10.9, 10.2, 10.0, 2.5],             'pH3': [2.2, 8.7, 3.4, 0.5, 3.5, 4.0, 7.2, 10.6, 9.5, 3.0, 12.7, 6.4, 11.5, 13.4, 13.9, 9.7, 9.5, 10.3, 3.2]         })         ph_data['Average_pH'] = ph_data[['pH1', 'pH2', 'pH3']].mean(axis=1)        return pet_survey, electromagnet_data, ph_data     except Exception as e:         print(f"Error loading data: {e}")         return None, None, Nonepet_survey, electromagnet_data, ph_data = load_data()def create_layout():     """Create the layout for the dashboard."""     return html.Div([         html.H1("Science Data Dashboard", style={'textAlign': 'center'}),                 # Pet Survey Chart         html.Div([             html.H2("Pet Survey Results"),             dcc.Graph(id='pet-survey-chart')         ], className='chart-container'),                 # Electromagnet Chart         html.Div([             html.H2("Electromagnet Experiment"),             dcc.Graph(id='electromagnet-chart'),             dcc.Slider(                 id='coil-slider',                 min=electromagnet_data['Coils'].min(),                 max=electromagnet_data['Coils'].max(),                 step=5,                 value=electromagnet_data['Coils'].max(),                 marks={str(coil): str(coil) for coil in electromagnet_data['Coils']}             )         ], className='chart-container'),                 # pH Chart         html.Div([             html.H2("pH of Household Substances"),             dcc.Graph(id='ph-chart'),             dcc.Dropdown(                 id='ph-dropdown',                 options=[{'label': substance, 'value': substance} for substance in ph_data['Substance']],                 value=ph_data['Substance'].tolist(),                 multi=True             )         ], className='chart-container')     ])app.layout = create_layout()@app.callback(     Output('pet-survey-chart', 'figure'),     Input('pet-survey-chart', 'id'))def update_pet_survey_chart(_):     fig = px.bar(pet_survey, x='Pet', y='Count', title='Pet Survey Results')     fig.update_layout(transition_duration=500)     return fig@app.callback(     Output('electromagnet-chart', 'figure'),     Input('coil-slider', 'value'))def update_electromagnet_chart(max_coils):     filtered_data = electromagnet_data[electromagnet_data['Coils'] <= max_coils]     fig = go.Figure()     for trial in ['Trial1', 'Trial2', 'Trial3']:         fig.add_trace(go.Scatter(x=filtered_data['Coils'], y=filtered_data[trial],                                  mode='lines+markers', name=f'{trial}'))     fig.update_layout(title=f'Electromagnet Experiment: Number of Paperclips vs Coils (Max Coils: {max_coils})',                       xaxis_title='Number of Coils', yaxis_title='Number of Paperclips')     return fig@app.callback(     Output('ph-chart', 'figure'),     Input('ph-dropdown', 'value'))def update_ph_chart(selected_substances):     filtered_data = ph_data[ph_data['Substance'].isin(selected_substances)]     fig = px.bar(filtered_data, x='Substance', y='Average_pH', title='Average pH of Household Substances',                  color='Average_pH', color_continuous_scale='RdBu_r')     fig.update_layout(xaxis={'categoryorder':'total ascending'})     return figif __name__ == '__main__':     app.run_server(debug=True)

     

    结论


     

           ChatGPT-4o-Latest 提供了一个改进后的Python脚本,实现了一个科学数据仪表板。该脚本包含了宠物调查、电磁铁实验和家用物质pH值的数据可视化。主要改进包括:完整的数据集、交互性功能(如电磁铁图表的滑块和pH图表的下拉菜单)、响应式设计、错误处理和更好的代码组织。Mixtral-8x7B-Chat 对改进表示赞同,并总结了主要变化。它还提供了在Replit上部署该脚本的具体步骤,包括创建requirements.txt文件和配置运行命令。

    Gemini-1.5-Flash 分析了脚本的优点,并提出了进一步改进的建议,如:

    1. 增加数据验证

    2. 自定义图表外观

    3. 增强数据过滤功能

    4. 动态更新图表标题

    5. 添加数据表格

    6. 加入用户反馈机制

    Gemini-1.5-Flash 还提供了一个refined代码示例,实现了部分建议的改进,如数据验证和动态标题更新。最后,它提醒在Replit环境中安装必要的包。


        使用AI工具能快速生成视化图表代码,Replit在线运行代码实际上就是Serverless应用场景, 后现代趋势就是AI+Serverless轻量级应用接入。

    Megadotnet
    为您介绍各体系平台的新闻,系统研发相关框架,组件,方法,过程,运维,设计。企业IT与互联网信息系统或产品解决方案。开源项目,项目管理。
     最新文章