Trae Assistant commited on
Commit
cefc0f7
·
0 Parent(s):

Deploy: Dynamic Pricing Lab with Batch Analysis

Browse files
Files changed (7) hide show
  1. .gitignore +5 -0
  2. Dockerfile +16 -0
  3. README.md +67 -0
  4. app.py +255 -0
  5. requirements.txt +6 -0
  6. templates/index.html +466 -0
  7. test_data.csv +3 -0
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .DS_Store
5
+ .env
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY . .
9
+
10
+ # Create a user to avoid running as root (good practice for HF Spaces)
11
+ RUN useradd -m -u 1000 user
12
+ USER user
13
+ ENV HOME=/home/user \
14
+ PATH=/home/user/.local/bin:$PATH
15
+
16
+ CMD ["gunicorn", "-b", "0.0.0.0:7860", "app:app"]
README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: 智能动态定价实验室
3
+ emoji: 📈
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ short_description: 基于价格弹性模型的AI利润优化引擎
9
+ ---
10
+
11
+ # 智能动态定价实验室 (Dynamic Pricing Lab)
12
+
13
+ ![License](https://img.shields.io/badge/license-MIT-blue.svg)
14
+ ![Python](https://img.shields.io/badge/python-3.11-green.svg)
15
+ ![Vue](https://img.shields.io/badge/vue-3.0-green.svg)
16
+
17
+ ## 项目简介
18
+
19
+ **智能动态定价实验室** 是一个专业的商业定价模拟工具,旨在帮助电商卖家和零售商通过算法寻找利润最大化的最优价格点。
20
+
21
+ 本项目不仅仅是一个简单的计算器,它基于微观经济学中的**价格弹性模型 (Price Elasticity of Demand)**,通过模拟不同价格下的市场需求变化,实时计算由于销量波动带来的边际利润变化。
22
+
23
+ ### 核心功能
24
+
25
+ * **双模型支持**:
26
+ * **线性模型 (Linear Model)**: 适用于普通商品,$D = a - bP$
27
+ * **指数模型 (Constant Elasticity)**: 适用于高敏感度或必需品,$D = A \cdot P^\epsilon$
28
+ * **实时可视化**:使用 ECharts 绘制 "价格-利润" 曲线和 "价格-需求" 曲线,直观展示价格变动对经营结果的影响。
29
+ * **智能优化**:基于 `scipy.optimize` 算法,自动寻找理论上的最大利润价格点。
30
+ * **敏感度分析**:通过滑块实时调整市场弹性系数,模拟不同市场环境(如促销季、淡季)下的定价策略。
31
+
32
+ ## 技术栈
33
+
34
+ * **Backend**: Flask (Python 3.11), NumPy, SciPy
35
+ * **Frontend**: Vue 3, Tailwind CSS (Dark Mode), ECharts
36
+ * **Deployment**: Docker (Compatible with Hugging Face Spaces)
37
+
38
+ ## 快速开始
39
+
40
+ ### Docker 部署 (推荐)
41
+
42
+ ```bash
43
+ # 构建镜像
44
+ docker build -t dynamic-pricing-lab .
45
+
46
+ # 运行容器
47
+ docker run -p 7860:7860 dynamic-pricing-lab
48
+ ```
49
+
50
+ 访问 `http://localhost:7860` 即可使用。
51
+
52
+ ### 本地开发
53
+
54
+ ```bash
55
+ pip install -r requirements.txt
56
+ python app.py
57
+ ```
58
+
59
+ ## 商业应用场景
60
+
61
+ 1. **新品定价**:通过测试少量流量估算弹性,反推最优上市价格。
62
+ 2. **促销策略**:计算打折带来的销量提升是否足以覆盖毛利损失。
63
+ 3. **库存清理**:寻找在清空库存目标下的最高收益价格。
64
+
65
+ ## License
66
+
67
+ MIT License
app.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import numpy as np
4
+ import pandas as pd
5
+ from scipy.optimize import minimize_scalar
6
+ from flask import Flask, render_template, send_from_directory, request, jsonify
7
+ from werkzeug.utils import secure_filename
8
+
9
+ # 配置日志
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
+
13
+ app = Flask(__name__)
14
+ app.config['JSON_AS_ASCII'] = False # 支持中文 JSON
15
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 限制上传文件大小为 16MB
16
+ app.config['UPLOAD_FOLDER'] = 'uploads'
17
+
18
+ # 确保上传目录存在
19
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
20
+
21
+ @app.route('/')
22
+ def index():
23
+ # 使用 render_template 渲染模板,前端需注意 Vue 分隔符冲突问题
24
+ return render_template('index.html')
25
+
26
+ @app.route('/static/<path:path>')
27
+ def send_static(path):
28
+ return send_from_directory('static', path)
29
+
30
+ def calculate_demand_linear(price, base_price, base_demand, elasticity):
31
+ """
32
+ 线性需求模型: D = a - bP
33
+ 在基准点 (base_price, base_demand) 处的弹性为 elasticity
34
+ """
35
+ # 弹性定义: E = (dD/dP) * (P/D)
36
+ # 线性: dD/dP = -b
37
+ # E = -b * (base_price / base_demand)
38
+ # -> b = -E * (base_demand / base_price)
39
+ # -> a = base_demand + b * base_price
40
+
41
+ # 确保弹性为负值 (输入如果是正数则取反)
42
+ e = -abs(elasticity)
43
+
44
+ b = -e * (base_demand / base_price)
45
+ a = base_demand + b * base_price
46
+
47
+ demand = a - b * price
48
+ return np.maximum(demand, 0) # 需求不能为负
49
+
50
+ def calculate_demand_constant_elasticity(price, base_price, base_demand, elasticity):
51
+ """
52
+ 恒定弹性模型 (指数模型): D = A * P^e
53
+ """
54
+ # base_demand = A * base_price^e
55
+ # -> A = base_demand / (base_price^e)
56
+
57
+ e = -abs(elasticity)
58
+ A = base_demand / (base_price ** e)
59
+
60
+ demand = A * (price ** e)
61
+ return demand
62
+
63
+ def run_optimization(cost, base_price, base_demand, elasticity, model_type='linear'):
64
+ """
65
+ 运行价格优化算法
66
+ """
67
+ # 模拟范围 (0.5x 成本 到 3x 成本,或者基准价格的 2 倍)
68
+ min_p = max(cost * 0.8, 0.01)
69
+ max_p = max(base_price * 2.0, cost * 3.0)
70
+
71
+ prices = np.linspace(min_p, max_p, 100)
72
+
73
+ results = []
74
+ max_profit = -float('inf')
75
+ optimal_price = base_price
76
+
77
+ # 第一次粗略扫描
78
+ for p in prices:
79
+ if model_type == 'constant':
80
+ d = calculate_demand_constant_elasticity(p, base_price, base_demand, elasticity)
81
+ else:
82
+ d = calculate_demand_linear(p, base_price, base_demand, elasticity)
83
+
84
+ revenue = p * d
85
+ profit = (p - cost) * d
86
+
87
+ if profit > max_profit:
88
+ max_profit = profit
89
+ optimal_price = p
90
+
91
+ results.append({
92
+ 'price': round(p, 2),
93
+ 'demand': round(d, 2),
94
+ 'revenue': round(revenue, 2),
95
+ 'profit': round(profit, 2)
96
+ })
97
+
98
+ # 第二次精细优化 (SciPy minimize_scalar)
99
+ # 确定搜索上界
100
+ zero_demand_price = max_p
101
+ if model_type == 'linear':
102
+ # a - bP = 0 -> P = a/b
103
+ e_val = -abs(elasticity)
104
+ b_val = -e_val * (base_demand / base_price)
105
+ if b_val != 0:
106
+ a_val = base_demand + b_val * base_price
107
+ zero_demand_price = a_val / b_val
108
+
109
+ upper_bound = min(max_p * 1.5, zero_demand_price * 1.1 if model_type == 'linear' else max_p * 1.5)
110
+
111
+ def profit_func(p):
112
+ if p <= 0: return 1e9 # 惩罚项
113
+ if model_type == 'constant':
114
+ d = calculate_demand_constant_elasticity(p, base_price, base_demand, elasticity)
115
+ else:
116
+ d = calculate_demand_linear(p, base_price, base_demand, elasticity)
117
+
118
+ # 目标是最大化利润,即最小化 -利润
119
+ prof = (p - cost) * d
120
+ return -prof
121
+
122
+ res = minimize_scalar(profit_func, bounds=(cost, upper_bound), method='bounded')
123
+
124
+ refined_optimal_price = optimal_price
125
+ refined_max_profit = max_profit
126
+
127
+ if res.success:
128
+ opt_p = res.x
129
+ opt_prof = -res.fun
130
+ # 只有当结果更好时才采纳 (避免局部极小值)
131
+ if opt_prof >= max_profit:
132
+ refined_optimal_price = opt_p
133
+ refined_max_profit = opt_prof
134
+
135
+ # 计算最优价格下的最终需求
136
+ if model_type == 'constant':
137
+ opt_d = calculate_demand_constant_elasticity(refined_optimal_price, base_price, base_demand, elasticity)
138
+ else:
139
+ opt_d = calculate_demand_linear(refined_optimal_price, base_price, base_demand, elasticity)
140
+
141
+ return {
142
+ 'results': results,
143
+ 'optimal': {
144
+ 'price': round(refined_optimal_price, 2),
145
+ 'profit': round(refined_max_profit, 2),
146
+ 'demand': round(opt_d, 2),
147
+ 'margin': round(((refined_optimal_price - cost) / refined_optimal_price) * 100, 2) if refined_optimal_price > 0 else 0
148
+ }
149
+ }
150
+
151
+ @app.route('/api/analyze', methods=['POST'])
152
+ def analyze():
153
+ try:
154
+ data = request.json
155
+ if not data:
156
+ return jsonify({'success': False, 'error': 'No data provided'}), 400
157
+
158
+ # 获取参数,提供默认值
159
+ cost = float(data.get('cost', 10.0))
160
+ base_price = float(data.get('base_price', 20.0))
161
+ base_demand = float(data.get('base_demand', 100.0))
162
+ elasticity = float(data.get('elasticity', -1.5))
163
+ model_type = data.get('model_type', 'linear')
164
+
165
+ result = run_optimization(cost, base_price, base_demand, elasticity, model_type)
166
+
167
+ return jsonify({
168
+ 'success': True,
169
+ 'data': result['results'],
170
+ 'optimal': result['optimal']
171
+ })
172
+
173
+ except Exception as e:
174
+ logger.error(f"Analysis Error: {str(e)}")
175
+ return jsonify({'success': False, 'error': str(e)}), 500
176
+
177
+ @app.route('/api/upload', methods=['POST'])
178
+ def upload_file():
179
+ """
180
+ 处理 CSV/Excel 文件上传并批量分析
181
+ """
182
+ try:
183
+ if 'file' not in request.files:
184
+ return jsonify({'success': False, 'error': 'No file part'}), 400
185
+
186
+ file = request.files['file']
187
+ if file.filename == '':
188
+ return jsonify({'success': False, 'error': 'No selected file'}), 400
189
+
190
+ if file:
191
+ filename = secure_filename(file.filename)
192
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
193
+ file.save(filepath)
194
+
195
+ # 读取文件
196
+ try:
197
+ if filename.endswith('.csv'):
198
+ df = pd.read_csv(filepath)
199
+ elif filename.endswith(('.xls', '.xlsx')):
200
+ df = pd.read_excel(filepath)
201
+ else:
202
+ return jsonify({'success': False, 'error': 'Unsupported file format'}), 400
203
+ except Exception as e:
204
+ return jsonify({'success': False, 'error': f'File read error: {str(e)}'}), 400
205
+
206
+ # 检查必需列
207
+ required_cols = ['cost', 'base_price', 'base_demand']
208
+ missing_cols = [col for col in required_cols if col not in df.columns]
209
+ if missing_cols:
210
+ return jsonify({'success': False, 'error': f'Missing columns: {", ".join(missing_cols)}'}), 400
211
+
212
+ # 批量处理
213
+ results = []
214
+ for _, row in df.iterrows():
215
+ try:
216
+ cost = float(row['cost'])
217
+ base_price = float(row['base_price'])
218
+ base_demand = float(row['base_demand'])
219
+ elasticity = float(row.get('elasticity', -1.5))
220
+ model_type = str(row.get('model_type', 'linear'))
221
+
222
+ opt_res = run_optimization(cost, base_price, base_demand, elasticity, model_type)
223
+
224
+ item_res = {
225
+ 'input': {
226
+ 'cost': cost,
227
+ 'base_price': base_price,
228
+ 'base_demand': base_demand,
229
+ 'elasticity': elasticity
230
+ },
231
+ 'optimal': opt_res['optimal']
232
+ }
233
+ results.append(item_res)
234
+ except Exception as row_err:
235
+ logger.warning(f"Row processing error: {row_err}")
236
+ continue
237
+
238
+ # 清理文件
239
+ try:
240
+ os.remove(filepath)
241
+ except:
242
+ pass
243
+
244
+ return jsonify({
245
+ 'success': True,
246
+ 'batch_results': results[:50] # 限制返回数量防止过大
247
+ })
248
+
249
+ except Exception as e:
250
+ logger.error(f"Upload Error: {str(e)}")
251
+ return jsonify({'success': False, 'error': str(e)}), 500
252
+
253
+ if __name__ == '__main__':
254
+ port = int(os.environ.get('PORT', 7860))
255
+ app.run(host='0.0.0.0', port=port)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ flask
2
+ numpy>=1.24.0
3
+ scipy>=1.10.0
4
+ gunicorn
5
+ pandas>=2.0.0
6
+ openpyxl>=3.1.0
templates/index.html ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN" class="dark">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>智能动态定价实验室 | Dynamic Pricing Lab</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
9
+ <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
10
+ <script>
11
+ tailwind.config = {
12
+ darkMode: 'class',
13
+ theme: {
14
+ extend: {
15
+ colors: {
16
+ primary: '#3B82F6',
17
+ secondary: '#10B981',
18
+ dark: '#0f172a',
19
+ surface: '#1e293b'
20
+ }
21
+ }
22
+ }
23
+ }
24
+ </script>
25
+ <style>
26
+ body { background-color: #0f172a; color: #e2e8f0; font-family: 'Inter', sans-serif; }
27
+ .glass-panel {
28
+ background: rgba(30, 41, 59, 0.7);
29
+ backdrop-filter: blur(10px);
30
+ border: 1px solid rgba(255, 255, 255, 0.1);
31
+ }
32
+ input[type="range"] {
33
+ -webkit-appearance: none;
34
+ background: transparent;
35
+ }
36
+ input[type="range"]::-webkit-slider-thumb {
37
+ -webkit-appearance: none;
38
+ height: 16px;
39
+ width: 16px;
40
+ border-radius: 50%;
41
+ background: #3B82F6;
42
+ margin-top: -6px;
43
+ cursor: pointer;
44
+ }
45
+ input[type="range"]::-webkit-slider-runnable-track {
46
+ width: 100%;
47
+ height: 4px;
48
+ background: #475569;
49
+ border-radius: 2px;
50
+ }
51
+ [v-cloak] { display: none; }
52
+ </style>
53
+ </head>
54
+ <body class="min-h-screen p-4 md:p-8">
55
+ <div id="app" class="max-w-7xl mx-auto" v-cloak>
56
+ <!-- Header -->
57
+ <header class="mb-8 flex justify-between items-center">
58
+ <div>
59
+ <h1 class="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-teal-400">
60
+ 智能动态定价实验室
61
+ </h1>
62
+ <p class="text-slate-400 mt-1">基于价格弹性模型的 AI 利润优化引擎</p>
63
+ </div>
64
+ <div class="text-xs text-slate-500 border border-slate-700 px-3 py-1 rounded-full">
65
+ v1.1.0 | Powered by SciPy
66
+ </div>
67
+ </header>
68
+
69
+ <!-- Navigation Tabs -->
70
+ <div class="flex space-x-4 mb-6">
71
+ <button @click="currentTab = 'single'"
72
+ :class="{'text-blue-400 border-b-2 border-blue-400': currentTab === 'single', 'text-slate-400': currentTab !== 'single'}"
73
+ class="pb-2 px-1 transition font-medium">
74
+ 单品模拟
75
+ </button>
76
+ <button @click="currentTab = 'batch'"
77
+ :class="{'text-blue-400 border-b-2 border-blue-400': currentTab === 'batch', 'text-slate-400': currentTab !== 'batch'}"
78
+ class="pb-2 px-1 transition font-medium">
79
+ 批量分析 (Excel/CSV)
80
+ </button>
81
+ </div>
82
+
83
+ <!-- Single Analysis Mode -->
84
+ <div v-show="currentTab === 'single'" class="grid grid-cols-1 lg:grid-cols-12 gap-6">
85
+ <!-- Sidebar Controls -->
86
+ <div class="lg:col-span-3 space-y-6">
87
+ <div class="glass-panel rounded-xl p-6 shadow-lg">
88
+ <h2 class="text-lg font-semibold mb-4 text-blue-400 flex items-center">
89
+ <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path></svg>
90
+ 参数配置
91
+ </h2>
92
+
93
+ <div class="space-y-4">
94
+ <!-- Input Group -->
95
+ <div>
96
+ <label class="block text-sm text-slate-400 mb-1">商品成本 (Cost)</label>
97
+ <div class="relative">
98
+ <span class="absolute left-3 top-2 text-slate-500">¥</span>
99
+ <input type="number" v-model.number="params.cost" @change="calculate"
100
+ class="w-full bg-slate-800 border border-slate-600 rounded px-8 py-2 focus:outline-none focus:border-blue-500 transition">
101
+ </div>
102
+ </div>
103
+
104
+ <div>
105
+ <label class="block text-sm text-slate-400 mb-1">当前售价 (Base Price)</label>
106
+ <div class="relative">
107
+ <span class="absolute left-3 top-2 text-slate-500">¥</span>
108
+ <input type="number" v-model.number="params.base_price" @change="calculate"
109
+ class="w-full bg-slate-800 border border-slate-600 rounded px-8 py-2 focus:outline-none focus:border-blue-500 transition">
110
+ </div>
111
+ </div>
112
+
113
+ <div>
114
+ <label class="block text-sm text-slate-400 mb-1">当前销量 (Base Demand)</label>
115
+ <div class="relative">
116
+ <span class="absolute left-3 top-2 text-slate-500">📦</span>
117
+ <input type="number" v-model.number="params.base_demand" @change="calculate"
118
+ class="w-full bg-slate-800 border border-slate-600 rounded px-8 py-2 focus:outline-none focus:border-blue-500 transition">
119
+ </div>
120
+ </div>
121
+
122
+ <div class="pt-4 border-t border-slate-700">
123
+ <div class="flex justify-between mb-1">
124
+ <label class="block text-sm text-slate-400">价格敏感度 (Elasticity)</label>
125
+ <span class="text-sm font-mono text-teal-400">${ params.elasticity }</span>
126
+ </div>
127
+ <input type="range" min="-5" max="-0.1" step="0.1" v-model.number="params.elasticity" @input="calculate"
128
+ class="w-full mb-1">
129
+ <p class="text-xs text-slate-500">
130
+ 值越小(-5),用户对价格越敏感(稍微涨价就跑光)。
131
+ </p>
132
+ </div>
133
+
134
+ <div class="pt-4">
135
+ <label class="block text-sm text-slate-400 mb-2">需求模型</label>
136
+ <div class="flex space-x-2 bg-slate-800 p-1 rounded">
137
+ <button @click="params.model_type = 'linear'; calculate()"
138
+ :class="{'bg-blue-600 text-white': params.model_type === 'linear', 'text-slate-400 hover:text-white': params.model_type !== 'linear'}"
139
+ class="flex-1 py-1.5 rounded text-sm transition">
140
+ 线性模型
141
+ </button>
142
+ <button @click="params.model_type = 'constant'; calculate()"
143
+ :class="{'bg-blue-600 text-white': params.model_type === 'constant', 'text-slate-400 hover:text-white': params.model_type !== 'constant'}"
144
+ class="flex-1 py-1.5 rounded text-sm transition">
145
+ 指数模型
146
+ </button>
147
+ </div>
148
+ </div>
149
+ </div>
150
+ </div>
151
+
152
+ <!-- Optimal Result Card -->
153
+ <div class="glass-panel rounded-xl p-6 border-l-4 border-teal-500" v-if="result">
154
+ <h3 class="text-sm font-uppercase text-slate-400 tracking-wider mb-3">AI 建议最优解</h3>
155
+ <div class="flex justify-between items-end mb-2">
156
+ <span class="text-3xl font-bold text-white">¥${ result.optimal.price }</span>
157
+ <span class="text-sm text-teal-400 mb-1" v-if="result.optimal.price > params.base_price">
158
+ (建议涨价 ${ ((result.optimal.price - params.base_price)/params.base_price*100).toFixed(1) }%)
159
+ </span>
160
+ <span class="text-sm text-red-400 mb-1" v-else>
161
+ (建议降价 ${ ((params.base_price - result.optimal.price)/params.base_price*100).toFixed(1) }%)
162
+ </span>
163
+ </div>
164
+ <div class="grid grid-cols-2 gap-2 mt-4 text-sm">
165
+ <div class="bg-slate-800 p-2 rounded">
166
+ <div class="text-slate-500">预期利润</div>
167
+ <div class="font-mono text-teal-400">¥${ result.optimal.profit }</div>
168
+ </div>
169
+ <div class="bg-slate-800 p-2 rounded">
170
+ <div class="text-slate-500">预期销量</div>
171
+ <div class="font-mono text-blue-400">${ result.optimal.demand }</div>
172
+ </div>
173
+ </div>
174
+ </div>
175
+ </div>
176
+
177
+ <!-- Main Chart Area -->
178
+ <div class="lg:col-span-9 space-y-6">
179
+ <div class="glass-panel rounded-xl p-6 h-[500px] flex flex-col">
180
+ <div class="flex justify-between items-center mb-4">
181
+ <h2 class="text-lg font-semibold text-white">利润与需求模拟分析</h2>
182
+ <div class="flex space-x-4 text-sm">
183
+ <div class="flex items-center"><span class="w-3 h-3 bg-teal-500 rounded-full mr-2"></span>利润 (左轴)</div>
184
+ <div class="flex items-center"><span class="w-3 h-3 bg-blue-500 rounded-full mr-2"></span>需求量 (右轴)</div>
185
+ </div>
186
+ </div>
187
+ <div id="mainChart" class="flex-1 w-full"></div>
188
+ </div>
189
+
190
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
191
+ <div class="glass-panel p-4 rounded-xl text-center">
192
+ <div class="text-sm text-slate-400 mb-1">当前利润 (Current)</div>
193
+ <div class="text-xl font-mono text-slate-300">
194
+ ¥${ ((params.base_price - params.cost) * params.base_demand).toFixed(2) }
195
+ </div>
196
+ </div>
197
+ <div class="glass-panel p-4 rounded-xl text-center">
198
+ <div class="text-sm text-slate-400 mb-1">优化后利润 (Optimized)</div>
199
+ <div class="text-xl font-mono text-teal-400">
200
+ ¥${ result ? result.optimal.profit : '---' }
201
+ </div>
202
+ </div>
203
+ <div class="glass-panel p-4 rounded-xl text-center border border-teal-500/30 bg-teal-500/10">
204
+ <div class="text-sm text-teal-300 mb-1">利润提升 (Uplift)</div>
205
+ <div class="text-xl font-bold text-teal-400">
206
+ +${ calculateUplift() }%
207
+ </div>
208
+ </div>
209
+ </div>
210
+ </div>
211
+ </div>
212
+
213
+ <!-- Batch Analysis Mode -->
214
+ <div v-show="currentTab === 'batch'" class="glass-panel rounded-xl p-8 max-w-4xl mx-auto">
215
+ <h2 class="text-xl font-bold mb-4 text-white">批量文件分析</h2>
216
+ <p class="text-slate-400 mb-6">
217
+ 上传 CSV 或 Excel 文件,包含以下列:<code class="text-sm bg-slate-800 px-1 py-0.5 rounded text-blue-300">cost</code>,
218
+ <code class="text-sm bg-slate-800 px-1 py-0.5 rounded text-blue-300">base_price</code>,
219
+ <code class="text-sm bg-slate-800 px-1 py-0.5 rounded text-blue-300">base_demand</code>。
220
+ 可选列:<code class="text-sm bg-slate-800 px-1 py-0.5 rounded text-blue-300">elasticity</code> (默认 -1.5),
221
+ <code class="text-sm bg-slate-800 px-1 py-0.5 rounded text-blue-300">model_type</code> (默认 linear)。
222
+ </p>
223
+
224
+ <div class="border-2 border-dashed border-slate-600 rounded-xl p-8 text-center hover:border-blue-500 transition cursor-pointer bg-slate-800/50"
225
+ @dragover.prevent @drop.prevent="handleDrop" @click="$refs.fileInput.click()">
226
+ <input type="file" ref="fileInput" class="hidden" @change="handleFileSelect" accept=".csv,.xlsx,.xls">
227
+ <div class="text-4xl mb-3">📂</div>
228
+ <p class="text-lg text-slate-300 font-medium">点击或拖拽文件到此处</p>
229
+ <p class="text-sm text-slate-500 mt-2">支持 .csv, .xlsx (最大 16MB)</p>
230
+ </div>
231
+
232
+ <div v-if="uploadStatus" class="mt-4 p-4 rounded bg-slate-800 border border-slate-700">
233
+ <p :class="{'text-green-400': uploadStatus.type === 'success', 'text-red-400': uploadStatus.type === 'error'}">
234
+ ${ uploadStatus.message }
235
+ </p>
236
+ </div>
237
+
238
+ <!-- Batch Results Table -->
239
+ <div v-if="batchResults && batchResults.length > 0" class="mt-8 overflow-x-auto">
240
+ <h3 class="text-lg font-bold mb-3 text-white">分析结果 (前 50 条)</h3>
241
+ <table class="w-full text-sm text-left text-slate-300">
242
+ <thead class="text-xs text-slate-400 uppercase bg-slate-800">
243
+ <tr>
244
+ <th class="px-4 py-3">成本</th>
245
+ <th class="px-4 py-3">原价</th>
246
+ <th class="px-4 py-3">建议价格</th>
247
+ <th class="px-4 py-3">预期利润</th>
248
+ <th class="px-4 py-3">利润率提升</th>
249
+ </tr>
250
+ </thead>
251
+ <tbody>
252
+ <tr v-for="(item, index) in batchResults" :key="index" class="border-b border-slate-700 hover:bg-slate-800/50">
253
+ <td class="px-4 py-3">¥${ item.input.cost }</td>
254
+ <td class="px-4 py-3">¥${ item.input.base_price }</td>
255
+ <td class="px-4 py-3 font-bold text-blue-400">¥${ item.optimal.price }</td>
256
+ <td class="px-4 py-3 text-green-400">¥${ item.optimal.profit }</td>
257
+ <td class="px-4 py-3">
258
+ <span v-if="item.optimal.profit > (item.input.base_price - item.input.cost) * item.input.base_demand" class="text-green-400">
259
+ ↑ 提升
260
+ </span>
261
+ <span v-else class="text-slate-500">-</span>
262
+ </td>
263
+ </tr>
264
+ </tbody>
265
+ </table>
266
+ </div>
267
+ </div>
268
+ </div>
269
+
270
+ <script>
271
+ const { createApp, ref, onMounted, reactive, watch } = Vue;
272
+
273
+ createApp({
274
+ delimiters: ['${', '}'], // Changed delimiters to avoid Jinja2 conflict
275
+ setup() {
276
+ const currentTab = ref('single');
277
+ const params = reactive({
278
+ cost: 100,
279
+ base_price: 150,
280
+ base_demand: 500,
281
+ elasticity: -2.0,
282
+ model_type: 'linear'
283
+ });
284
+
285
+ const result = ref(null);
286
+ const batchResults = ref([]);
287
+ const uploadStatus = ref(null);
288
+ const fileInput = ref(null);
289
+ let chartInstance = null;
290
+
291
+ const calculateUplift = () => {
292
+ if (!result.value) return 0;
293
+ const currentProfit = (params.base_price - params.cost) * params.base_demand;
294
+ const optProfit = result.value.optimal.profit;
295
+ if (currentProfit <= 0) return 100; // Edge case
296
+ return ((optProfit - currentProfit) / currentProfit * 100).toFixed(1);
297
+ };
298
+
299
+ const initChart = () => {
300
+ const chartDom = document.getElementById('mainChart');
301
+ if (!chartDom) return;
302
+ chartInstance = echarts.init(chartDom);
303
+ window.addEventListener('resize', () => chartInstance.resize());
304
+ };
305
+
306
+ const updateChart = (data) => {
307
+ if (!chartInstance) return;
308
+ const prices = data.map(item => item.price);
309
+ const profits = data.map(item => item.profit);
310
+ const demands = data.map(item => item.demand);
311
+
312
+ const option = {
313
+ backgroundColor: 'transparent',
314
+ tooltip: {
315
+ trigger: 'axis',
316
+ axisPointer: { type: 'cross' },
317
+ backgroundColor: 'rgba(15, 23, 42, 0.9)',
318
+ borderColor: '#334155',
319
+ textStyle: { color: '#e2e8f0' }
320
+ },
321
+ grid: {
322
+ left: '3%', right: '3%', bottom: '3%', containLabel: true
323
+ },
324
+ xAxis: {
325
+ type: 'category',
326
+ data: prices,
327
+ name: '价格 (Price)',
328
+ nameLocation: 'middle',
329
+ nameGap: 30,
330
+ axisLine: { lineStyle: { color: '#64748b' } }
331
+ },
332
+ yAxis: [
333
+ {
334
+ type: 'value',
335
+ name: '利润 (Profit)',
336
+ position: 'left',
337
+ axisLine: { lineStyle: { color: '#10B981' } },
338
+ splitLine: { lineStyle: { color: '#334155', type: 'dashed' } },
339
+ axisLabel: { formatter: '{value}' }
340
+ },
341
+ {
342
+ type: 'value',
343
+ name: '需求 (Demand)',
344
+ position: 'right',
345
+ axisLine: { lineStyle: { color: '#3B82F6' } },
346
+ splitLine: { show: false },
347
+ axisLabel: { formatter: '{value}' }
348
+ }
349
+ ],
350
+ series: [
351
+ {
352
+ name: '利润',
353
+ type: 'line',
354
+ data: profits,
355
+ smooth: true,
356
+ lineStyle: { width: 3, color: '#10B981' },
357
+ showSymbol: false,
358
+ areaStyle: {
359
+ color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
360
+ { offset: 0, color: 'rgba(16, 185, 129, 0.3)' },
361
+ { offset: 1, color: 'rgba(16, 185, 129, 0)' }
362
+ ])
363
+ },
364
+ markPoint: {
365
+ data: [
366
+ { type: 'max', name: 'Max Profit', itemStyle: { color: '#F59E0B' } }
367
+ ]
368
+ }
369
+ },
370
+ {
371
+ name: '需求',
372
+ type: 'line',
373
+ yAxisIndex: 1,
374
+ data: demands,
375
+ smooth: true,
376
+ lineStyle: { width: 2, type: 'dashed', color: '#3B82F6' },
377
+ showSymbol: false
378
+ }
379
+ ]
380
+ };
381
+ chartInstance.setOption(option);
382
+ };
383
+
384
+ const calculate = async () => {
385
+ try {
386
+ const res = await fetch('/api/analyze', {
387
+ method: 'POST',
388
+ headers: { 'Content-Type': 'application/json' },
389
+ body: JSON.stringify(params)
390
+ });
391
+ const data = await res.json();
392
+ if (data.success) {
393
+ result.value = data;
394
+ updateChart(data.data);
395
+ } else {
396
+ console.error(data.error);
397
+ }
398
+ } catch (e) {
399
+ console.error(e);
400
+ }
401
+ };
402
+
403
+ const uploadFile = async (file) => {
404
+ uploadStatus.value = { type: 'info', message: '正在上传分析中...' };
405
+ const formData = new FormData();
406
+ formData.append('file', file);
407
+
408
+ try {
409
+ const res = await fetch('/api/upload', {
410
+ method: 'POST',
411
+ body: formData
412
+ });
413
+ const data = await res.json();
414
+
415
+ if (data.success) {
416
+ batchResults.value = data.batch_results;
417
+ uploadStatus.value = { type: 'success', message: `分析完成!成功处理 ${data.batch_results.length} 条数据。` };
418
+ } else {
419
+ uploadStatus.value = { type: 'error', message: `错误: ${data.error}` };
420
+ }
421
+ } catch (e) {
422
+ uploadStatus.value = { type: 'error', message: `网络错误: ${e.message}` };
423
+ }
424
+ };
425
+
426
+ const handleFileSelect = (event) => {
427
+ const file = event.target.files[0];
428
+ if (file) uploadFile(file);
429
+ };
430
+
431
+ const handleDrop = (event) => {
432
+ const file = event.dataTransfer.files[0];
433
+ if (file) uploadFile(file);
434
+ };
435
+
436
+ // Watch for tab change to resize chart
437
+ watch(currentTab, (newTab) => {
438
+ if (newTab === 'single') {
439
+ setTimeout(() => {
440
+ if (chartInstance) chartInstance.resize();
441
+ }, 100);
442
+ }
443
+ });
444
+
445
+ onMounted(() => {
446
+ initChart();
447
+ calculate();
448
+ });
449
+
450
+ return {
451
+ currentTab,
452
+ params,
453
+ result,
454
+ batchResults,
455
+ uploadStatus,
456
+ fileInput,
457
+ calculate,
458
+ calculateUplift,
459
+ handleFileSelect,
460
+ handleDrop
461
+ };
462
+ }
463
+ }).mount('#app');
464
+ </script>
465
+ </body>
466
+ </html>
test_data.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ cost,base_price,base_demand,elasticity
2
+ 100,150,500,-2.0
3
+ 50,80,1000,-1.5