PYTHON WEB 开发(人工智能) · 第 6 章实验指导书

AI 数据分析看板

从一个空白目录开始,逐步完成 CSV 上传、pandas 数据清洗与统计、Matplotlib 图表、Flask 页面和大模型洞察报告。本指导书中的完整代码与旁边的 ai-data-dashboard 项目保持一致。

6 个开发步骤Flask + pandas + MatplotlibMiMo / OpenAI 兼容接口约 4 课时

实验目标与数据流

完成后,你可以说明文件从浏览器进入 Flask 后如何校验、清洗、统计并绘图;能够解释为什么模型只接收聚合摘要,以及如何处理模型未配置或返回异常的情况。

选择 CSV → Flask 校验 → pandas 清洗与汇总 → 生成图表 → 汇总数据脱敏 → 请求大模型 → 页面展示统计、图表和 AI 报告

数据边界:原始 CSV 只在应用内存中读取,不保存到静态目录。发给模型前,类别文本替换为“类别1、类别2”等匿名标签;请求仅包含聚合值与统计数据。请只使用有权处理的数据。

项目最终文件结构

ai-data-dashboard/
├── app.py                       # Flask 路由、数据处理、图表与模型 API
├── .env.example                 # 模型配置模板
├── .gitignore
├── requirements.txt             # Python 依赖
├── README.md                    # 安装、数据格式和运行说明
├── templates/
│   └── index.html               # 上传表单和看板页面
└── static/
    ├── app.js                   # 上传请求及结果渲染
    ├── style.css                # 页面样式
    ├── sample_sales.csv         # 页面内置下载的样例
    ├── sales_public_100.csv     # 100 条公开合成数据
    └── sales_public_240.csv     # 240 条公开合成数据

所有代码文件可在下方各步骤中展开查看;样例和测试数据文件可从这里打开:

步骤导航

01准备

建立项目结构与运行环境

先建立独立项目目录,安装 Flask、pandas、Matplotlib 和 python-dotenv。先准备好空的密钥配置文件,真实密钥只写在本机 .env,不放进代码或提交到仓库。

本步文件结构

ai-data-dashboard/
├── app.py
├── .env.example
├── .gitignore
├── requirements.txt
├── README.md
├── templates/
│   └── index.html
└── static/
    ├── app.js
    ├── style.css
    ├── sample_sales.csv
    ├── sales_public_100.csv
    └── sales_public_240.csv

操作要点

从项目目录创建虚拟环境并安装依赖。将 .env.example 复制为 .env;先留空 MIMO_API_KEY 也能运行本地统计功能。

完整代码

展开文件名即可查看完整内容;“打开/下载源文件”可直接查看项目对应文件。

requirements.txt打开/下载源文件 ↗
# Flask serves the page and JSON analysis endpoints.
# Flask 用于提供页面和 JSON 分析接口。
Flask>=3.0,<4.0
# pandas reads CSV files and calculates grouped statistics.
# pandas 用于读取 CSV 并计算分组统计。
pandas>=2.1,<4.0
# Matplotlib renders category and monthly charts.
# Matplotlib 用于在服务端生成类别和月度图表。
matplotlib>=3.8,<4.0
# python-dotenv loads local settings from .env.
# python-dotenv 用于从 .env 加载本地配置。
python-dotenv>=1.0,<2.0
.env.example打开/下载源文件 ↗
# Optional model settings; copy this file to .env for local development.
# 可选模型配置;本地开发时将本文件复制为 .env。
# Keep the real API key here, never in app.py or browser JavaScript.
# 真实密钥只保存在本地配置中,不要写入 app.py 或前端脚本。
MIMO_API_KEY=
# API base URL and chat model used by Flask.
# Flask 服务使用的 API 地址和对话模型。
MIMO_BASE_URL=https://api.xiaomimimo.com/v1
MIMO_MODEL=mimo-v2.6-flash
# Local Flask port; change it if 5006 is occupied.
# Flask 本机端口;若 5006 已被占用可修改。
PORT=5006
.gitignore打开/下载源文件 ↗
# Exclude local secrets and virtual environment from version control.
# 将本地密钥和虚拟环境排除在版本管理之外。
.env
.venv/
# Python cache and bytecode are generated automatically.
# Python 缓存和字节码会自动生成,无需提交。
__pycache__/
*.py[cod]
02后端

编写 Flask 后端与数据分析流程

后端负责接收上传、校验格式、用 pandas 清洗统计、绘制两张图,并在服务端调用 MiMo OpenAI 兼容接口。原始文件仅在内存中读取,模型请求只包含脱敏聚合摘要。

本步文件结构

ai-data-dashboard/
└── app.py  # 完整后端:路由、校验、清洗、统计、绘图、模型调用

操作要点

重点阅读 read_csv_upload、make_analysis、anonymized_model_summary 和 request_ai_insight。留意上传大小限制设在 Flask 配置中,文件内容由 upload.read() 读入内存,没有保存原始 CSV。

完整代码

展开文件名即可查看完整内容;“打开/下载源文件”可直接查看项目对应文件。

app.py打开/下载源文件 ↗
"""Flask + pandas + LLM data analysis teaching demo.
Flask + pandas + 大模型数据分析教学示例。

请求链路:上传 CSV -> 清洗并聚合 -> 生成图表 -> 将脱敏摘要发给模型。
原始 CSV 不写入磁盘,图表以内嵌 base64 图片返回浏览器。
"""

from __future__ import annotations

import base64
import io
import json
import logging
import os
import re
import urllib.error
import urllib.request
# Use a non-interactive backend because charts are rendered on the server.
# 使用非交互式后端,因为图表由服务器生成。
# They are returned in the page instead of opening a desktop window.
# 图表会返回到网页中,不会在桌面窗口打开。
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
from dotenv import load_dotenv
from flask import Flask, jsonify, render_template, request

# Load local development settings from .env.
# 从 .env 加载本地开发配置。
# Production can set the same variables through its process or container.
# 生产环境也可通过进程或容器变量传入相同配置。
load_dotenv()

# Keep upload and analysis limits together for easy classroom adjustment.
# 将上传和分析限制集中定义,便于课堂调整。
ROOT = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 2 * 1024 * 1024
app.logger.setLevel(logging.INFO)

# These columns define the sales dataset accepted by this demo.
# 这些字段定义了本示例支持的销售数据格式。
REQUIRED_COLUMNS = {"date", "category", "amount", "quantity"}
MAX_ROWS = 20_000
MAX_CATEGORIES = 12


class DataError(ValueError):
    """A user-correctable CSV or validation error
    可由用户修正的 CSV 或数据校验错误。
    """


def read_csv_upload(file_bytes: bytes) -> pd.DataFrame:
    """Read request bytes and validate size, encoding, and schema
    读取请求字节并校验文件大小、编码和字段结构。
    """
    if not file_bytes:
        raise DataError("CSV 文件为空,请选择包含数据行的文件。")

    frame = None
    last_error = None
    # Try common classroom encodings.
    # 依次尝试课堂中常见的文件编码。
    # utf-8-sig also removes a UTF-8 BOM.
    # utf-8-sig 还会自动移除 UTF-8 文件开头的 BOM 标记。
    for encoding in ("utf-8-sig", "gbk"):
        try:
            frame = pd.read_csv(io.BytesIO(file_bytes), encoding=encoding)
            break
        except UnicodeDecodeError as exc:
            last_error = exc
        except pd.errors.EmptyDataError as exc:
            raise DataError("CSV 文件没有可读取的表头或数据。") from exc
        except pd.errors.ParserError as exc:
            raise DataError("CSV 格式无法解析,请检查分隔符和引号。") from exc
    if frame is None:
        raise DataError("无法识别 CSV 编码,请另存为 UTF-8 或 GBK 编码。") from last_error
    if frame.empty:
        raise DataError("CSV 中没有数据行。")
    if len(frame) > MAX_ROWS:
        raise DataError(f"演示版最多分析 {MAX_ROWS:,} 行,请缩小文件后重试。")

    # Normalize names so Date and DATE match the schema.
    # 统一列名格式,使 Date、DATE 都能匹配必需字段。
    frame.columns = [str(column).strip().lower() for column in frame.columns]
    missing_columns = sorted(REQUIRED_COLUMNS - set(frame.columns))
    if missing_columns:
        raise DataError("缺少必要列:" + ", ".join(missing_columns))

    return frame


def make_analysis(frame: pd.DataFrame) -> tuple[pd.DataFrame, dict]:
    """Clean required fields and calculate chart/UI metrics
    清洗必需字段,并计算图表和页面所需指标。
    """
    raw_rows = len(frame)
    # Capture missing counts before dropping invalid rows.
    # 删除无效行前先统计各列缺失值,供报告展示。
    missing_before = {str(k): int(v) for k, v in frame.isna().sum().items()}
    clean = frame.copy()

    # Convert text columns to types needed for grouping and arithmetic.
    # 将文本列转换为分组和计算所需的数据类型。
    clean["date"] = pd.to_datetime(clean["date"], errors="coerce")
    clean["amount"] = pd.to_numeric(clean["amount"], errors="coerce")
    clean["quantity"] = pd.to_numeric(clean["quantity"], errors="coerce")
    clean["category"] = clean["category"].astype("string").str.strip()
    # Remove records with invalid required values or impossible sales amounts.
    # 移除必需字段无效或金额、数量不合理的记录。
    clean = clean.dropna(subset=list(REQUIRED_COLUMNS))
    clean = clean[(clean["amount"] >= 0) & (clean["quantity"] > 0)]
    clean = clean[clean["category"] != ""]
    if clean.empty:
        raise DataError("清洗后没有可分析记录,请检查日期、类别、金额和数量。")

    # Add a month key and aggregate values for the charts.
    # 添加月份字段,并汇总生成分类图和趋势图的数据。
    clean["month"] = clean["date"].dt.to_period("M").astype(str)
    by_category = (
        clean.groupby("category", as_index=False)[["amount", "quantity"]]
        .sum()
        .sort_values("amount", ascending=False)
    )
    by_month = clean.groupby("month")["amount"].sum().sort_index()
    describe = clean["amount"].describe()
    # Convert NumPy/pandas scalars to plain Python values for JSON.
    # 将 NumPy、pandas 标量转换为普通 Python 类型以便 JSON 序列化。
    summary = {
        "source_rows": int(raw_rows),
        "rows": int(len(clean)),
        "dropped_rows": int(raw_rows - len(clean)),
        "missing_by_column": missing_before,
        "columns": [str(column) for column in frame.columns],
        "date_range": [clean["date"].min().strftime("%Y-%m-%d"), clean["date"].max().strftime("%Y-%m-%d")],
        "total_sales": round(float(clean["amount"].sum()), 2),
        "total_quantity": round(float(clean["quantity"].sum()), 2),
        "average_order_amount": round(float(clean["amount"].mean()), 2),
        "amount_describe": {key: round(float(value), 2) for key, value in describe.items()},
        "sales_by_category": [
            {"category": str(row.category), "amount": round(float(row.amount), 2), "quantity": round(float(row.quantity), 2)}
            for row in by_category.head(MAX_CATEGORIES).itertuples(index=False)
        ],
        "sales_by_month": {str(month): round(float(amount), 2) for month, amount in by_month.items()},
    }
    return clean, summary


def chart_data_uri(frame: pd.DataFrame, summary: dict) -> dict:
    """Render aggregate charts in memory as browser-ready data URIs
    在内存中生成汇总图表,并转为浏览器可用的数据 URI。
    """
    # Agg works without a desktop; uploaded rows and charts are not saved.
    # Agg 后端无需桌面环境;不会保存上传明细或图表文件。
    plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "Arial", "DejaVu Sans"]
    plt.rcParams["axes.unicode_minus"] = False
    charts = {}
    category = pd.DataFrame(summary["sales_by_category"])
    # Use labels and values from the aggregated summary only.
    # 图表标签和数值仅取自已汇总的数据。
    for key, title, color, labels, values, ylabel in (
        ("category", "Sales by Category", "#4778f5", category.get("category", []), category.get("amount", []), "Sales amount"),
        ("monthly", "Monthly Sales Trend", "#10a98a", list(summary["sales_by_month"].keys()), list(summary["sales_by_month"].values()), "Sales amount"),
    ):
        fig, ax = plt.subplots(figsize=(8, 4.2), dpi=130)
        if key == "category":
            ax.bar(labels, values, color=color, width=0.62)
            ax.tick_params(axis="x", rotation=25)
        else:
            ax.plot(labels, values, color=color, marker="o", linewidth=2.5)
            ax.tick_params(axis="x", rotation=25)
        ax.set_title(title, loc="left", fontsize=13, pad=14, color="#172033")
        ax.set_ylabel(ylabel, color="#667085")
        ax.grid(axis="y", alpha=0.2)
        ax.spines[["top", "right"]].set_visible(False)
        fig.tight_layout()
        output = io.BytesIO()
        fig.savefig(output, format="png", bbox_inches="tight", facecolor="white")
        plt.close(fig)
        encoded = base64.b64encode(output.getvalue()).decode("ascii")
        charts[key] = "data:image/png;base64," + encoded
    return charts


def anonymized_model_summary(summary: dict) -> dict:
    """Build a minimal payload and hide original category labels
    生成最小化摘要,并隐藏原始类别名称。
    """
    # Category labels may contain sensitive text; replace them before sending.
    # 类别名称可能包含敏感文本,发送前先替换为匿名标签。
    return {
        "rows_analyzed": summary["rows"],
        "rows_excluded_during_cleaning": summary["dropped_rows"],
        "date_range": summary["date_range"],
        "total_sales": summary["total_sales"],
        "total_quantity": summary["total_quantity"],
        "average_order_amount": summary["average_order_amount"],
        "amount_statistics": summary["amount_describe"],
        "sales_by_category": [
            {"category": f"类别{index + 1}", "sales": row["amount"], "quantity": row["quantity"]}
            for index, row in enumerate(summary["sales_by_category"])
        ],
        "sales_by_month": summary["sales_by_month"],
        "missing_values_by_required_field": {key: value for key, value in summary["missing_by_column"].items() if key in REQUIRED_COLUMNS},
    }


def parse_json_object(content: str) -> dict:
    """Parse model JSON, including code-fenced responses
    解析模型返回的 JSON,也兼容带代码围栏的响应。
    """
    text = content.strip()
    text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.IGNORECASE)
    result = json.loads(text)
    if not isinstance(result, dict):
        raise ValueError("模型返回的不是 JSON 对象")
    return result


def request_ai_insight(summary: dict) -> dict:
    """Call a compatible chat endpoint; local analysis works without a key
    调用兼容的对话接口;未配置密钥时本地统计仍可使用。
    """
    api_key = os.getenv("MIMO_API_KEY") or os.getenv("OPENAI_API_KEY")
    if not api_key:
        return {"available": False, "message": "尚未配置模型密钥。统计和图表已完成;配置 MIMO_API_KEY 后可生成 AI 洞察。"}

    base_url = os.getenv("MIMO_BASE_URL", "https://api.xiaomimimo.com/v1").rstrip("/")
    model = os.getenv("MIMO_MODEL", "mimo-v2.6-flash")
    # Request a stable JSON shape for the three report cards.
    # 要求模型返回固定 JSON 结构,供页面生成三类报告卡片。
    payload = {
        "model": model,
        "temperature": 0.2,
        "response_format": {"type": "json_object"},
        "messages": [
            {"role": "system", "content": "你是审慎的数据分析助理。只根据给定的聚合统计数字作答,不推断因果,不编造字段、背景或数据。请输出 JSON 对象,且必须有 facts、risks、actions 三个键,每个键对应 2 至 4 条简短中文字符串。报告用于人工参考,不构成自动业务决策。"},
            {"role": "user", "content": "请分析以下脱敏聚合摘要。facts 写可从数据直接核对的事实;risks 写数据质量或解读限制;actions 写需人工评估的低风险建议。摘要:\n" + json.dumps(anonymized_model_summary(summary), ensure_ascii=False)},
        ],
    }
    # Keep the API key in this server-side request; never expose it to the page.
    # 密钥只用于服务端请求,绝不传给网页。
    request = urllib.request.Request(
        base_url + "/chat/completions",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Authorization": "Bearer " + api_key, "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=25) as response:
            response_body = json.loads(response.read().decode("utf-8"))
        content = response_body["choices"][0]["message"]["content"]
        insight = parse_json_object(content)
        # Validate report lists and limit text length before returning.
        # 返回前校验报告字段,并限制每条文本长度。
        for key in ("facts", "risks", "actions"):
            if not isinstance(insight.get(key), list):
                raise ValueError("模型报告缺少必需字段")
            insight[key] = [str(item)[:500] for item in insight[key][:6]]
        return {"available": True, "report": insight, "model": model}
    except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, KeyError, IndexError, TypeError, ValueError, json.JSONDecodeError) as exc:
        app.logger.warning("LLM insight request failed (%s)", type(exc).__name__)
        return {"available": False, "message": "模型暂时无法生成报告,请检查服务配置后重试。统计与图表仍可使用。"}


@app.get("/")
def index():
    """Serve the upload and results page
    返回上传和分析结果页面。
    """
    return render_template("index.html")


@app.get("/sample.csv")
def sample_csv():
    """Serve the bundled sample CSV
    返回静态目录中内置的示例 CSV 文件。
    """
    return app.send_static_file("sample_sales.csv")


@app.get("/api/health")
def health():
    """Report whether a model API key is configured
    返回是否已配置大模型 API 密钥。
    """
    return jsonify({"ok": True, "llm_configured": bool(os.getenv("MIMO_API_KEY") or os.getenv("OPENAI_API_KEY"))})


@app.post("/api/analyze")
def analyze():
    """Validate and analyze one upload, then return metrics, charts, and insight
    校验并分析上传文件,返回指标、图表和 AI 洞察。
    """
    upload = request.files.get("file")
    if upload is None or not upload.filename:
        return jsonify({"message": "请选择一个 CSV 文件。"}), 400
    if "." not in upload.filename or upload.filename.rsplit(".", 1)[1].lower() != "csv":
        return jsonify({"message": "只支持 CSV 文件。"}), 400
    try:
        # Read the upload into memory without explicitly saving an original copy.
        # 在内存中读取上传文件,不主动保存原始文件副本。
        frame = read_csv_upload(upload.read())
        clean, summary = make_analysis(frame)
        charts = chart_data_uri(clean, summary)
        insight = request_ai_insight(summary)
        return jsonify({"summary": summary, "charts": charts, "insight": insight})
    except DataError as exc:
        return jsonify({"message": str(exc)}), 400
    # Log details server-side and return a safe message.
    # 详细错误只写入服务端日志,并向用户返回安全提示。
    except Exception as exc:
        app.logger.exception("Analysis failed (%s)", type(exc).__name__)
        return jsonify({"message": "分析失败,请检查 CSV 内容后重试。"}), 500


@app.errorhandler(413)
def too_large(_error):
    """Format Flask's request-size error as JSON
    将 Flask 的请求大小错误转换为页面使用的 JSON 格式。
    """
    return jsonify({"message": "文件不能超过 2 MB。"}), 413


if __name__ == "__main__":
    # Debug mode is opt-in; bind to localhost for the classroom demo.
    # 调试模式需显式开启;课堂示例默认只监听本机。
    app.run(host="127.0.0.1", port=int(os.getenv("PORT", "5006")), debug=os.getenv("FLASK_DEBUG") == "1")
03前端页面

编写页面结构与字段说明

Jinja 模板搭建上传区、字段格式指南、统计结果区域、图表容器和 AI 报告容器。字段说明在页面中默认展开,让使用者上传前就能核对 CSV 列名与数据格式。

本步文件结构

ai-data-dashboard/
└── templates/
    └── index.html  # 页面骨架、上传表单、字段要求和结果容器

操作要点

确认模板中的文件 input 名称为 file,与 Flask 的 request.files.get("file") 对应;结果区域使用 dashboard 容器,由 JavaScript 在请求成功后显示。

完整代码

展开文件名即可查看完整内容;“打开/下载源文件”可直接查看项目对应文件。

templates/index.html打开/下载源文件 ↗
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#f4f6fb">
  <title>AI 数据分析看板</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
  <main class="shell">
    <!-- Hero area introduces the demo -->
    <!-- 首屏介绍应用用途和主要技术。 -->
    <header class="hero">
      <div class="hero-copy">
        <p class="eyebrow">FLASK · PANDAS · LARGE LANGUAGE MODEL</p>
        <h1>AI 数据分析看板</h1>
        <p class="hero-text">上传一份销售 CSV,快速查看数据质量、关键统计和趋势,再让大模型根据脱敏摘要整理可核对的洞察。</p>
        <div class="hero-tags"><span>CSV 数据分析</span><span>自动生成图表</span><span>AI 结构化报告</span></div>
      </div>
      <div class="hero-mark" aria-hidden="true">✳</div>
    </header>

    <!-- Upload form: app.js sends the selected file to Flask -->
    <!-- 上传表单:app.js 将选中的文件发送给 Flask。 -->
    <section class="panel upload-panel" aria-labelledby="upload-title">
      <div class="section-heading">
        <div><p class="eyebrow dark">第一步</p><h2 id="upload-title">选择数据文件</h2></div>
        <a class="sample-link" href="{{ url_for('sample_csv') }}" download>下载演示 CSV ↗</a>
      </div>
      <form id="upload-form">
        <label class="dropzone" for="csv-file" id="dropzone">
          <span class="file-icon" aria-hidden="true">↑</span>
          <strong id="file-label">点击选择 CSV 文件</strong>
          <span id="file-help">或将文件拖放到这里 · 最大 2 MB</span>
          <input id="csv-file" name="file" type="file" accept=".csv,text/csv" required>
        </label>
        <div class="data-note"><span aria-hidden="true">ⓘ</span><span>请仅上传你有权处理的数据。原始 CSV 仅在内存中读取;模型只接收匿名类别标签和聚合统计数值。</span></div>
        <!-- Show the required schema beside the file picker -->
        <!-- 在文件选择框旁展示必需字段和数据规则。 -->
        <details class="format-guide" open>
          <summary>CSV 格式要求</summary>
          <p>当前看板用于销售数据分析,只接受包含以下四列的 CSV。列名大小写不敏感,但请勿省略字段:</p>
          <div class="table-wrap format-table-wrap"><table class="format-table">
            <thead><tr><th>必需字段</th><th>用途</th><th>示例值</th></tr></thead>
            <tbody>
              <tr><td><code>date</code></td><td>销售日期,用于按月统计</td><td><code>2025-01-05</code></td></tr>
              <tr><td><code>category</code></td><td>商品类别,用于分类汇总</td><td><code>手机</code></td></tr>
              <tr><td><code>amount</code></td><td>销售金额,须为非负数字</td><td><code>3299</code></td></tr>
              <tr><td><code>quantity</code></td><td>销售数量,须为大于 0 的数字</td><td><code>1</code></td></tr>
            </tbody>
          </table></div>
          <p class="format-example">示例表头:<code>date,category,amount,quantity</code><br>示例数据:<code>2025-01-05,手机,3299,1</code></p>
          <p class="format-limits">仅支持 CSV 文件(UTF-8、UTF-8 BOM 或 GBK 编码),大小不超过 2 MB、最多 20,000 行。缺少必需列或清洗后没有有效数据时,系统会提示修正后重试。</p>
        </details>
        <div class="form-footer"><span id="status" role="status" aria-live="polite">数据列要求:date、category、amount、quantity</span><button id="submit-btn" type="submit"><span>开始分析</span><span aria-hidden="true">→</span></button></div>
      </form>
    </section>

    <!-- app.js fills these containers after /api/analyze returns JSON -->
    <!-- 分析接口 /api/analyze 返回 JSON 后,由 app.js 填充结果区域。 -->
    <section id="dashboard" class="dashboard" hidden aria-live="polite">
      <div class="section-heading results-heading"><div><p class="eyebrow dark">分析结果</p><h2>数据概览</h2></div><span id="date-range" class="date-pill"></span></div>
      <div class="metric-grid" id="metrics"></div>
      <div class="content-grid">
        <article class="panel chart-panel"><div class="panel-title"><div><span class="panel-icon blue">▥</span><h3>类别销售额</h3></div><span class="subtle">按销售额排序</span></div><img id="category-chart" alt="各类别销售额柱状图"></article>
        <article class="panel chart-panel"><div class="panel-title"><div><span class="panel-icon green">⌁</span><h3>月度销售趋势</h3></div><span class="subtle">按月份汇总</span></div><img id="monthly-chart" alt="月度销售额趋势折线图"></article>
      </div>
      <article class="panel table-panel">
        <div class="panel-title"><div><span class="panel-icon violet">▤</span><h3>字段与数据质量</h3></div><span id="clean-note" class="subtle"></span></div>
        <div class="table-wrap"><table><thead><tr><th>字段</th><th>缺失值</th><th>说明</th></tr></thead><tbody id="quality-rows"></tbody></table></div>
        <details class="stats-details"><summary>查看金额描述统计</summary><div id="stats-grid" class="stats-grid"></div></details>
      </article>
      <!-- app.js inserts AI text safely; a person should verify it -->
      <!-- app.js 以文本方式插入 AI 内容,使用者仍需人工核对。 -->
      <article class="panel ai-panel">
        <div class="panel-title"><div><span class="panel-icon gold">✳</span><h3>AI 洞察报告</h3></div><span class="ai-badge">模型辅助 · 需人工核对</span></div>
        <div id="ai-report"></div>
      </article>
      <p class="disclaimer">AI 生成内容仅供分析参考。请对照统计表和图表核验事实;相关性不代表因果关系。</p>
    </section>
    <footer>课程演示项目 · Flask 数据分析与大模型应用</footer>
  </main>
  <script src="{{ url_for('static', filename='app.js') }}"></script>
</body>
</html>
04样式

完成看板样式与响应式布局

样式文件负责上传区域、数据质量表、指标卡、图表和报告卡片布局,并为窄屏设置单列排版。

本步文件结构

ai-data-dashboard/
└── static/
    └── style.css  # 完整页面样式及移动端布局

操作要点

页面通过 Flask 的 url_for("static", filename="style.css") 加载静态样式。若离线访问,Google Fonts 不可用时会回退到系统字体。

完整代码

展开文件名即可查看完整内容;“打开/下载源文件”可直接查看项目对应文件。

static/style.css打开/下载源文件 ↗
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;600;700&display=swap');

/* Color palette and default typography */
/* 看板的配色变量和默认字体。 */
:root {
  font-family:"DM Sans","Noto Sans SC","Microsoft YaHei",sans-serif;
  color:#1d2939;
  background:#f4f6fb;
  font-synthesis:none;
  text-rendering:optimizeLegibility;
  --muted:#7d8797;
  --line:#e8ebf2;
  --blue:#4778f5;
  --surface:#fff
}

* {
  box-sizing:border-box
}

body {
  margin:0;
  min-width:320px;
  background:radial-gradient(ellipse at 78% 0,#e8edff 0,transparent 33%),#f4f6fb
}

.shell {
  width:min(1080px,calc(100% - 36px));
  margin:auto;
  padding:38px 0 26px
}

/* Header banner and upload panel */
/* 顶部横幅和文件上传区域。 */
.hero {
  position:relative;
  overflow:hidden;
  display:flex;
  align-items:center;
  justify-content:space-between;
  min-height:240px;
  padding:40px 48px;
  color:#fff;
  border-radius:22px;
  background:linear-gradient(118deg,#1e3479,#4068d8 62%,#7189e7);
  box-shadow:0 18px 45px #2d4d9b25
}

.hero:after {
  position:absolute;
  right:6%;
  bottom:-190px;
  width:360px;
  height:360px;
  border:1px solid #ffffff30;
  border-radius:50%;
  content:"";
  box-shadow:0 0 0 42px #ffffff0b,0 0 0 84px #ffffff0b
}

.hero-copy {
  position:relative;
  z-index:1;
  max-width:690px
}

.eyebrow {
  margin:0 0 13px;
  color:#d5dfff;
  font-size:11px;
  font-weight:700;
  letter-spacing:.14em
}

.eyebrow.dark {
  margin-bottom:6px;
  color:#8692a7
}

.hero h1 {
  margin:0;
  font-size:clamp(30px,4vw,43px);
  letter-spacing:-.04em
}

.hero-text {
  max-width:650px;
  margin:14px 0 21px;
  color:#edf1ff;
  font-size:15px;
  line-height:1.8
}

.hero-tags {
  display:flex;
  flex-wrap:wrap;
  gap:8px
}

.hero-tags span {
  padding:6px 11px;
  border:1px solid #ffffff45;
  border-radius:999px;
  color:#f2f5ff;
  font-size:11px
}

.hero-mark {
  position:relative;
  z-index:1;
  margin-right:28px;
  color:#ffffffb5;
  font-size:92px
}

.panel {
  border:1px solid #e9ecf3;
  border-radius:17px;
  background:var(--surface);
  box-shadow:0 7px 25px #1e2b4708
}

/* File picker, privacy note, and CSV format guide */
/* 文件选择、隐私提示和 CSV 格式说明。 */
.upload-panel {
  margin-top:22px;
  padding:27px 30px
}

.section-heading,.panel-title,.panel-title>div {
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px
}

.section-heading h2 {
  margin:0;
  font-size:21px;
  letter-spacing:-.03em
}

.sample-link {
  color:#4265c5;
  font-size:13px;
  text-decoration:none
}

.sample-link:hover {
  text-decoration:underline
}

.dropzone {
  position:relative;
  display:flex;
  min-height:145px;
  margin-top:20px;
  align-items:center;
  justify-content:center;
  flex-direction:column;
  gap:7px;
  border:1.5px dashed #cdd5e6;
  border-radius:13px;
  background:#fafbfe;
  cursor:pointer;
  transition:.18s
}

.dropzone:hover,.dropzone.dragging {
  border-color:#6788ec;
  background:#f5f7ff
}

.dropzone strong {
  font-size:15px
}

.dropzone>span:last-of-type {
  color:#929bad;
  font-size:12px
}

.dropzone input {
  position:absolute;
  inset:0;
  width:100%;
  height:100%;
  opacity:0;
  cursor:pointer
}

.file-icon {
  display:grid;
  width:34px;
  height:34px;
  place-items:center;
  border-radius:10px;
  background:#eaf0ff;
  color:#4c6ed1;
  font-size:21px
}

.data-note {
  display:flex;
  gap:9px;
  margin-top:14px;
  color:#7d6b39;
  font-size:12px;
  line-height:1.7
}

.data-note>span:first-child {
  color:#bd9531
}

.form-footer {
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:16px;
  margin-top:19px
}

#status {
  color:#7a8495;
  font-size:12px
}

#status.error {
  color:#c34444
}

#status.loading {
  color:#4265c5
}

button {
  display:flex;
  align-items:center;
  gap:19px;
  padding:11px 17px;
  border:0;
  border-radius:9px;
  background:#4169db;
  color:white;
  font:600 13px inherit;
  font-family:inherit;
  cursor:pointer;
  box-shadow:0 5px 12px #4169db29
}

button:hover {
  background:#345bc9
}

button:disabled {
  opacity:.62;
  cursor:wait
}

/* Results area: metrics, charts, and data quality */
/* 分析结果区域:指标卡、图表和数据质量信息。 */
.dashboard {
  margin-top:31px
}

.results-heading {
  margin:0 2px 16px
}

.date-pill {
  padding:7px 11px;
  border:1px solid #e2e7f1;
  border-radius:999px;
  background:#fff;
  color:#69758a;
  font-size:11px
}

/* Four summary cards on desktop */
/* 桌面布局中的四张汇总指标卡片。 */
.metric-grid {
  display:grid;
  grid-template-columns:repeat(4,1fr);
  gap:13px
}

.metric {
  padding:17px 18px;
  border:1px solid #e9ecf3;
  border-radius:14px;
  background:#fff;
  box-shadow:0 5px 18px #1e2b4706
}

.metric-label {
  color:#818b9d;
  font-size:11px
}

.metric-value {
  margin-top:9px;
  color:#212d43;
  font-size:23px;
  font-weight:700;
  letter-spacing:-.04em
}

.metric-foot {
  margin-top:4px;
  color:#9aa3b1;
  font-size:10px
}

/* Two chart cards sit side by side on wide screens */
/* 宽屏下两张图表卡片并排显示。 */
.content-grid {
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:14px;
  margin-top:14px
}

.chart-panel,.table-panel,.ai-panel {
  padding:19px 21px
}

/* Three-column AI report with a single-column mobile fallback */
/* AI 报告桌面端三列、窄屏时单列显示。 */
.ai-panel {
  margin-top:14px
}

.panel-title {
  margin-bottom:14px
}

.panel-title>div {
  justify-content:flex-start
}

.panel-title h3 {
  margin:0;
  font-size:14px
}

.panel-icon {
  display:grid;
  width:29px;
  height:29px;
  place-items:center;
  border-radius:9px;
  font-size:17px
}

.panel-icon.blue {
  background:#edf2ff;
  color:#4e6fd1
}

.panel-icon.green {
  background:#e8f7f1;
  color:#199b78
}

.panel-icon.violet {
  background:#f3edff;
  color:#8d66c7
}

.panel-icon.gold {
  background:#fff5df;
  color:#bd8d24
}

.subtle {
  color:#96a0ae;
  font-size:10px
}

.chart-panel img {
  display:block;
  width:100%;
  height:auto;
  min-height:220px;
  object-fit:contain
}

/* Data quality table and expandable descriptive statistics */
/* 数据质量表和可展开的描述统计。 */
.table-panel {
  margin-top:14px
}

.table-wrap {
  overflow:auto
}

table {
  width:100%;
  border-collapse:collapse;
  text-align:left
}

th,td {
  padding:10px 12px;
  border-bottom:1px solid #edf0f5;
  font-size:12px
}

th {
  background:#fafbfc;
  color:#788397;
  font-size:10px;
  font-weight:600
}

td {
  color:#485467
}

.stats-details {
  margin-top:14px;
  color:#536179;
  font-size:12px
}

.stats-details summary {
  width:max-content;
  cursor:pointer
}

.stats-grid {
  display:grid;
  grid-template-columns:repeat(4,1fr);
  gap:8px;
  margin-top:12px
}

.stat {
  padding:9px;
  border-radius:8px;
  background:#f7f8fb
}

.stat span {
  display:block;
  color:#8a94a4;
  font-size:10px
}

.stat strong {
  display:block;
  margin-top:4px;
  font-size:12px
}

.ai-panel {
  margin-top:14px
}

.ai-badge {
  padding:5px 9px;
  border-radius:999px;
  background:#fff7e7;
  color:#9a762a;
  font-size:10px
}

.report-grid {
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:11px
}

.report-section {
  padding:13px 14px;
  border:1px solid #edf0f5;
  border-radius:11px;
  background:#fcfcfe
}

.report-section h4 {
  margin:0 0 9px;
  color:#344054;
  font-size:12px
}

.report-section ul {
  display:grid;
  gap:8px;
  margin:0;
  padding-left:16px;
  color:#657084;
  font-size:11px;
  line-height:1.65
}

.ai-empty {
  padding:17px;
  border-radius:10px;
  background:#f8f9fc;
  color:#707b8c;
  font-size:12px;
  line-height:1.8
}

.disclaimer {
  margin:12px 5px 0;
  color:#919baa;
  font-size:11px
}

footer {
  padding:26px 0 0;
  color:#a1a9b5;
  text-align:center;
  font-size:10px
}

[hidden] {
  display:none!important
}

/* Tablet and phone layout adjustments */
/* 平板和手机屏幕的布局调整。 */
@media(max-width:760px) {
  .shell {
    width:min(100% - 24px,620px);
    padding-top:16px
  }

.hero {
    min-height:220px;
    padding:29px 24px
  }

.hero-mark {
    margin-right:0;
    font-size:64px
  }

.upload-panel {
    padding:21px 18px
  }

.metric-grid {
    grid-template-columns:repeat(2,1fr)
  }

.content-grid {
    grid-template-columns:1fr
  }

.chart-panel img {
    min-height:180px
  }

.report-grid {
    grid-template-columns:1fr
  }

.form-footer {
    align-items:flex-start;
    flex-direction:column
  }

.form-footer button {
    align-self:flex-end
  }

.stats-grid {
    grid-template-columns:repeat(2,1fr)
  }


}

@media(max-width:440px) {
  .hero-mark {
    display:none
  }

.section-heading h2 {
    font-size:19px
  }

.date-pill {
    font-size:10px
  }

.metric {
    padding:14px
  }

.metric-value {
    font-size:20px
  }

.panel-title {
    align-items:flex-start
  }

.subtle {
    max-width:90px;
    text-align:right
  }


}


/* The field table documents the schema expected by app.py */
/* 字段表说明 app.py 所需的数据结构。 */
.format-guide {
  margin-top:16px;
  padding:14px 16px;
  border:1px solid #e7ebf3;
  border-radius:11px;
  background:#fafbfe;
  color:#536179;
  font-size:12px;
  line-height:1.75
}

.format-guide summary {
  color:#344765;
  font-weight:700;
  cursor:pointer
}

.format-guide>p {
  margin:9px 0
}

.format-table-wrap {
  margin:8px 0
}

.format-table th,.format-table td {
  padding:8px 10px;
  font-size:11px
}

.format-table td:first-child {
  color:#3559b7;
  font-weight:700
}

.format-table code,.format-example code {
  padding:2px 5px;
  border-radius:4px;
  background:#edf1fa;
  color:#344765;
  font-family:Consolas,monospace
}

.format-example {
  color:#55647c
}

.format-limits {
  margin-bottom:0!important;
  color:#7d8797;
  font-size:11px
}
05前端交互

实现上传交互与安全渲染

JavaScript 负责拖放选文件、显示文件名、校验前端限制、用 fetch 发送 multipart/form-data,并把统计结果安全地渲染到页面。模型返回的文字通过 textContent 写入,避免作为 HTML 执行。

本步文件结构

ai-data-dashboard/
└── static/
    └── app.js  # 文件选择、上传、状态提示和结果渲染

操作要点

观察 renderMetrics、renderQuality 和 renderInsight 如何创建 DOM 节点。前端校验用于及时提示,服务端仍会独立校验文件类型和大小。

完整代码

展开文件名即可查看完整内容;“打开/下载源文件”可直接查看项目对应文件。

static/app.js打开/下载源文件 ↗
// Cache elements for file selection, status, and upload.
// 缓存文件选择、状态提示和上传流程会用到的页面元素。
const form = document.querySelector("#upload-form");
const input = document.querySelector("#csv-file");
const dropzone = document.querySelector("#dropzone");
const fileLabel = document.querySelector("#file-label");
const fileHelp = document.querySelector("#file-help");
const statusBox = document.querySelector("#status");
const submitButton = document.querySelector("#submit-btn");

// Format metric and table numbers consistently in Chinese.
// 统一指标卡片和表格中的中文数字格式。
const number = (value) => new Intl.NumberFormat("zh-CN", { maximumFractionDigits: 2 }).format(value ?? 0);

// Write messages as text, never as HTML.
// 状态内容始终作为纯文本写入,不按 HTML 解析。
const status = (message, kind = "") => {
  statusBox.textContent = message;
  statusBox.className = kind;
};

// Show filename and size before analysis starts.
// 开始分析前显示所选文件名和大小。
input.addEventListener("change", () => {
  const file = input.files[0];
  fileLabel.textContent = file ? file.name : "点击选择 CSV 文件";
  fileHelp.textContent = file ? `${(file.size / 1024).toFixed(1)} KB · 点击可重新选择` : "或将文件拖放到这里 · 最大 2 MB";
});

// Highlight the drop target while a CSV is dragged over it.
// CSV 文件拖到上传区域上方时显示视觉提示。
for (const eventName of ["dragenter", "dragover"]) {
  dropzone.addEventListener(eventName, (event) => { event.preventDefault(); dropzone.classList.add("dragging"); });
}
for (const eventName of ["dragleave", "drop"]) {
  dropzone.addEventListener(eventName, (event) => { event.preventDefault(); dropzone.classList.remove("dragging"); });
}
// Pass dropped files through the regular file input.
// 将拖放文件交给常规文件输入框,复用同一上传流程。
dropzone.addEventListener("drop", (event) => {
  const file = event.dataTransfer.files[0];
  if (!file) return;
  const transfer = new DataTransfer();
  transfer.items.add(file);
  input.files = transfer.files;
  input.dispatchEvent(new Event("change"));
});

// Render the four headline metrics returned by Flask.
// 渲染 Flask 返回的四项核心指标。
function renderMetrics(summary) {
  const metrics = [
    ["清洗后记录", number(summary.rows), `原始 ${number(summary.source_rows)} 行`],
    ["销售总额", `¥${number(summary.total_sales)}`, "基于有效记录汇总"],
    ["平均单笔金额", `¥${number(summary.average_order_amount)}`, "金额字段的算术平均"],
    ["销售数量", number(summary.total_quantity), "数量字段汇总"],
  ];
  document.querySelector("#metrics").replaceChildren(...metrics.map(([label, value, foot]) => {
    const card = document.createElement("div");
    card.className = "metric";
    const title = document.createElement("div"); title.className = "metric-label"; title.textContent = label;
    const main = document.createElement("div"); main.className = "metric-value"; main.textContent = value;
    const note = document.createElement("div"); note.className = "metric-foot"; note.textContent = foot;
    card.append(title, main, note); return card;
  }));
}

// Show missing counts and amount.describe() from the response.
// 展示后端返回的缺失值数量和金额描述统计。
function renderQuality(summary) {
  const descriptions = { date: "日期维度", category: "分组维度", amount: "金额指标", quantity: "数量指标" };
  const rows = Object.entries(summary.missing_by_column).map(([field, count]) => {
    const tr = document.createElement("tr");
    for (const value of [field, number(count), descriptions[field] || "其他字段"]) {
      const td = document.createElement("td"); td.textContent = value; tr.append(td);
    }
    return tr;
  });
  document.querySelector("#quality-rows").replaceChildren(...rows);
  document.querySelector("#clean-note").textContent = `清洗排除 ${number(summary.dropped_rows)} 行`;
  const labels = { count: "记录数", mean: "平均值", std: "标准差", min: "最小值", "25%": "第 25 百分位", "50%": "中位数", "75%": "第 75 百分位", max: "最大值" };
  document.querySelector("#stats-grid").replaceChildren(...Object.entries(summary.amount_describe).map(([key, value]) => {
    const item = document.createElement("div"); item.className = "stat";
    const label = document.createElement("span"); label.textContent = labels[key] || key;
    const val = document.createElement("strong"); val.textContent = number(value);
    item.append(label, val); return item;
  }));
}

// Build the report from text nodes to prevent HTML injection.
// 用文本节点构建报告,避免将模型内容作为 HTML 执行。
function renderInsight(insight) {
  const host = document.querySelector("#ai-report");
  host.replaceChildren();
  if (!insight.available) {
    const message = document.createElement("div"); message.className = "ai-empty"; message.textContent = insight.message;
    host.append(message); return;
  }
  const labels = { facts: "数据事实", risks: "风险与限制", actions: "建议关注" };
  const grid = document.createElement("div"); grid.className = "report-grid";
  for (const key of ["facts", "risks", "actions"]) {
    const section = document.createElement("section"); section.className = "report-section";
    const title = document.createElement("h4"); title.textContent = labels[key];
    const list = document.createElement("ul");
    for (const item of insight.report[key] || []) { const li = document.createElement("li"); li.textContent = item; list.append(li); }
    section.append(title, list); grid.append(section);
  }
  host.append(grid);
}

// Upload the CSV, then render metrics, charts, quality, and AI insight.
// 上传 CSV 后渲染指标、图表、数据质量和 AI 洞察。
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const file = input.files[0];
  if (!file) { status("请先选择 CSV 文件。", "error"); return; }
  if (!file.name.toLowerCase().endsWith(".csv")) { status("只支持 CSV 文件。", "error"); return; }
  if (file.size > 2 * 1024 * 1024) { status("文件不能超过 2 MB。", "error"); return; }
  submitButton.disabled = true;
  status("正在校验数据、生成图表并请求 AI 洞察…", "loading");
  const body = new FormData(form);
  try {
    const response = await fetch("/api/analyze", { method: "POST", body });
    const result = await response.json();
    if (!response.ok) throw new Error(result.message || "分析失败,请重试。");
    renderMetrics(result.summary);
    renderQuality(result.summary);
    document.querySelector("#date-range").textContent = `${result.summary.date_range[0]} — ${result.summary.date_range[1]}`;
    document.querySelector("#category-chart").src = result.charts.category;
    document.querySelector("#monthly-chart").src = result.charts.monthly;
    renderInsight(result.insight);
    document.querySelector("#dashboard").hidden = false;
    status(result.insight.available ? "分析完成,请结合数据图表核对报告。" : "统计与图表已完成;AI 报告暂不可用。", result.insight.available ? "" : "error");
  } catch (error) {
    status(error.message || "网络请求失败,请检查服务后重试。", "error");
  } finally {
    submitButton.disabled = false;
  }
});
06运行验收

准备数据、启动并完成验收

项目内含一份小型演示数据和两份公开合成销售数据,均已整理为应用需要的列结构。配置模型密钥后可生成 AI 报告;不配置密钥也能查看统计与图表。

本步文件结构

ai-data-dashboard/
├── README.md             # 安装、格式、隐私边界与运行说明
├── .env.example          # 模型服务环境变量模板
└── static/
    ├── sample_sales.csv  # 页面“下载演示 CSV”使用的数据
    ├── sales_public_100.csv
    └── sales_public_240.csv

操作要点

启动后分别上传 sample_sales.csv、sales_public_100.csv 和 sales_public_240.csv。再检查缺列文件、非 CSV 文件和超过 2 MB 文件的提示。验收时确认图表、数据质量、描述统计都出现,并核对 AI 报告是否提示需要人工复核。

完整代码

展开文件名即可查看完整内容;“打开/下载源文件”可直接查看项目对应文件。

static/sample_sales.csv打开/下载源文件 ↗
date,category,amount,quantity
2025-01-05,手机,3299,1
2025-01-12,配件,299,3
2025-01-18,平板,2499,1
2025-02-03,手机,4299,1
2025-02-10,配件,599,4
2025-02-21,智能家居,899,2
2025-03-02,平板,2799,1
2025-03-08,手机,3599,1
2025-03-14,配件,399,3
2025-03-27,智能家居,1299,3
2025-04-04,手机,4599,1
2025-04-11,平板,3199,1
2025-04-19,配件,799,5
2025-04-26,智能家居,699,2
2025-05-06,手机,3899,1
2025-05-13,平板,2999,1
2025-05-20,配件,499,4
2025-05-29,智能家居,1599,3
2025-06-03,手机,4999,1
2025-06-09,配件,899,6
2025-06-17,平板,3499,1
2025-06-25,智能家居,1099,2
README.md打开/下载源文件 ↗
# AI 数据分析看板

一个课堂演示用的 Flask 项目:上传销售 CSV,使用 pandas 清洗并汇总数据,生成类别销售额和月度趋势图,再把脱敏后的聚合摘要发送给大语言模型生成结构化洞察。

## 功能

- 校验 CSV 类型、文件大小、编码、数据列和记录数。
- 清洗日期、金额、数量和类别字段,显示缺失值和排除行数。
- 展示销售统计、类别柱状图、月度趋势图和描述统计。
- 通过 MiMo 的 OpenAI 兼容接口生成 `facts`、`risks`、`actions` 三部分报告。
- 原始 CSV 只在内存中读取,不保存到公开目录;发送给模型前将类别名称替换为匿名标签。
- 未配置密钥时仍可查看统计与图表,并提示如何启用 AI 报告。

## 环境与运行

建议使用 Python 3.10 或更高版本。

```powershell
cd static/course/python_web_ai/section-6/ai-data-dashboard
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
Copy-Item .env.example .env
```

在 `.env` 中设置自己的 MiMo API 密钥:

```dotenv
MIMO_API_KEY=你的密钥
MIMO_BASE_URL=https://api.xiaomimimo.com/v1
MIMO_MODEL=mimo-v2.6-flash
```

启动服务:

```powershell
python app.py
```

浏览器访问 <http://127.0.0.1:5006>。点击“下载演示 CSV”可获取符合格式的数据样例。没有设置 API 密钥时,上传和本地统计仍可运行,AI 报告会显示未配置提示。

项目目录另附两份用于上传练习的公开合成数据:

- `sales_public_100.csv`:100 条订单,来自 [Sawan 的 sales.csv](https://github.com/sawanch/build-challenge-java-intuit)。
- `sales_public_240.csv`:240 条订单,来自 [HowToCSV Sample Sales](https://howtocsv.com/sample-sales-csv/);将商品名映射为 `category`。

两份文件均已整理为本应用所需列名,不含来源文件中其他字段。

## CSV 格式

必须包含以下列名(大小写不敏感):

| 列名 | 含义 | 示例 |
| --- | --- | --- |
| `date` | 日期 | `2025-01-05` |
| `category` | 商品类别 | `手机` |
| `amount` | 金额 | `3299` |
| `quantity` | 数量,必须大于 0 | `1` |

支持 UTF-8、UTF-8 BOM 和 GBK 编码;文件不能超过 2 MB,最多分析 20,000 行。金额不能为负数。无法转换日期或数值、字段缺失、金额为负和数量非正的记录会被排除。

## 模型数据边界

模型收到的是行数、日期范围、金额描述统计、月度聚合和匿名类别汇总,不会收到 CSV 原始记录、文件名或用户提供的类别原文。模型服务仍由外部平台处理,因此只应上传已获授权且适合处理的数据。报告可能不准确,需人工结合统计表和图表核验。

## 项目结构

```text
ai-data-dashboard/
├── app.py
├── .env.example
├── requirements.txt
├── README.md
├── templates/
│   └── index.html
└── static/
    ├── app.js
    ├── style.css
    └── sample_sales.csv
```

启动与验收

安装依赖

cd D:\wwwroot\teacher_gao\static\course\python_web_ai\section-6\ai-data-dashboard
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
pip install -r requirements.txt

配置与启动

Copy-Item .env.example .env
# 编辑 .env,填写自己的 MIMO_API_KEY;不填也能测试本地统计和图表
python app.py

浏览器打开 http://127.0.0.1:5006。如需 AI 报告,在本机 .env 设置 MIMO_API_KEY,必要时调整 MIMO_BASE_URL 与 MIMO_MODEL,然后重启 Flask。

验收清单

  • 样例 CSV 上传后显示有效记录数、销售金额、数量、描述统计和日期范围。
  • 显示类别销售额柱状图和月度趋势折线图。
  • 缺少必需列、数据清洗后为空、上传非 CSV 或文件超过 2 MB 时,页面显示可读错误。
  • 无 API 密钥时本地统计照常完成,AI 区域提示模型尚未配置。
  • 有 API 密钥时报告包含 facts、risks、actions;逐条对照统计表和图表,不把模型输出直接当成业务结论。
  • 检查发给模型的摘要不包含原始行、文件名及 CSV 中的类别原文。

评分建议(100 分):目录与依赖 10 分;CSV 服务端校验和异常提示 20 分;清洗与统计 20 分;两类图表 15 分;模型调用和结构化报告 20 分;数据最小化与人工核验意识 15 分。