首页 > 其他分享 >AI应用任何PDF转换为交互式仪表盘

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

时间:2024-08-15 21:48:56浏览次数:12  
标签:electromagnet AI chart html fig 交互式 PDF ph data

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

背景   

     在不到一分钟的时间内将任何 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 兼容。

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


image


2. 上传数据文件

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

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

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


image


详细回复内容生成如下:

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.
  2. Data Preparation:

    • Structure the financial data from the report into a DataFrame for easy manipulation.
  3. Layout Creation:

    • Define the layout of the dashboard, including different charts for revenue streams.
  4. Chart Creation:

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

    • Add interactivity like hover effects, filters by year, and interactive legends.
  6. 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 dash, dcc, html, 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 生成的代码,然后单击“运行”。 几秒钟后,您将能够将仪表板全屏显示并与之交互!

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

image


测试@Llama-3-70b-Groq

测试的PDF https://sedl.org/afterschool/toolkits/science/pdf/ast_sci_data_tables_sample.pdf

image

生成代码

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd

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

# Define the 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_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 layout
app.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 app
if __name__ == '__main__':
     app.run_server(debug=True)


image


image


测试@Claude-3.5-Sonnet生成代码如下

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd

# Initialize the Dash app
app = 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)

生成了更详尽的图的代码

image

@ChatGPT-4o 生成的代码

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd

# Initialize the Dash app with responsive meta tags
app = 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 data
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)

image

测试@Gemini-1.5-Flash

生成的代码

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd

# Initialize the Dash app
app = 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, 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=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 fig

if __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环境中安装必要的包。


今天先到这儿,希望对AIGC,云原生,技术领导力, 企业管理,系统架构设计与评估,团队管理, 项目管理, 产品管理,信息安全,团队建设 有参考作用 , 您可能感兴趣的文章:
构建创业公司突击小团队
国际化环境下系统架构演化
微服务架构设计
视频直播平台的系统架构演化
微服务与Docker介绍
Docker与CI持续集成/CD
互联网电商购物车架构演变案例
互联网业务场景下消息队列架构
互联网高效研发团队管理演进之一
消息系统架构设计演进
互联网电商搜索架构演化之一
企业信息化与软件工程的迷思
企业项目化管理介绍
软件项目成功之要素
人际沟通风格介绍一
精益IT组织与分享式领导
学习型组织与企业
企业创新文化与等级观念
组织目标与个人目标
初创公司人才招聘与管理
人才公司环境与企业文化
企业文化、团队文化与知识共享
高效能的团队建设
项目管理沟通计划
构建高效的研发与自动化运维
某大型电商云平台实践
互联网数据库架构设计思路
IT基础架构规划方案一(网络系统规划)
餐饮行业解决方案之客户分析流程
餐饮行业解决方案之采购战略制定与实施流程
餐饮行业解决方案之业务设计流程
供应链需求调研CheckList
企业应用之性能实时度量系统演变

如有想了解更多软件设计与架构, 系统IT,企业信息化, 团队管理 资讯,请关注我的微信订阅号:

image_thumb2_thumb_thumb_thumb_thumb

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 该文章也同时发布在我的独立博客中-Petter Liu Blog。

标签:electromagnet,AI,chart,html,fig,交互式,PDF,ph,data
From: https://www.cnblogs.com/wintersun/p/18361864

相关文章

  • Markov Chain
    Anaturalwaytodealwithuncertaintyistointroduceprobabilisticrules. Inthesimplestcase,wecanimagineanFSM-likedevicehavingnocommands butclockticksassociatedwithprobabilities(seeFigure7.10). Thisdevicestartsitsoperationin......
  • 智匠MindCraft AI 1.2.6版本更新啦!!
    智匠MindCraftAI​​​​​​​迎来1.2.6版本更新,本次更新四大内容:1、网页代码及python代码渲染优化。更稳定的代码渲染功能,您可以在智匠AI中,实现炫酷的网页效果,或者用python制作图表和游戏。2、语音实验室增加语音识别功能,可识别多国语言和方言。用户可以在语音实验室中,选......
  • 洛谷题单指南-常见优化技巧-P2866 [USACO06NOV] Bad Hair Day S
    原题链接:https://www.luogu.com.cn/problem/P2866题意解读:每个牛能看到的右边比他矮的牛,直到有比他高的挡住为止,因此只用找每个牛右边第一个比他高的牛的位置即可计算中间比他矮的有多少。解题思路:典型的单调栈应用,注意,常规的单调栈可以用来:1、找每个数左边第一个比他小的数的......
  • 酷!化学数据分析AI实验室
    本文由ChatMoney团队出品AI确实是个好东西,但AI到底是有什么用?其实很多人都没搞明白。AI如果在某个行业用的好,是能带来很大经济价值的。就拿AI在化学应用来说,AI在化工领域上的应用和化学相关研究帮助都是很显著的。比如说医药行业,化学实验室,化学生物基因科学等等。化工领域同......
  • 化学数据分析AI实验室?ChatMoney帮你打造
    本文由ChatMoney团队出品AI确实是个好东西,但AI到底是有什么用?其实很多人都没搞明白。AI如果在某个行业用的好,是能带来很大经济价值的。就拿AI在化学应用来说,AI在化工领域上的应用和化学相关研究帮助都是很显著的。比如说医药行业,化学实验室,化学生物基因科学等等。化工领域同......
  • AI绘画支持:DallE·3/Midjouney全功能覆盖支持、SD绘画
    MidjourneyAI超强绘画原生态系统完美还原 MidjourneyAI超强绘画原生态系统界面完美还原操作功能统一中文界面功能齐全(支付系统、会员系统、分销系统、支持中转站可自己搭建中转站Midjourney-Proxy-Plus)支持MewAI绘画(MX)艺术二维码、条件生图、多种大模型、多种绘画......
  • DB+AI会擦出怎样的火花?一站式带你了解阿里云瑶池数据库经典的AI产品服务与实践!
    从DB+AI精选解决方案、特惠权益等,一站式带你了解阿里云瑶池数据库经典的AI产品服务与实践。点此了解DB+AI【方案、权益】一站通。https://www.aliyun.com/activity/database/db4ai前言GenAI时代下的数据库发展趋势阿里云瑶池数据库旨在为客户提供智能化的一站式数据管理......
  • 国内外AI大语言模型推荐分享 除了Chatgpt 你会选择哪个模型?
    当前AI技术飞速发展,Ai已经成为许多人日常工作和生活中不可或缺的工具,特别是以大语言模型为首的人工智能,它能够与我们进行自然语言对话,支持多种应用场景,如技术问答、代码生成、内容创作等,而且适用于各种群体和场景。现在国内外都有不少出色的大语言模型,这些模型在自然语言......
  • 亮相2024 DPU&AI Networking创新大会,天翼云斩获两项大奖!
    近日,以“智驱网络芯动未来”为主题的2024DPU&AINetworking创新大会在北京举办。大会表彰了在DPU与AI网络技术创新及实践应用中取得卓越成就的单位与项目,天翼云科技有限公司荣膺创新引擎奖、《紫金DPU算力卸载与网络加速应用》荣获实践先锋奖,技术创新实力以及应用实践成果再获行......
  • SciTech-BigDataAIML-LLM-Transformer Series-统计模型和大量数据 + MI移动互联+IoT万
    词汇MI(MobileInternet):移动互联网IoT(InternetofThings):万物互联网WE(WordEmbedding):词嵌入PE(PositionalEncoding):位置编码统计模型和大数据的保障和源头是"MI"和"IoT"。1真正"改革生产生活习惯"的是"国家政策"与"政府"。新经济的产生是以“改革生产生活......