Cbphcr commited on
Commit
d2b2b78
·
verified ·
1 Parent(s): dfe35ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -146
app.py CHANGED
@@ -1,146 +1,147 @@
1
- import os
2
- import time
3
- import json
4
- import shutil
5
- import zipfile
6
- import gradio as gr
7
- from eval_exp import evaluate
8
- from datetime import datetime
9
- from apscheduler.schedulers.background import BackgroundScheduler
10
-
11
-
12
- def load_splits():
13
- splits_dir = "chinatravel/evaluation/default_splits"
14
- splits = []
15
- for filename in os.listdir(splits_dir):
16
- if filename.endswith(".txt"):
17
- splits.append(filename.replace(".txt", ""))
18
- return splits
19
-
20
-
21
- SPLITS_LIST = load_splits()
22
- # SUBMIT_DIR = "./submissions"
23
- # OUTPUT_DIR = "./outputs"
24
- SUBMIT_DIR = os.path.abspath("submissions")
25
- OUTPUT_DIR = os.path.abspath("outputs")
26
-
27
- os.makedirs(SUBMIT_DIR, exist_ok=True)
28
- os.makedirs(OUTPUT_DIR, exist_ok=True)
29
- # clear directories if they already exist
30
- shutil.rmtree(SUBMIT_DIR, ignore_errors=True)
31
- shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
32
-
33
-
34
- def clean_old_outputs(folder, keep_hours=24):
35
- now = time.time()
36
- for fname in os.listdir(folder):
37
- fpath = os.path.join(folder, fname)
38
- if os.path.isfile(fpath) and now - os.path.getmtime(fpath) > keep_hours * 3600:
39
- os.remove(fpath)
40
-
41
-
42
- scheduler = BackgroundScheduler()
43
- scheduler.add_job(lambda: clean_old_outputs(OUTPUT_DIR), "interval", hours=12)
44
- scheduler.start()
45
-
46
-
47
- class Arguments:
48
- def __init__(self, splits, result_dir):
49
- self.splits = splits
50
- self.result_dir = result_dir
51
-
52
-
53
- def handle_submission(zip_file, dataset_choice):
54
- if zip_file is None:
55
- yield "❌ 请上传 zip 文件!", 0, 0, 0, None
56
- return
57
-
58
- shutil.rmtree(SUBMIT_DIR, ignore_errors=True)
59
- os.makedirs(SUBMIT_DIR, exist_ok=True)
60
-
61
- with zipfile.ZipFile(zip_file.name, "r") as zip_ref:
62
- print(f"正在解压缩 {zip_file.name} 到 {SUBMIT_DIR}...")
63
- zip_ref.extractall(SUBMIT_DIR)
64
-
65
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
66
- print(f"Submission dir: {SUBMIT_DIR}")
67
- print(os.path.splitext(zip_file.name))
68
- unzipped_dir = os.path.join(
69
- SUBMIT_DIR, os.path.basename(zip_file.name).replace(".zip", "")
70
- )
71
- print(f"Unzipped directory: {unzipped_dir}")
72
- output_path = os.path.join(OUTPUT_DIR, f"result_main_{timestamp}.json")
73
- args = Arguments(splits=dataset_choice, result_dir=unzipped_dir)
74
-
75
- try:
76
- yield "🚀 开始测评...", 0, 0, 0, None
77
-
78
- result = {}
79
- for progress in evaluate(args, result):
80
- stage = progress.get("stage", "")
81
- progress_value = progress.get("progress", 0)
82
-
83
- if stage == "schema":
84
- yield "Schema 阶段测评中...", progress_value, 0, 0, None
85
- elif stage == "commonsense":
86
- yield "Commonsense 阶段测评中...", 100, progress_value, 0, None
87
- elif stage == "logic":
88
- yield "Logic 阶段测评中...", 100, 100, progress_value, None
89
- elif stage == "final":
90
- result.update(progress.get("result", {}))
91
- yield "测评完成,正在保存结果...", 100, 100, 100, None
92
-
93
- # 保存结果到文件
94
- with open(output_path, "w", encoding="utf-8") as f:
95
- json.dump(result, f, ensure_ascii=False, indent=4)
96
-
97
- # 在测评完成后更新结果文件的值和可见性
98
- result_file.value = output_path
99
- result_file.visible = True
100
- yield "✅ 测评完成!", 100, 100, 100, output_path
101
-
102
- except Exception as e:
103
- import traceback
104
-
105
- traceback.print_exc()
106
- yield f"❌ 测评异常:{e}", 0, 0, 0, None
107
-
108
-
109
- with gr.Blocks() as demo:
110
- gr.Markdown("# 📊 ChinaTravel 模型测评")
111
-
112
- with gr.Row():
113
- zip_input = gr.File(label="上传模型预测 zip 文件", file_types=[".zip"])
114
- dataset_choice = gr.Radio(
115
- SPLITS_LIST, label="选择评估数据集", value="validation"
116
- )
117
-
118
- submit_btn = gr.Button("开始测评")
119
-
120
- output_msg = gr.Markdown()
121
- result_file = gr.File(label="结果文件下载") # , visible=False)
122
-
123
- # 添加三个进度条
124
- schema_progress = gr.Slider(
125
- label="Schema 阶段进度", minimum=0, maximum=100, value=0, interactive=False
126
- )
127
- commonsense_progress = gr.Slider(
128
- label="Commonsense 阶段进度", minimum=0, maximum=100, value=0, interactive=False
129
- )
130
- logic_progress = gr.Slider(
131
- label="Logic 阶段进度", minimum=0, maximum=100, value=0, interactive=False
132
- )
133
-
134
- submit_btn.click(
135
- handle_submission,
136
- inputs=[zip_input, dataset_choice],
137
- outputs=[
138
- output_msg,
139
- schema_progress,
140
- commonsense_progress,
141
- logic_progress,
142
- result_file,
143
- ],
144
- )
145
-
146
- demo.launch(debug=True)
 
 
1
+ import os
2
+ import time
3
+ import json
4
+ import shutil
5
+ import zipfile
6
+ import gradio as gr
7
+ from eval_exp import evaluate
8
+ from datetime import datetime
9
+ from apscheduler.schedulers.background import BackgroundScheduler
10
+
11
+
12
+ def load_splits():
13
+ splits_dir = "chinatravel/evaluation/default_splits"
14
+ splits = []
15
+ for filename in os.listdir(splits_dir):
16
+ if filename.endswith(".txt"):
17
+ splits.append(filename.replace(".txt", ""))
18
+ return splits
19
+
20
+
21
+ SPLITS_LIST = load_splits()
22
+ # SUBMIT_DIR = "./submissions"
23
+ # OUTPUT_DIR = "./outputs"
24
+ SUBMIT_DIR = os.path.abspath("submissions")
25
+ OUTPUT_DIR = os.path.abspath("outputs")
26
+
27
+ # clear directories if they already exist
28
+ shutil.rmtree(SUBMIT_DIR, ignore_errors=True)
29
+ shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
30
+
31
+ os.makedirs(SUBMIT_DIR, exist_ok=True)
32
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
33
+
34
+
35
+ def clean_old_outputs(folder, keep_hours=24):
36
+ now = time.time()
37
+ for fname in os.listdir(folder):
38
+ fpath = os.path.join(folder, fname)
39
+ if os.path.isfile(fpath) and now - os.path.getmtime(fpath) > keep_hours * 3600:
40
+ os.remove(fpath)
41
+
42
+
43
+ scheduler = BackgroundScheduler()
44
+ scheduler.add_job(lambda: clean_old_outputs(OUTPUT_DIR), "interval", hours=12)
45
+ scheduler.start()
46
+
47
+
48
+ class Arguments:
49
+ def __init__(self, splits, result_dir):
50
+ self.splits = splits
51
+ self.result_dir = result_dir
52
+
53
+
54
+ def handle_submission(zip_file, dataset_choice):
55
+ if zip_file is None:
56
+ yield "❌ 请上传 zip 文件!", 0, 0, 0, None
57
+ return
58
+
59
+ shutil.rmtree(SUBMIT_DIR, ignore_errors=True)
60
+ os.makedirs(SUBMIT_DIR, exist_ok=True)
61
+
62
+ with zipfile.ZipFile(zip_file.name, "r") as zip_ref:
63
+ print(f"正在解压缩 {zip_file.name} 到 {SUBMIT_DIR}...")
64
+ zip_ref.extractall(SUBMIT_DIR)
65
+
66
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
67
+ print(f"Submission dir: {SUBMIT_DIR}")
68
+ print(os.path.splitext(zip_file.name))
69
+ unzipped_dir = os.path.join(
70
+ SUBMIT_DIR, os.path.basename(zip_file.name).replace(".zip", "")
71
+ )
72
+ print(f"Unzipped directory: {unzipped_dir}")
73
+ output_path = os.path.join(OUTPUT_DIR, f"result_main_{timestamp}.json")
74
+ args = Arguments(splits=dataset_choice, result_dir=unzipped_dir)
75
+
76
+ try:
77
+ yield "🚀 开始测评...", 0, 0, 0, None
78
+
79
+ result = {}
80
+ for progress in evaluate(args, result):
81
+ stage = progress.get("stage", "")
82
+ progress_value = progress.get("progress", 0)
83
+
84
+ if stage == "schema":
85
+ yield "Schema 阶段测评中...", progress_value, 0, 0, None
86
+ elif stage == "commonsense":
87
+ yield "Commonsense 阶段测评中...", 100, progress_value, 0, None
88
+ elif stage == "logic":
89
+ yield "Logic 阶段测评中...", 100, 100, progress_value, None
90
+ elif stage == "final":
91
+ result.update(progress.get("result", {}))
92
+ yield "测评完成,正在保存结果...", 100, 100, 100, None
93
+
94
+ # 保存结果到文件
95
+ with open(output_path, "w", encoding="utf-8") as f:
96
+ json.dump(result, f, ensure_ascii=False, indent=4)
97
+
98
+ # 在测评完成后更新结果文件的值和可见性
99
+ result_file.value = output_path
100
+ result_file.visible = True
101
+ yield "✅ 测评完成!", 100, 100, 100, output_path
102
+
103
+ except Exception as e:
104
+ import traceback
105
+
106
+ traceback.print_exc()
107
+ yield f"❌ 测评异常:{e}", 0, 0, 0, None
108
+
109
+
110
+ with gr.Blocks() as demo:
111
+ gr.Markdown("# 📊 ChinaTravel 模型测评")
112
+
113
+ with gr.Row():
114
+ zip_input = gr.File(label="上传模型预测 zip 文件", file_types=[".zip"])
115
+ dataset_choice = gr.Radio(
116
+ SPLITS_LIST, label="选择评估数据集", value="validation"
117
+ )
118
+
119
+ submit_btn = gr.Button("开始测评")
120
+
121
+ output_msg = gr.Markdown()
122
+ result_file = gr.File(label="结果文件下载") # , visible=False)
123
+
124
+ # 添加三个进度条
125
+ schema_progress = gr.Slider(
126
+ label="Schema 阶段进度", minimum=0, maximum=100, value=0, interactive=False
127
+ )
128
+ commonsense_progress = gr.Slider(
129
+ label="Commonsense 阶段进度", minimum=0, maximum=100, value=0, interactive=False
130
+ )
131
+ logic_progress = gr.Slider(
132
+ label="Logic 阶段进度", minimum=0, maximum=100, value=0, interactive=False
133
+ )
134
+
135
+ submit_btn.click(
136
+ handle_submission,
137
+ inputs=[zip_input, dataset_choice],
138
+ outputs=[
139
+ output_msg,
140
+ schema_progress,
141
+ commonsense_progress,
142
+ logic_progress,
143
+ result_file,
144
+ ],
145
+ )
146
+
147
+ demo.launch(debug=True)