File size: 20,564 Bytes
a27816a
 
 
30b1610
4f32597
621bc72
a27816a
3499425
fc6c268
7032d9e
 
 
f41205f
30b1610
74d43a2
4f32597
74d43a2
4f32597
 
74d43a2
 
4f32597
7f83e08
621bc72
 
 
 
 
 
7f83e08
 
 
 
 
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f83e08
 
 
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f83e08
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f83e08
 
621bc72
 
 
 
 
 
 
08681f4
 
30b1610
141e12d
3499425
141e12d
 
3499425
141e12d
 
3499425
 
 
 
a27816a
e74db4f
3499425
 
 
 
 
 
 
 
 
 
 
141e12d
 
 
 
 
 
 
08681f4
3499425
30b1610
08681f4
 
 
 
a27816a
 
 
3499425
 
52d43e7
3499425
 
52d43e7
3499425
 
 
 
 
4d4a4b6
0900021
08681f4
3499425
621bc72
08681f4
 
22cec65
08681f4
 
 
 
 
 
30b1610
08681f4
 
 
 
f41205f
 
e18e210
30b1610
08681f4
 
30b1610
621bc72
 
7032d9e
 
621bc72
7032d9e
621bc72
 
 
7032d9e
621bc72
 
 
 
 
7032d9e
621bc72
 
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7032d9e
621bc72
 
7032d9e
 
621bc72
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7032d9e
621bc72
 
 
 
 
 
 
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7032d9e
 
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7032d9e
621bc72
 
 
 
 
 
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f83e08
 
 
 
621bc72
7f83e08
621bc72
 
 
 
 
 
 
7032d9e
621bc72
 
 
 
7f83e08
1bac4cd
 
7f83e08
741b8a0
 
 
 
3af21c3
 
741b8a0
3af21c3
741b8a0
3af21c3
 
 
 
 
 
 
 
 
 
 
 
 
 
1bac4cd
3af21c3
1bac4cd
 
 
3af21c3
 
 
 
 
 
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
7f83e08
7032d9e
621bc72
 
 
7032d9e
621bc72
7032d9e
621bc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30b1610
73850c8
5922648
 
 
 
73850c8
08681f4
1bac4cd
 
 
 
 
 
 
 
a27816a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import gradio as gr
import json
import importlib
import os
import sys
import time
from pathlib import Path
import concurrent.futures
import multiprocessing
import threading
import queue
from datetime import datetime, timedelta
from src.containerized_eval import eval_string_script

# 添加当前目录和src目录到模块搜索路径
current_dir = os.path.dirname(os.path.abspath(__file__))
src_dir = os.path.join(current_dir, "src")
if current_dir not in sys.path:
    sys.path.append(current_dir)
if src_dir not in sys.path:
    sys.path.append(src_dir)

# 添加全局任务队列和任务状态跟踪
task_queue = queue.Queue()
task_results = {}
active_tasks = {}
completed_tasks = []
task_id_counter = 0
task_lock = threading.Lock()
update_event = threading.Event()  # 通知UI需要刷新

def trigger_ui_update():
    """触发UI更新事件"""
    update_event.set()

def get_next_task_id():
    global task_id_counter
    with task_lock:
        task_id_counter += 1
        return f"task_{task_id_counter}"

def submit_task(input_data):
    """提交任务到队列
    
    Args:
        input_data: 列表(批量处理多个测试用例)
        
    Returns:
        str: 任务ID
    """
    try:
        if not isinstance(input_data, list):
            return {"status": "error", "message": "Input must be a list"}
            
        task_id = get_next_task_id()
        with task_lock:
            estimated_time = estimate_completion_time(input_data)
            task_info = {
                "id": task_id,
                "data": input_data,
                "status": "queued",
                "submitted_at": datetime.now(),
                "estimated_completion_time": estimated_time,
                "items_count": len(input_data)
            }
            active_tasks[task_id] = task_info
            task_queue.put(task_info)
            
            # 触发UI更新
            trigger_ui_update()
            
        # 如果这是第一个任务,启动处理线程
        if len(active_tasks) == 1:
            threading.Thread(target=process_task_queue, daemon=True).start()
            
        return {"status": "success", "task_id": task_id}
            
    except Exception as e:
        return {"status": "error", "message": str(e)}

def estimate_completion_time(input_data):
    """估计完成任务所需的时间
    
    Args:
        input_data: 任务数据
        
    Returns:
        timedelta: 估计的完成时间
    """
    # 假设每个任务项平均需要2秒处理
    # 这个值可以根据实际情况调整或从历史数据中学习
    avg_time_per_item = 2  
    total_items = len(input_data)
    
    # 考虑并行处理因素
    cpu_count = multiprocessing.cpu_count()
    parallel_factor = min(cpu_count, total_items)
    
    if parallel_factor > 0:
        estimated_seconds = (total_items * avg_time_per_item) / parallel_factor
        return timedelta(seconds=estimated_seconds)
    else:
        return timedelta(seconds=0)

def process_task_queue():
    """处理任务队列的后台线程"""
    while True:
        try:
            if task_queue.empty():
                time.sleep(0.5)
                continue
                
            task_info = task_queue.get()
            task_id = task_info["id"]
            
            # 更新任务状态
            with task_lock:
                active_tasks[task_id]["status"] = "processing"
                trigger_ui_update()  # 状态变更为处理中时更新UI
            
            # 处理任务
            result = evaluate(task_info["data"])
            
            # 更新任务结果
            with task_lock:
                active_tasks[task_id]["status"] = "completed"
                active_tasks[task_id]["completed_at"] = datetime.now()
                active_tasks[task_id]["result"] = result
                
                # 将任务移至已完成列表
                completed_tasks.append(active_tasks[task_id])
                del active_tasks[task_id]
                
                # 保留最近的20个已完成任务
                if len(completed_tasks) > 20:
                    completed_tasks.pop(0)
                
                trigger_ui_update()  # 任务完成时更新UI
            
            task_queue.task_done()
            
        except Exception as e:
            print(f"Error processing task queue: {str(e)}")
            time.sleep(1)

def evaluate(input_data):
    """评估代码的主函数
    
    Args:
        input_data: 列表(批量处理多个测试用例)
        
    Returns:
        list: 包含评估结果的列表
    """
    try:
        if not isinstance(input_data, list):
            return {"status": "Exception", "error": "Input must be a list"}
            
        results = []
        max_workers = multiprocessing.cpu_count()
        with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
            future_to_item = {executor.submit(evaluate_single_case, item): item for item in input_data}
            for future in concurrent.futures.as_completed(future_to_item):
                item = future_to_item[future]
                try:
                    result = future.result()
                    item.update(result)
                    results.append(item)
                except Exception as e:
                    item.update({"status": "Exception", "error": str(e)})
                    results.append(item)
        return results
            
    except Exception as e:
        return {"status": "Exception", "error": str(e)}

def evaluate_single_case(input_data):
    """评估单个代码用例
    
    Args:
        input_data: 字典(包含代码信息)
        
    Returns:
        dict: 包含评估结果的字典
    """
    try:
        if not isinstance(input_data, dict):
            return {"status": "Exception", "error": "Input item must be a dictionary"}
            
        language = input_data.get('language')
        completions = input_data.get('processed_completions', [])

        if not completions:
            return {"status": "Exception", "error": "No code provided"}

        results = []
        for comp in completions:
            code = input_data.get('prompt') + comp + '\n' + input_data.get('tests')
            result = evaluate_code(code, language)
            if result["status"] == "OK":
                return result
            results.append(result)
            
        return results[0]
           
    except Exception as e:
        return {"status": "Exception", "error": str(e)}

def evaluate_code(code, language):
    """评估特定语言的代码
    
    Args:
        code (str): 要评估的代码
        language (str): 编程语言
        
    Returns:
        dict: 包含评估结果的字典
    """
    try:
        # 使用containerized_eval中的eval_string_script函数
        result = eval_string_script(language, code)
        return result

    except Exception as e:
        return {"status": "Exception", "error": str(e)}

def get_queue_status():
    """获取当前队列状态
    
    Returns:
        dict: 包含队列状态的字典
    """
    with task_lock:
        queued_tasks = [task for task in active_tasks.values() if task["status"] == "queued"]
        processing_tasks = [task for task in active_tasks.values() if task["status"] == "processing"]
        
        # 计算总的预计完成时间
        total_estimated_time = timedelta(seconds=0)
        for task in active_tasks.values():
            if isinstance(task["estimated_completion_time"], timedelta):
                total_estimated_time += task["estimated_completion_time"]
        
        # 计算队列中的项目总数
        total_items = sum(task["items_count"] for task in active_tasks.values())
        
        return {
            "queued_tasks": len(queued_tasks),
            "processing_tasks": len(processing_tasks),
            "total_tasks": len(active_tasks),
            "total_items": total_items,
            "estimated_completion_time": str(total_estimated_time),
            "active_tasks": [
                {
                    "id": task["id"],
                    "status": task["status"],
                    "items_count": task["items_count"],
                    "submitted_at": task["submitted_at"].strftime("%Y-%m-%d %H:%M:%S"),
                    "estimated_completion": str(task["estimated_completion_time"])
                } for task in active_tasks.values()
            ],
            "recent_completed": [
                {
                    "id": task["id"],
                    "items_count": task["items_count"],
                    "submitted_at": task["submitted_at"].strftime("%Y-%m-%d %H:%M:%S"),
                    "completed_at": task["completed_at"].strftime("%Y-%m-%d %H:%M:%S") if "completed_at" in task else "",
                    "duration": str(task["completed_at"] - task["submitted_at"]) if "completed_at" in task else ""
                } for task in completed_tasks[-5:]  # 只显示最近5个完成的任务
            ]
        }

def render_queue_status():
    """渲染队列状态UI
    
    Returns:
        str: HTML格式的队列状态显示
    """
    status = get_queue_status()
    
    html = f"""
    <div style="font-family: Arial, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; background: #f9f9f9; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
        <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
            <div style="background: #fff; padding: 15px; border-radius: 8px; width: 30%; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
                <h3 style="margin: 0 0 10px; color: #444; font-size: 16px;">排队任务</h3>
                <p style="font-size: 28px; font-weight: bold; margin: 0; color: #3498db;">{status['queued_tasks']}</p>
            </div>
            <div style="background: #fff; padding: 15px; border-radius: 8px; width: 30%; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
                <h3 style="margin: 0 0 10px; color: #444; font-size: 16px;">处理中任务</h3>
                <p style="font-size: 28px; font-weight: bold; margin: 0; color: #e74c3c;">{status['processing_tasks']}</p>
            </div>
            <div style="background: #fff; padding: 15px; border-radius: 8px; width: 30%; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
                <h3 style="margin: 0 0 10px; color: #444; font-size: 16px;">总项目数</h3>
                <p style="font-size: 28px; font-weight: bold; margin: 0; color: #2ecc71;">{status['total_items']}</p>
            </div>
        </div>
        
        <div style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
            <h2 style="margin: 0 0 15px; color: #333; font-size: 18px;">预计完成时间</h2>
            <div style="display: flex; align-items: center;">
                <div style="font-size: 24px; font-weight: bold; color: #9b59b6;">{status['estimated_completion_time']}</div>
                <div style="margin-left: 10px; color: #777; font-size: 14px;">(小时:分钟:秒)</div>
            </div>
        </div>
        
        <div style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
            <h2 style="margin: 0 0 15px; color: #333; font-size: 18px;">活跃任务</h2>
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f2f2f2;">
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">任务ID</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">状态</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">项目数</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">提交时间</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">预计完成</th>
                    </tr>
                </thead>
                <tbody>
    """
    
    if status['active_tasks']:
        for task in status['active_tasks']:
            status_color = "#3498db" if task['status'] == "queued" else "#e74c3c"
            html += f"""
                    <tr>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['id']}</td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">
                            <span style="padding: 4px 8px; border-radius: 4px; font-size: 12px; background: {status_color}; color: white;">
                                {task['status']}
                            </span>
                        </td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['items_count']}</td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['submitted_at']}</td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['estimated_completion']}</td>
                    </tr>
            """
    else:
        html += f"""
                    <tr>
                        <td colspan="5" style="padding: 15px; text-align: center; color: #777;">当前没有活跃任务</td>
                    </tr>
        """
        
    html += """
                </tbody>
            </table>
        </div>
        
        <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">
            <h2 style="margin: 0 0 15px; color: #333; font-size: 18px;">最近完成的任务</h2>
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f2f2f2;">
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">任务ID</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">项目数</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">提交时间</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">完成时间</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">持续时间</th>
                    </tr>
                </thead>
                <tbody>
    """
    
    if status['recent_completed']:
        for task in status['recent_completed']:
            html += f"""
                    <tr>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['id']}</td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['items_count']}</td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['submitted_at']}</td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['completed_at']}</td>
                        <td style="padding: 12px; border-bottom: 1px solid #eee;">{task['duration']}</td>
                    </tr>
            """
    else:
        html += f"""
                    <tr>
                        <td colspan="5" style="padding: 15px; text-align: center; color: #777;">暂无已完成任务</td>
                    </tr>
        """
        
    html += """
                </tbody>
            </table>
        </div>
    </div>
    """
    
    return html

def refresh_ui():
    """定期刷新UI函数"""
    return render_queue_status()

def submit_json_data(json_data):
    """提交JSON数据处理接口"""
    try:
        # 解析JSON字符串
        if isinstance(json_data, str):
            data = json.loads(json_data)
        else:
            data = json_data
            
        result = submit_task(data)
        response = json.dumps(result, ensure_ascii=False, indent=2)
        
        # 返回任务提交结果和最新的队列状态
        return response, render_queue_status()
    except Exception as e:
        return json.dumps({"status": "error", "message": str(e)}, ensure_ascii=False, indent=2), render_queue_status()

# 创建Gradio接口
with gr.Blocks(title="代码评估服务", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 代码评估服务
    ### 支持多种编程语言的代码评估服务
    """)
    
    with gr.Tab("任务队列状态"):
        status_html = gr.HTML(render_queue_status)
        refresh_button = gr.Button("刷新状态")
        refresh_button.click(fn=refresh_ui, outputs=status_html)
        
        # 使用正确的轮询方式替代
        dummy_input = gr.Textbox(value="", visible=False)
        
        # We'll rely on the JavaScript solution below for auto-refresh
        # The refresh button still works for manual refresh
        
        # JavaScript-based auto-refresh solution
        gr.HTML("""
        <script>
            // 使用JavaScript作为自动刷新机制
            function setupAutoRefresh() {
                const refreshInterval = 2000; // 2秒刷新一次
                
                // 查找刷新按钮并模拟点击
                function autoRefresh() {
                    // 获取所有按钮元素
                    const buttons = document.querySelectorAll('button');
                    // 查找刷新状态按钮
                    for (const button of buttons) {
                        if (button.textContent === '刷新状态') {
                            button.click();
                            break;
                        }
                    }
                }

                // 周期性检查刷新
                setInterval(autoRefresh, refreshInterval);
                
                // 设置首次加载时立即刷新一次
                setTimeout(autoRefresh, 100);
            }
            
            // 页面加载完成后设置自动刷新
            window.addEventListener('load', setupAutoRefresh);
        </script>
        """)
    
    with gr.Tab("提交新任务"):
        with gr.Row():
            with gr.Column():
                json_input = gr.Textbox(
                    label="输入JSON数据",
                    placeholder='[{"language": "python", "prompt": "def add(a, b):\\n", "processed_completions": ["    return a + b"], "tests": "assert add(1, 2) == 3"}]',
                    lines=10
                )
                submit_button = gr.Button("提交任务")
            
            with gr.Column():
                result_output = gr.Textbox(label="提交结果", lines=5)
                
        submit_button.click(fn=submit_json_data, inputs=json_input, outputs=[result_output, status_html])
    
    with gr.Tab("API文档"):
        gr.Markdown("""
        ## API 文档
        
        ### 1. 提交任务
        
        **请求:**
        
        ```
        POST /api/predict
        Content-Type: application/json
        
        [
            {
                "language": "python",
                "prompt": "def add(a, b):\\n",
                "processed_completions": ["    return a + b"],
                "tests": "assert add(1, 2) == 3"
            }
        ]
        ```
        
        **响应:**
        
        ```json
        {
            "status": "success",
            "task_id": "task_1"
        }
        ```
        
        ### 2. 查询任务状态
        
        **请求:**
        
        ```
        GET /api/status
        ```
        
        **响应:**
        
        ```json
        {
            "queued_tasks": 1,
            "processing_tasks": 2,
            "total_tasks": 3,
            "total_items": 15,
            "estimated_completion_time": "0:05:30",
            "active_tasks": [...],
            "recent_completed": [...]
        }
        ```
        """)

    # 添加API端点
    with gr.Row(visible=False):
        api_input = gr.JSON()
        api_output = gr.JSON()
        api_input.change(fn=evaluate, inputs=api_input, outputs=api_output)

if __name__ == "__main__":
    # 打印Gradio版本,用于调试
    import gradio
    print(f"Gradio version: {gradio.__version__}")
    
    # 设置队列,并添加API支持
    demo.queue(api_open=True)
    
    # 启动应用
    demo.launch()