KurtDu commited on
Commit
803861a
1 Parent(s): d0b4023

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +246 -219
app.py CHANGED
@@ -1,227 +1,254 @@
1
- import os
2
- import json
3
- import random
4
- import uuid
5
- from flask import Flask, request, jsonify, session, render_template
6
- from flask_cors import CORS
7
- from flask_session import Session # 引入 Flask-Session
8
- from datetime import datetime
9
- from elo_rank import EloRank
10
-
11
- app = Flask(__name__)
12
- CORS(app, supports_credentials=True)
13
-
14
- # 配置 Flask-Session
15
- app.config['SESSION_TYPE'] = 'filesystem' # 使用文件系统存储
16
- app.config['SESSION_PERMANENT'] = False # 不持久化 session
17
- app.config['SESSION_USE_SIGNER'] = True # 为 session 数据添加签名保护
18
- app.config['SESSION_FILE_DIR'] = '/app/session_data' # 存储 session 文件的路径
19
-
20
- # 确保目录存在
21
- if not os.path.exists('/tmp/flask_session/'):
22
- os.makedirs('/tmp/flask_session/')
23
-
24
- # 初始化 Session
25
- Session(app)
26
-
27
- app.secret_key = 'supersecretkey'
28
-
29
- base_dir = os.path.dirname(os.path.abspath(__file__))
30
-
31
- DATA_DIR = os.path.join(base_dir, '/app/data')
32
- RESULTS_DIR = os.path.join(base_dir, '/app/results')
33
-
34
- # 实例化 EloRank 系统
35
- elo_rank_system = EloRank()
36
-
37
- # 初始化 Elo 排名的模型
38
- models = [
39
- 'output_path_4o', 'output_path_miniomni', 'output_path_speechgpt',
40
- 'output_path_funaudio', 'output_path_4o_cascade', 'output_path_4o_llama_omni'
41
- ]
42
- for model in models:
43
- elo_rank_system.add_model(model)
44
-
45
-
46
- def print_directory_structure(start_path, indent=''):
47
- for item in os.listdir(start_path):
48
- item_path = os.path.join(start_path, item)
49
- if os.path.isdir(item_path):
50
- print(f"{indent}📁 {item}/")
51
- print_directory_structure(item_path, indent + ' ')
52
- else:
53
- print(f"{indent}📄 {item}")
54
-
55
-
56
- def load_test_data(task):
57
- """Load the JSON file corresponding to the selected task"""
58
- # 调用函数,打印当前目录结构
59
- try:
60
- with open('/app/test_text.txt', 'r') as file:
61
- content = file.read()
62
- print(content)
63
- except FileNotFoundError:
64
- print("Test text file not found.")
65
-
66
- try:
67
- with open(os.path.join(DATA_DIR, f"{task}.json"), "r", encoding='utf-8') as f:
68
- test_data = json.load(f)
69
- except FileNotFoundError:
70
- return jsonify({"message": "Test data file not found"}), 400
71
-
72
- # 更新音频路径,将它们指向 Flask 静态文件夹
73
- for item in test_data:
74
- item['input_path'] = f"/app/static/audio{item['input_path']}"
75
- item['output_path_4o'] = f"/app/static/audio{item['output_path_4o']}"
76
- item['output_path_miniomni'] = f"/app/static/audio{item['output_path_miniomni']}"
77
- item['output_path_speechgpt'] = f"/app/static/audio{item['output_path_speechgpt']}"
78
- item['output_path_funaudio'] = f"/app/static/audio{item['output_path_funaudio']}"
79
- item['output_path_4o_cascade'] = f"/app/static/audio{item['output_path_4o_cascade']}"
80
- item['output_path_4o_llama_omni'] = f"/app/static/audio{item['output_path_4o_llama_omni']}"
81
 
82
- return test_data
83
 
84
 
85
- def save_result(task, username, result_data, session_id):
86
- """Save user's result in a separate file"""
87
- file_path = os.path.join(RESULTS_DIR, f"{task}_{username}_{session_id}.jsonl")
88
- # 获取所有模型的 Elo 分数
89
- elo_scores = {model: elo_rank_system.get_rating(model) for model in models}
90
 
91
- # 添加 Elo 分数和时间戳到结果数据
92
- result_data['elo_scores'] = elo_scores
93
- result_data['timestamp'] = datetime.now().isoformat()
94
- with open(file_path, "a", encoding='utf-8') as f:
95
- f.write(json.dumps(result_data) + "\n")
96
 
97
 
98
- @app.route('/start_test', methods=['POST'])
99
- def start_test():
100
- """Initiate the test for a user with the selected task"""
101
- data = request.json
102
- task = data['task']
103
- username = data['username']
104
 
105
- # Load the test data
106
- test_data = load_test_data(task)
107
- if isinstance(test_data, tuple):
108
- return test_data # 返回错误信息
109
 
110
- # Shuffle test data for the user
111
- random.shuffle(test_data)
112
-
113
- # Generate a unique session ID
114
- session_id = str(uuid.uuid4())
115
-
116
- # Store in session
117
- session['task'] = task
118
- session['username'] = username
119
- session['test_data'] = test_data
120
- session['current_index'] = 0
121
- session['session_id'] = session_id
122
-
123
- task_description = test_data[0].get('task_description', '')
124
-
125
- return jsonify({
126
- "message": "Test started",
127
- "total_tests": len(test_data),
128
- "task_description": task_description
129
- })
130
-
131
-
132
- @app.route('/next_test', methods=['GET'])
133
- def next_test():
134
- """Serve the next test item"""
135
- if 'current_index' not in session or 'test_data' not in session:
136
- return jsonify({"message": "Session data missing"}), 400
137
-
138
- current_index = session['current_index']
139
- test_data = session['test_data']
140
-
141
- if current_index >= len(test_data):
142
- return jsonify({"message": "Test completed"}), 200
143
-
144
- # 使用 EloRank 的 sample_next_match 来选择两款模型
145
- selected_models = elo_rank_system.sample_next_match()
146
-
147
- if not selected_models or len(selected_models) != 2:
148
- return jsonify({"message": "Error selecting models"}), 500
149
-
150
- # Serve test data with the two selected models
151
- current_test = test_data[current_index]
152
- session['selected_models'] = selected_models
153
- session['current_index'] += 1
154
-
155
- return jsonify({
156
- "text": current_test["text"],
157
- "input_path": current_test["input_path"],
158
- "model_a": selected_models[0],
159
- "model_b": selected_models[1],
160
- "audio_a": current_test[selected_models[0]],
161
- "audio_b": current_test[selected_models[1]]
162
- })
163
-
164
-
165
- @app.route('/submit_result', methods=['POST'])
166
- def submit_result():
167
- """Submit the user's result and save it"""
168
- data = request.json
169
- chosen_model = data['chosen_model']
170
-
171
- username = session.get('username')
172
- task = session.get('task')
173
- current_index = session.get('current_index') - 1
174
- session_id = session.get('session_id')
175
-
176
- if not username or not task or current_index < 0:
177
- return jsonify({"message": "No active test found"}), 400
178
-
179
- selected_models = session['selected_models']
180
- model_a = selected_models[0]
181
- model_b = selected_models[1]
182
-
183
- result = {
184
- "name": username,
185
- "chosen_model": chosen_model,
186
- "model_a": model_a,
187
- "model_b": model_b,
188
- "result": {
189
- model_a: 1 if chosen_model == 'A' else 0,
190
- model_b: 1 if chosen_model == 'B' else 0
191
- }
192
- }
193
-
194
- test_data = session['test_data'][current_index]
195
- result_data = {**test_data, **result}
196
- save_result(task, username, result_data, session_id)
197
-
198
- # 更新 Elo 排名系统
199
- if chosen_model == 'A':
200
- elo_rank_system.record_match(model_a, model_b)
201
- else:
202
- elo_rank_system.record_match(model_b, model_a)
203
-
204
- return jsonify({
205
- "message": "Result submitted",
206
- "model_a": model_a,
207
- "model_b": model_b,
208
- "chosen_model": chosen_model
209
- })
210
-
211
-
212
- @app.route('/end_test', methods=['GET'])
213
- def end_test():
214
- """End the test session"""
215
- session.clear()
216
- return jsonify({"message": "Test completed"})
217
-
218
-
219
- @app.route('/')
220
- def index():
221
- return render_template('index.html')
222
-
223
-
224
- if __name__ == '__main__':
225
- if not os.path.exists(RESULTS_DIR):
226
- os.makedirs(RESULTS_DIR)
227
- app.run(host="0.0.0.0", debug=True, port=8080)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import os
2
+ # import json
3
+ # import random
4
+ # import uuid
5
+ # from flask import Flask, request, jsonify, session, render_template
6
+ # from flask_cors import CORS
7
+ # from flask_session import Session # 引入 Flask-Session
8
+ # from datetime import datetime
9
+ # from elo_rank import EloRank
10
+
11
+ # app = Flask(__name__)
12
+ # CORS(app, supports_credentials=True)
13
+
14
+ # # 配置 Flask-Session
15
+ # app.config['SESSION_TYPE'] = 'filesystem' # 使用文件系统存储
16
+ # app.config['SESSION_PERMANENT'] = False # 不持久化 session
17
+ # app.config['SESSION_USE_SIGNER'] = True # 为 session 数据添加签名保护
18
+ # app.config['SESSION_FILE_DIR'] = '/app/session_data' # 存储 session 文件的路径
19
+
20
+ # # 确保目录存在
21
+ # if not os.path.exists('/tmp/flask_session/'):
22
+ # os.makedirs('/tmp/flask_session/')
23
+
24
+ # # 初始化 Session
25
+ # Session(app)
26
+
27
+ # app.secret_key = 'supersecretkey'
28
+
29
+ # base_dir = os.path.dirname(os.path.abspath(__file__))
30
+
31
+ # DATA_DIR = os.path.join(base_dir, '/app/data')
32
+ # RESULTS_DIR = os.path.join(base_dir, '/app/results')
33
+
34
+ # # 实例化 EloRank 系统
35
+ # elo_rank_system = EloRank()
36
+
37
+ # # 初始化 Elo 排名的模型
38
+ # models = [
39
+ # 'output_path_4o', 'output_path_miniomni', 'output_path_speechgpt',
40
+ # 'output_path_funaudio', 'output_path_4o_cascade', 'output_path_4o_llama_omni'
41
+ # ]
42
+ # for model in models:
43
+ # elo_rank_system.add_model(model)
44
+
45
+
46
+ # def print_directory_structure(start_path, indent=''):
47
+ # for item in os.listdir(start_path):
48
+ # item_path = os.path.join(start_path, item)
49
+ # if os.path.isdir(item_path):
50
+ # print(f"{indent}📁 {item}/")
51
+ # print_directory_structure(item_path, indent + ' ')
52
+ # else:
53
+ # print(f"{indent}📄 {item}")
54
+
55
+
56
+ # def load_test_data(task):
57
+ # """Load the JSON file corresponding to the selected task"""
58
+ # # 调用函数,打印当前目录结构
59
+ # try:
60
+ # with open('/app/test_text.txt', 'r') as file:
61
+ # content = file.read()
62
+ # print(content)
63
+ # except FileNotFoundError:
64
+ # print("Test text file not found.")
65
+
66
+ # try:
67
+ # with open(os.path.join(DATA_DIR, f"{task}.json"), "r", encoding='utf-8') as f:
68
+ # test_data = json.load(f)
69
+ # except FileNotFoundError:
70
+ # return jsonify({"message": "Test data file not found"}), 400
71
+
72
+ # # 更新音频路径,将它们指向 Flask 静态文件夹
73
+ # for item in test_data:
74
+ # item['input_path'] = f"/app/static/audio{item['input_path']}"
75
+ # item['output_path_4o'] = f"/app/static/audio{item['output_path_4o']}"
76
+ # item['output_path_miniomni'] = f"/app/static/audio{item['output_path_miniomni']}"
77
+ # item['output_path_speechgpt'] = f"/app/static/audio{item['output_path_speechgpt']}"
78
+ # item['output_path_funaudio'] = f"/app/static/audio{item['output_path_funaudio']}"
79
+ # item['output_path_4o_cascade'] = f"/app/static/audio{item['output_path_4o_cascade']}"
80
+ # item['output_path_4o_llama_omni'] = f"/app/static/audio{item['output_path_4o_llama_omni']}"
81
 
82
+ # return test_data
83
 
84
 
85
+ # def save_result(task, username, result_data, session_id):
86
+ # """Save user's result in a separate file"""
87
+ # file_path = os.path.join(RESULTS_DIR, f"{task}_{username}_{session_id}.jsonl")
88
+ # # 获取所有模型的 Elo 分数
89
+ # elo_scores = {model: elo_rank_system.get_rating(model) for model in models}
90
 
91
+ # # 添加 Elo 分数和时间戳到结果数据
92
+ # result_data['elo_scores'] = elo_scores
93
+ # result_data['timestamp'] = datetime.now().isoformat()
94
+ # with open(file_path, "a", encoding='utf-8') as f:
95
+ # f.write(json.dumps(result_data) + "\n")
96
 
97
 
98
+ # @app.route('/start_test', methods=['POST'])
99
+ # def start_test():
100
+ # """Initiate the test for a user with the selected task"""
101
+ # data = request.json
102
+ # task = data['task']
103
+ # username = data['username']
104
 
105
+ # # Load the test data
106
+ # test_data = load_test_data(task)
107
+ # if isinstance(test_data, tuple):
108
+ # return test_data # 返回错误信息
109
 
110
+ # # Shuffle test data for the user
111
+ # random.shuffle(test_data)
112
+
113
+ # # Generate a unique session ID
114
+ # session_id = str(uuid.uuid4())
115
+
116
+ # # Store in session
117
+ # session['task'] = task
118
+ # session['username'] = username
119
+ # session['test_data'] = test_data
120
+ # session['current_index'] = 0
121
+ # session['session_id'] = session_id
122
+
123
+ # task_description = test_data[0].get('task_description', '')
124
+
125
+ # return jsonify({
126
+ # "message": "Test started",
127
+ # "total_tests": len(test_data),
128
+ # "task_description": task_description
129
+ # })
130
+
131
+
132
+ # @app.route('/next_test', methods=['GET'])
133
+ # def next_test():
134
+ # """Serve the next test item"""
135
+ # if 'current_index' not in session or 'test_data' not in session:
136
+ # return jsonify({"message": "Session data missing"}), 400
137
+
138
+ # current_index = session['current_index']
139
+ # test_data = session['test_data']
140
+
141
+ # if current_index >= len(test_data):
142
+ # return jsonify({"message": "Test completed"}), 200
143
+
144
+ # # 使用 EloRank 的 sample_next_match 来选择两款模型
145
+ # selected_models = elo_rank_system.sample_next_match()
146
+
147
+ # if not selected_models or len(selected_models) != 2:
148
+ # return jsonify({"message": "Error selecting models"}), 500
149
+
150
+ # # Serve test data with the two selected models
151
+ # current_test = test_data[current_index]
152
+ # session['selected_models'] = selected_models
153
+ # session['current_index'] += 1
154
+
155
+ # return jsonify({
156
+ # "text": current_test["text"],
157
+ # "input_path": current_test["input_path"],
158
+ # "model_a": selected_models[0],
159
+ # "model_b": selected_models[1],
160
+ # "audio_a": current_test[selected_models[0]],
161
+ # "audio_b": current_test[selected_models[1]]
162
+ # })
163
+
164
+
165
+ # @app.route('/submit_result', methods=['POST'])
166
+ # def submit_result():
167
+ # """Submit the user's result and save it"""
168
+ # data = request.json
169
+ # chosen_model = data['chosen_model']
170
+
171
+ # username = session.get('username')
172
+ # task = session.get('task')
173
+ # current_index = session.get('current_index') - 1
174
+ # session_id = session.get('session_id')
175
+
176
+ # if not username or not task or current_index < 0:
177
+ # return jsonify({"message": "No active test found"}), 400
178
+
179
+ # selected_models = session['selected_models']
180
+ # model_a = selected_models[0]
181
+ # model_b = selected_models[1]
182
+
183
+ # result = {
184
+ # "name": username,
185
+ # "chosen_model": chosen_model,
186
+ # "model_a": model_a,
187
+ # "model_b": model_b,
188
+ # "result": {
189
+ # model_a: 1 if chosen_model == 'A' else 0,
190
+ # model_b: 1 if chosen_model == 'B' else 0
191
+ # }
192
+ # }
193
+
194
+ # test_data = session['test_data'][current_index]
195
+ # result_data = {**test_data, **result}
196
+ # save_result(task, username, result_data, session_id)
197
+
198
+ # # 更新 Elo 排名系统
199
+ # if chosen_model == 'A':
200
+ # elo_rank_system.record_match(model_a, model_b)
201
+ # else:
202
+ # elo_rank_system.record_match(model_b, model_a)
203
+
204
+ # return jsonify({
205
+ # "message": "Result submitted",
206
+ # "model_a": model_a,
207
+ # "model_b": model_b,
208
+ # "chosen_model": chosen_model
209
+ # })
210
+
211
+
212
+ # @app.route('/end_test', methods=['GET'])
213
+ # def end_test():
214
+ # """End the test session"""
215
+ # session.clear()
216
+ # return jsonify({"message": "Test completed"})
217
+
218
+
219
+ # @app.route('/')
220
+ # def index():
221
+ # return render_template('index.html')
222
+
223
+
224
+ # if __name__ == '__main__':
225
+ # if not os.path.exists(RESULTS_DIR):
226
+ # os.makedirs(RESULTS_DIR)
227
+ # app.run(host="0.0.0.0", debug=True, port=8080)
228
+
229
+
230
+
231
+ from flask import Flask, render_template_string
232
+
233
+ app = Flask(__name__)
234
+
235
+ @app.route("/")
236
+ def home():
237
+ # 使用 iframe 嵌入目标网站
238
+ return render_template_string("""
239
+ <!DOCTYPE html>
240
+ <html lang="en">
241
+ <head>
242
+ <meta charset="UTF-8">
243
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
244
+ <title>Embedded Website</title>
245
+ </head>
246
+ <body style="margin: 0; padding: 0; height: 100%; overflow: hidden;">
247
+ <iframe src="http://71.132.14.167:6002/" frameborder="0" style="width: 100%; height: 100%; border: none;"></iframe>
248
+ </body>
249
+ </html>
250
+ """)
251
+
252
+ if __name__ == "__main__":
253
+ app.run(host="0.0.0.0", port=7860)
254
+