Spaces:
Sleeping
Sleeping
File size: 40,352 Bytes
f887c3b b8a0ce6 f887c3b b3d0315 b8a0ce6 35baab0 1998bf9 21d9d90 35baab0 1998bf9 f887c3b 1998bf9 b8a0ce6 e3e08aa e5d56ba e222380 e5d56ba e222380 e5d56ba e222380 e5d56ba e222380 e3e08aa e5d56ba b8a0ce6 b58538e 1537fc2 b58538e 1537fc2 b58538e f887c3b b8a0ce6 1998bf9 f887c3b b8a0ce6 5cb1e0a dfe914d 5cb1e0a b8a0ce6 77b3744 b8a0ce6 f887c3b b8a0ce6 d9cf01d 1998bf9 d9cf01d 26db7b2 d9cf01d 1998bf9 d9cf01d b883b46 d9cf01d 70e53f6 d9cf01d 70e53f6 f887c3b d9cf01d 70e53f6 d9cf01d 7e90033 bad2aa8 cf740ad 7e90033 cf740ad 7e90033 8629493 4ef5948 8629493 8c3d5de 4ef5948 8629493 b8a0ce6 8c3d5de 4ef5948 b8a0ce6 7e90033 8629493 75218ae 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 7acc3c0 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 7e90033 b8a0ce6 9418d97 b8a0ce6 7e90033 f887c3b 7e90033 35baab0 1998bf9 b8a0ce6 35baab0 1998bf9 35baab0 b8a0ce6 35baab0 b8a0ce6 35baab0 b8a0ce6 1537fc2 b8a0ce6 b58538e b8a0ce6 6b502be b3d0315 b8a0ce6 8d3bc4d 940f97c 8d3bc4d b8a0ce6 f887c3b 1998bf9 b8a0ce6 fa62f4d b8a0ce6 1998bf9 b8a0ce6 1998bf9 b8a0ce6 1998bf9 b8a0ce6 a6e97ea b8a0ce6 b58538e 35baab0 b8a0ce6 35baab0 b8a0ce6 adbeedd b3d0315 661d369 b3d0315 661d369 b3d0315 661d369 d0d268e 661d369 d0d268e bb44f5d d0d268e bb44f5d d0d268e 940f97c df060ae 4e3b4cd ba1206a b3d0315 df060ae b3d0315 1a8524b 8d3bc4d b3d0315 d0d268e b3d0315 d0d268e 1a8524b b3d0315 940f97c 1998bf9 e8dd5e9 1998bf9 e8dd5e9 1998bf9 e8dd5e9 1998bf9 e8dd5e9 1998bf9 eb27961 b8a0ce6 3db8ccb eb27961 8b8350c a91640a b68e368 a91640a 8b8350c eb27961 8b8350c eb27961 8b8350c 3db8ccb b8a0ce6 eb27961 b8a0ce6 ec4eb40 b8a0ce6 1998bf9 b8a0ce6 1998bf9 b8a0ce6 26db7b2 b8a0ce6 35baab0 1998bf9 b8a0ce6 26db7b2 b8a0ce6 ec4eb40 26db7b2 1998bf9 1537fc2 f887c3b |
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 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 |
import gradio as gr
import pandas as pd
import json
import plotly.express as px
import requests
import os
from textblob.download_corpora import download_all
from highlight_util import highlight_adjectives
from send_file import send_to_backend
# 下载TextBlob所需数据(只需运行一次)
download_all()
def on_confirm(task_type_radio,dataset_radio, num_parts_dropdown, perspective_radio, division_method_radio):
num_parts = num_parts_dropdown
method = "QS" if division_method_radio == "Equal Frequency Partitioning" else "EI"
base_path = f"./dataset/{task_type_radio}/{dataset_radio}"
analysis_result,_ = load_analysis_report(task_type_radio,dataset_radio, num_parts_dropdown, perspective_radio, division_method_radio)
# 根据perspective选择读取对应的文件
if task_type_radio=="Api Recommendation":
if "Tokens" in perspective_radio and "Recall" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/recall/token_counts_{method}.csv")
elif "Tokens" in perspective_radio and "F1" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/f1/token_counts_{method}.csv")
elif "Lines" in perspective_radio and "Recall" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/recall/line_counts_{method}.csv")
elif "Lines" in perspective_radio and "f1" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/f1/line_counts_{method}.csv")
elif task_type_radio=="Code Completion":
if "Tokens" in perspective_radio :
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/token_counts_{method}.csv")
elif "Lines" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/line_counts_{method}.csv")
elif task_type_radio=="Test Generation":
if "Tokens" in perspective_radio :
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/token_counts_{method}.csv")
elif "Lines" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/line_counts_{method}.csv")
else:
if "Tokens" in perspective_radio :
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/token_counts_{method}.csv")
elif "Lines" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/line_counts_{method}.csv")
elif "Complexity" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/CC_{method}.csv")
elif "Problem Types" in perspective_radio:
df = pd.read_csv(f"{base_path}/cata_result.csv")
# 加载分析报告
# AI分析列
# df["Analysis"] = df["Model"].map(lambda m: analysis_result.get(m, "No analysis provided."))
df["Analysis"] = df["Model"].map(
lambda m: highlight_adjectives(analysis_result.get(m, "No analysis provided."))
)
return df
# 生成 CSS 样式
def generate_css(line_counts, token_counts, cyclomatic_complexity, problem_type, show_high, show_medium, show_low):
css = """
#dataframe th {
background-color: #f2f2f2
}
"""
colors = ["#e6f7ff", "#ffeecc", "#e6ffe6", "#ffe6e6"]
categories = [line_counts, token_counts, cyclomatic_complexity]
category_index = 0
column_index = 1
for category in categories:
if category:
if show_high:
css += f"#dataframe td:nth-child({column_index + 1}) {{ background-color: {colors[category_index]}; }}\n"
column_index += 1
if show_medium:
css += f"#dataframe td:nth-child({column_index + 1}) {{ background-color: {colors[category_index]}; }}\n"
column_index += 1
if show_low:
css += f"#dataframe td:nth-child({column_index + 1}) {{ background-color: {colors[category_index]}; }}\n"
column_index += 1
category_index += 1
# 为 Problem Type 相关的三个子列设置固定颜色
if problem_type:
problem_type_color = "#d4f0fc" # 你可以选择任何你喜欢的颜色
css += f"#dataframe td:nth-child({column_index + 1}) {{ background-color: {problem_type_color}; }}\n"
css += f"#dataframe td:nth-child({column_index + 2}) {{ background-color: {problem_type_color}; }}\n"
css += f"#dataframe td:nth-child({column_index + 3}) {{ background-color: {problem_type_color}; }}\n"
# 隐藏 "data" 标识
css += """
.gradio-container .dataframe-container::before {
content: none !important;
}
"""
return css
# AI分析
def load_analysis_report(task_type_radio,dataset_radio, num_parts_dropdown, perspective_radio, division_method_radio):
num_parts = num_parts_dropdown
method = "QS" if division_method_radio == "Equal Frequency Partitioning" else "EI"
# # 根据perspective确定文件路径
# if "Tokens" in perspective_radio:
# perspective = "token_counts"
# elif "Lines" in perspective_radio:
# perspective = "line_counts"
# elif "Complexity" in perspective_radio:
# perspective = "CC"
# else:
# perspective = "problem_type"
# base_path = f"./llm_insight/{task_type_radio}"
# if perspective == "problem_type":
# report_file = f"{base_path}/{dataset_radio}/{perspective}_report.json"
# recommendation_file = f"{base_path}/{dataset_radio}/{perspective}_recommendation.json"
# else:
# report_file = f"{base_path}/{dataset_radio}/{num_parts}/{method}/{perspective}_report.json"
# recommendation_file = f"{base_path}/{dataset_radio}/{num_parts}/{method}/{perspective}_recommendation.json"
base_path = f"./llm_insight/{task_type_radio}"
if task_type_radio=="Code Generation":
# 根据perspective确定文件路径
if "Tokens" in perspective_radio:
perspective = "token_counts"
elif "Lines" in perspective_radio:
perspective = "line_counts"
elif "Complexity" in perspective_radio:
perspective = "CC"
else:
perspective = "problem_type"
if perspective == "problem_type":
report_file = f"{base_path}/{dataset_radio}/{perspective}_report.json"
recommendation_file = f"{base_path}/{dataset_radio}/{perspective}_recommendation.json"
else:
report_file = f"{base_path}/{dataset_radio}/{num_parts}/{method}/{perspective}_report.json"
recommendation_file = f"{base_path}/{dataset_radio}/{num_parts}/{method}/{perspective}_recommendation.json"
else:
report_file = f"{base_path}/{dataset_radio}/report.json"
recommendation_file = f"{base_path}/{dataset_radio}/recommendation.json"
try:
with open(report_file, 'r', encoding='utf-8') as f:
analysis_result = json.load(f)
except Exception as e:
analysis_result = f"[Error] error load analysis report: {e}"
try:
with open(recommendation_file, 'r', encoding='utf-8') as f:
recommendation_result = json.load(f)
except Exception as e:
recommendation_result = f"[Error] error load model recommendation: {e}"
return (analysis_result,recommendation_result)
# 可视化
# def plot_visualization(task_type_radio,dataset_radio, perspective_radio, num_parts, plot_type):
# base_path = f"./dataset/{task_type_radio}/{dataset_radio}"
# if "Tokens" in perspective_radio:
# file_path = f'{base_path}/{num_parts}/QS/token_counts_QS.csv'
# elif "Lines" in perspective_radio:
# file_path = f'{base_path}/{num_parts}/QS/line_counts_QS.csv'
# elif "Complexity" in perspective_radio:
# file_path = f'{base_path}/{num_parts}/QS/CC_QS.csv'
# else: # Problem Types
# file_path = f'{base_path}/cata_result.csv'
# df = pd.read_csv(file_path)
# df.set_index('Model', inplace=True)
# df_transposed = df.T
# if plot_type == "Line Chart":
# fig = px.line(df_transposed,
# x=df_transposed.index,
# y=df_transposed.columns,
# title='Model Performance Across Different Subsets',
# labels={'value': 'Evaluation Score', 'index': 'Subsets'},
# color_discrete_sequence=px.colors.qualitative.Plotly)
# fig.update_traces(hovertemplate='%{y}')
# elif plot_type == "Radar Chart": # Radar Chart
# # 重新组织数据为雷达图所需格式
# radar_data = []
# for model in df.index:
# for subset, score in df.loc[model].items():
# radar_data.append({
# 'Model': model,
# 'Subset': subset,
# 'Score': score
# })
# radar_df = pd.DataFrame(radar_data)
# colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
# # 创建雷达图
# fig = px.line_polar(radar_df,
# r='Score',
# theta='Subset',
# color='Model',
# line_close=True,
# color_discrete_sequence=colors,
# title='Model Performance Radar Chart')
# # 自定义每个模型的线条样式
# for i, trace in enumerate(fig.data):
# trace.update(
# fill=None, # 移除填充
# line=dict(
# width=2,
# dash='solid' if i % 2 == 0 else 'dash', # 交替使用实线和虚线
# )
# )
# # 优化雷达图的显示
# fig.update_layout(
# polar=dict(
# radialaxis=dict(
# visible=True,
# range=[0, 100],
# showline=True,
# linewidth=1,
# gridcolor='lightgrey'
# ),
# angularaxis=dict(
# showline=True,
# linewidth=1,
# gridcolor='lightgrey'
# )
# ),
# showlegend=True,
# legend=dict(
# yanchor="middle", # 垂直居中
# y=0.5,
# xanchor="left",
# x=1.2, # 将图例移到雷达图右侧
# bgcolor="rgba(255, 255, 255, 0.8)", # 半透明白色背景
# bordercolor="lightgrey", # 添加边框
# borderwidth=1
# ),
# margin=dict(r=150), # 增加右侧边距,为图例留出空间
# paper_bgcolor='white'
# )
# else: # Heatmap
# # 创建热力图
# fig = px.imshow(df_transposed,
# labels=dict(x="Model", y="Subset", color="Score"),
# color_continuous_scale="RdYlBu_r", # 使用科研风格配色:红-黄-蓝
# aspect="auto", # 自动调整宽高比
# title="Model Performance Heatmap")
# # 优化热力图显示
# fig.update_layout(
# title=dict(
# text='Model Performance Distribution Across Subsets',
# x=0.5,
# y=0.95,
# xanchor='center',
# yanchor='top',
# font=dict(size=14)
# ),
# xaxis=dict(
# title="Model",
# tickangle=45, # 斜着显示模型名称
# tickfont=dict(size=10),
# side="bottom"
# ),
# yaxis=dict(
# title="Subset",
# tickfont=dict(size=10)
# ),
# coloraxis=dict(
# colorbar=dict(
# title="Score",
# titleside="right",
# tickfont=dict(size=10),
# titlefont=dict(size=12),
# len=0.9, # 色条长度
# )
# ),
# margin=dict(t=80, r=100, b=80, l=80), # 调整边距
# paper_bgcolor='white',
# plot_bgcolor='white'
# )
# # 添加具体数值标注
# annotations = []
# for i in range(len(df_transposed.index)):
# for j in range(len(df_transposed.columns)):
# annotations.append(
# dict(
# x=j,
# y=i,
# text=f"{df_transposed.iloc[i, j]:.1f}",
# showarrow=False,
# font=dict(size=9, color='black')
# )
# )
# fig.update_layout(annotations=annotations)
# return fig
def plot_visualization(task_type_radio,dataset_radio, num_parts_dropdown, perspective_radio, division_method_radio,plot_type):
# base_path = f"./dataset/{task_type_radio}/{dataset_radio}"
# if "Tokens" in perspective_radio:
# file_path = f'{base_path}/{num_parts}/QS/token_counts_QS.csv'
# elif "Lines" in perspective_radio:
# file_path = f'{base_path}/{num_parts}/QS/line_counts_QS.csv'
# elif "Complexity" in perspective_radio:
# file_path = f'{base_path}/{num_parts}/QS/CC_QS.csv'
# else: # Problem Types
# file_path = f'{base_path}/cata_result.csv'
num_parts = num_parts_dropdown
method = "QS" if division_method_radio == "Equal Frequency Partitioning" else "EI"
base_path = f"./dataset/{task_type_radio}/{dataset_radio}"
analysis_result,_ = load_analysis_report(task_type_radio,dataset_radio, num_parts_dropdown, perspective_radio, division_method_radio)
# 根据perspective选择读取对应的文件
if task_type_radio=="Api Recommendation":
if "Tokens" in perspective_radio and "Recall" in perspective_radio:
print(f"{base_path}/{num_parts}/{method}/recall/token_counts_{method}.csv")
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/recall/token_counts_{method}.csv")
print(df)
elif "Tokens" in perspective_radio and "F1" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/f1/token_counts_{method}.csv")
elif "Lines" in perspective_radio and "Recall" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/recall/line_counts_{method}.csv")
elif "Lines" in perspective_radio and "f1" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/f1/line_counts_{method}.csv")
elif task_type_radio=="Code Completion":
if "Tokens" in perspective_radio :
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/token_counts_{method}.csv")
elif "Lines" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/line_counts_{method}.csv")
elif task_type_radio=="Test Generation":
if "Tokens" in perspective_radio :
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/token_counts_{method}.csv")
elif "Lines" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/line_counts_{method}.csv")
else:
if "Tokens" in perspective_radio :
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/token_counts_{method}.csv")
print(df)
elif "Lines" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/line_counts_{method}.csv")
elif "Complexity" in perspective_radio:
df = pd.read_csv(f"{base_path}/{num_parts}/{method}/CC_{method}.csv")
elif "Problem Types" in perspective_radio:
df = pd.read_csv(f"{base_path}/cata_result.csv")
if task_type_radio == "Code Generation":
df.set_index('Model', inplace=True)
df_transposed = df.T
model_column_name = 'Model' # Store the column name for later use
else:
df.set_index('Models', inplace=True)
df_transposed = df.T
model_column_name = 'Models' # Store the column name for later use
if plot_type == "Line Chart" and task_type_radio=="Api Recommendation":
df_melted = df_transposed.reset_index().melt(
id_vars="index", # 保留subset列(原列名)
var_name=model_column_name, # 模型列名
value_name="Score" # 分数列
)
fig = px.line(df_transposed,
x=df_transposed.index,
y=df_transposed.columns,
title='Model Performance Across Different Subsets',
labels={'value': 'Evaluation Score', 'index': 'Subsets'},
color_discrete_sequence=px.colors.qualitative.Plotly
)
fig.update_traces(hovertemplate='%{y}')
if plot_type == "Line Chart" and task_type_radio!="Api Recommendation":
fig = px.line(df_transposed,
x=df_transposed.index,
y=df_transposed.columns,
title='Model Performance Across Different Subsets',
labels={'value': 'Evaluation Score', 'index': 'Subsets'},
color_discrete_sequence=px.colors.qualitative.Plotly
)
fig.update_traces(hovertemplate='%{y}')
if plot_type == "Radar Chart":
# Reorganize data for radar chart
radar_data = []
for model in df.index:
for subset, score in df.loc[model].items():
radar_data.append({
model_column_name: model, # Use the stored column name
'Subset': subset,
'Score': score
})
radar_df = pd.DataFrame(radar_data)
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
# Create radar chart
fig = px.line_polar(radar_df,
r='Score',
theta='Subset',
color=model_column_name, # Use the stored column name
line_close=True,
color_discrete_sequence=colors,
title='Model Performance Radar Chart')
# Customize line styles for each model
for i, trace in enumerate(fig.data):
trace.update(
fill=None, # Remove fill
line=dict(
width=2,
dash='solid' if i % 2 == 0 else 'dash', # Alternate solid and dashed lines
)
)
# Optimize radar chart display
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 100],
showline=True,
linewidth=1,
gridcolor='lightgrey'
),
angularaxis=dict(
showline=True,
linewidth=1,
gridcolor='lightgrey'
)
),
showlegend=True,
legend=dict(
yanchor="middle",
y=0.5,
xanchor="left",
x=1.2,
bgcolor="rgba(255, 255, 255, 0.8)",
bordercolor="lightgrey",
borderwidth=1
),
margin=dict(r=150),
paper_bgcolor='white'
)
if plot_type == "Radar Chart":
# Reorganize data for radar chart
radar_data = []
for model in df.index:
for subset, score in df.loc[model].items():
radar_data.append({
model_column_name: model, # Use the stored column name
'Subset': subset,
'Score': score
})
radar_df = pd.DataFrame(radar_data)
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
# Create radar chart
fig = px.line_polar(radar_df,
r='Score',
theta='Subset',
color=model_column_name, # Use the stored column name
line_close=True,
color_discrete_sequence=colors,
title='Model Performance Radar Chart')
# Customize line styles for each model
for i, trace in enumerate(fig.data):
trace.update(
fill=None, # Remove fill
line=dict(
width=2,
dash='solid' if i % 2 == 0 else 'dash', # Alternate solid and dashed lines
)
)
# Optimize radar chart display
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 100],
showline=True,
linewidth=1,
gridcolor='lightgrey'
),
angularaxis=dict(
showline=True,
linewidth=1,
gridcolor='lightgrey'
)
),
showlegend=True,
legend=dict(
yanchor="middle",
y=0.5,
xanchor="left",
x=1.2,
bgcolor="rgba(255, 255, 255, 0.8)",
bordercolor="lightgrey",
borderwidth=1
),
margin=dict(r=150),
paper_bgcolor='white'
)
if plot_type == "Heatmap":
# Create heatmap
fig = px.imshow(df_transposed,
labels=dict(x=model_column_name, y="Subset", color="Score"), # Use stored column name
color_continuous_scale="RdYlBu_r",
aspect="auto",
title="Model Performance Heatmap")
# Optimize heatmap display
fig.update_layout(
title=dict(
text='Model Performance Distribution Across Subsets',
x=0.5,
y=0.95,
xanchor='center',
yanchor='top',
font=dict(size=14)
),
xaxis=dict(
title=model_column_name, # Use stored column name
tickangle=45,
tickfont=dict(size=10),
side="bottom"
),
yaxis=dict(
title="Subset",
tickfont=dict(size=10)
),
coloraxis=dict(
colorbar=dict(
title="Score",
titleside="right",
tickfont=dict(size=10),
titlefont=dict(size=12),
len=0.9,
)
),
margin=dict(t=80, r=100, b=80, l=80),
paper_bgcolor='white',
plot_bgcolor='white'
)
# Add value annotations
annotations = []
for i in range(len(df_transposed.index)):
for j in range(len(df_transposed.columns)):
annotations.append(
dict(
x=j,
y=i,
text=f"{df_transposed.iloc[i, j]:.1f}",
showarrow=False,
font=dict(size=9, color='black')
)
)
fig.update_layout(annotations=annotations)
return fig
# 桑基图展示推荐模型
def plot_recommendation_sankey(task_type_radio,dataset_radio, num_parts_dropdown, perspective_radio, division_method_radio):
import plotly.graph_objects as go
from plotly.colors import sample_colorscale
_, recommendation_result = load_analysis_report(task_type_radio,dataset_radio, num_parts_dropdown, perspective_radio, division_method_radio)
# 定义节点层级和颜色方案
levels = ['Model Recommendation', 'Scenario', 'Model Family', 'Specific Model']
color_scale = "RdYlBu_r"
# 节点和连接数据
node_labels = [levels[0]] # 根节点
customdata = ["Root node"]
sources, targets, values = [], [], []
# 节点索引跟踪
node_indices = {levels[0]: 0}
current_idx = 1
# 处理推荐列表结构 {"场景1": [ {模型1:原因1}, {模型2:原因2} ], ...}
for scenario, model_dicts in recommendation_result.items():
# 添加场景节点
scenario_label = " ".join(scenario.split()[:3]) + ("..." if len(scenario.split()) > 3 else "")
node_labels.append(scenario_label)
customdata.append(scenario)
node_indices[f"scenario_{scenario}"] = current_idx
current_idx += 1
# 根节点 -> 场景节点连接
sources.append(0)
targets.append(node_indices[f"scenario_{scenario}"])
values.append(10)
# 处理模型列表 [ {模型1:原因1}, {模型2:原因2} ]
for model_dict in model_dicts:
for model, reason in model_dict.items():
# 提取模型系列 (如"GPT-4" -> "GPT")
family = model.split('-')[0].split('_')[0]
# 添加模型系列节点 (如果不存在)
if f"family_{family}" not in node_indices:
node_labels.append(family)
customdata.append(f"Model family: {family}")
node_indices[f"family_{family}"] = current_idx
current_idx += 1
# 场景 -> 模型系列连接
sources.append(node_indices[f"scenario_{scenario}"])
targets.append(node_indices[f"family_{family}"])
values.append(8)
# 添加具体模型节点 (如果不存在)
if f"model_{model}" not in node_indices:
node_labels.append(model)
customdata.append(f"<b>{model}</b><br>{reason}")
node_indices[f"model_{model}"] = current_idx
current_idx += 1
# 模型系列 -> 具体模型连接
sources.append(node_indices[f"family_{family}"])
targets.append(node_indices[f"model_{model}"])
values.append(5)
# 生成颜色 (确保颜色数量匹配节点数量)
node_colors = ["#2c7bb6"] # 根节点颜色
node_colors += sample_colorscale(color_scale, [n/(len(node_labels)-1) for n in range(1, len(node_labels))])
# 创建桑基图
fig = go.Figure(go.Sankey(
arrangement="perpendicular",
node=dict(
pad=20,
thickness=15,
line=dict(color="rgba(0,0,0,0.3)", width=0.2),
label=node_labels,
color=node_colors,
hovertemplate='%{label}<extra></extra>',
x=[0] + [0.33]*len([n for n in node_indices if n.startswith('scenario_')])
+ [0.66]*len([n for n in node_indices if n.startswith('family_')])
+ [1.0]*len([n for n in node_indices if n.startswith('model_')]),
),
link=dict(
source=sources,
target=targets,
value=values,
color="rgba(180,180,180,0.4)",
customdata=[customdata[t] for t in targets],
hovertemplate='%{customdata}<extra></extra>'
)
))
fig.update_layout(
title_text="<b>Model Recommendation Flow</b>",
font_size=11,
height=700,
margin=dict(t=80, l=20, r=20, b=20)
)
return fig
### Gradio代码部分 ###
# 自定义 CSS 样式
custom_css = """
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f9f9f9;
}
.gr-label {
font-size: 15px;
}
.gr-button-primary {
background-color: #4CAF50;
color: white;
border-radius: 8px;
}
.gr-tabs > .tab-nav {
background-color: #e0e0e0;
border-bottom: 2px solid #ccc;
}
.gr-tabs > .tab-nav button.selected {
background-color: #ffffff !important;
border-bottom: 2px solid #4CAF50;
}
.gr-panel {
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
background-color: #fff;
}
.markdown-title {
font-size: 1.5em;
font-weight: bold;
margin-bottom: 10px;
}
.analysis-box {
background-color: #f1f8ff;
padding: 20px;
border-left: 5px solid #4CAF50;
border-radius: 6px;
margin-top: 10px;
}
.recommendation-box {
background-color: #fff3cd;
padding: 20px;
border-left: 5px solid #ff9800;
border-radius: 6px;
margin-top: 10px;
}
</style>
"""
SERVER_URL = "http://10.249.190.53:8000/upload"
# 构建界面
def update_dataset(task):
if task == "Code Generation":
return gr.update(choices=["HumanEval", "MBPP"])
elif task== "Code Completion":
return gr.update(choices=["ComplexCodeEval-Python","ComplexCodeEval-Java"])
elif task == "Api Recommendation":
return gr.update(choices=["ComplexCodeEval-Python","ComplexCodeEval-Java"])
elif task == "Test Generation":
return gr.update(choices=["ComplexCodeEval-Python","ComplexCodeEval-Java"])
with gr.Blocks(css=custom_css) as iface:
gr.HTML("""
<div style='text-align:center; padding:5px;'>
<h1>Multi-view Code LLM Leaderboard</h1>
<p>Multi-view Leaderboard: Towards Evaluating the Code Intelligence of LLMs From Multiple Views</p>
</div>
""")
with gr.Row():
# 配置相关
with gr.Column(scale=1):
task_type_radio = gr.Radio(
["Code Generation", "Code Completion", "Api Recommendation", "Test Generation"],
label="Select Task Type",
value="Code Generation"
)
dataset_radio = gr.Radio(
["HumanEval", "MBPP",'ComplexCodeEval'],
label="Select a dataset",
value="HumanEval"
)
num_parts_slider = gr.Slider(
minimum=3,
maximum=8,
step=1,
label="Choose the Number of Subsets",
value=3
)
# 将多个checkbox改为一个radio
perspective_radio = gr.Radio(
["I - Num of Tokens in Problem Desc",
"II - Num of Lines in Problem Desc",
"III - Complexity of Reference Code",
"IV - Problem Types"],
label="Choose Perspective",
value="I - Num of Tokens in Problem Desc"
)
# 统一的division method radio
division_method_radio = gr.Radio(
["Equal Frequency Partitioning", "Equal Interval Partitioning"],
label="Choose the Division Method",
visible=True
)
confirm_btn = gr.Button("Confirm", variant="primary")
# 核心展示
with gr.Column(scale=2):
with gr.Tabs():
# 表格
with gr.TabItem("Ranking Table"):
data_table = gr.Dataframe(headers=["Model", "Score","Analysis"],
interactive=True,
datatype="html", # 指定第三列为HTML
render=True, # 启用HTML渲染
)
# 可视化
with gr.TabItem("Visualization"):
plot_type = gr.Radio(
choices=["Line Chart", "Radar Chart","Heatmap"],
label="Select Plot Type",
value="Line Chart"
)
chart = gr.Plot()
# AI分析
with gr.TabItem("Model selection suggestions"):
with gr.Column():
# gr.Markdown("<h2 class='markdown-title'>🎯 Model Recommendation</h2>")
recommendation_plot = gr.Plot()
# #*********************上传文件界面布局******************
# with gr.TabItem("Upload inference result"):
# print("new!!!!!!!!!!!!!!!!")
# with gr.Column(scale=1):
# upload_file = gr.File(
# label="📤 上传JSON结果文件",
# type="filepath",
# file_types=[".json"],
# height=100
# )
# task_choice = gr.Radio(
# label="Select Evaluation Task",
# choices=["Code Generation", "Code Completion", "Api Recommendation", "Test Generation"],
# value="Code Generation"
# )
# dataset_choice = gr.Radio(
# ["HumanEval", "MBPP"],
# label="Select a dataset",
# value="HumanEval",
# interactive=True
# )
# task_choice.change(fn=update_dataset, inputs=task_choice, outputs=dataset_choice)
# with gr.Column(scale=2):
# # 状态显示区域
# status = gr.Textbox(
# label="📊 处理状态",
# interactive=False,
# lines=4,
# placeholder="等待文件上传..."
# )
# # 操作按钮区域
# with gr.Row():
# submit_btn = gr.Button("🚀 提交到服务器", variant="primary")
# clear_btn = gr.Button("🧹 清除所有")
# 按钮动作
# submit_btn.click(
# fn=send_to_backend,
# inputs=[upload_file, task_choice, dataset_choice],
# outputs=status
# )
# clear_btn.click(
# fn=lambda: (None, "Code Generation", "HumanEval", "状态已重置"),
# inputs=None,
# outputs=[upload_file, task_choice, dataset_choice, status]
# )
# with gr.Column(scale=2):
# status = gr.Textbox(label="Status")
# submit_btn = gr.Button("Send to Server")
# submit_btn.click(fn=send_to_backend,
# inputs=[upload_file,task_choice, dataset_choice],
# outputs=status
# )
# 根据任务类型切换数据集
def update_dataset_options(task_type):
if task_type == "Code Generation":
return gr.update(choices=["HumanEval", "MBPP"])
elif task_type == "Code Completion":
return gr.update(choices=["ComplexCodeEval-Python","ComplexCodeEval-Java"])
elif task_type == "Api Recommendation":
return gr.update(choices=["ComplexCodeEval-Python","ComplexCodeEval-Java"])
elif task_type == "Test Generation":
return gr.update(choices=["ComplexCodeEval-Python","ComplexCodeEval-Java"])
# 根据数据集切换拆分角度
def update_perspective_options(task,dataset):
if dataset == "MBPP":
return gr.update(choices=[
"I - Num of Tokens in Problem Desc",
"III - Complexity of Reference Code",
"IV - Problem Types"
])
elif dataset =="HumanEval":
return gr.update(choices=[
"I - Num of Tokens in Problem Desc",
"II - Num of Lines in Problem Desc",
"III - Complexity of Reference Code",
"IV - Problem Types"
])
elif task == "Api Recommendation":
return gr.update(choices=[
"I - Num of Tokens in Problem Desc(Eval Metric:Recall)",
"II - Num of Tokens in Problem Desc(Eval Metric:F1)",
"III - Num of Lines in Problem Desc(Eval Metric:Recall)",
"IV - Num of Lines in Problem Desc(Eval Metric:f1)"
])
elif task == "Code Completion" or "Test Generation":
return gr.update(choices=[
"I - Num of Tokens in Problem Desc(Eval Metric:ES)",
"II - Num of Lines in Problem Desc(Eval Metric:ES)"
])
dataset_radio.change(
fn=update_perspective_options,
inputs=[task_type_radio,dataset_radio],
outputs=perspective_radio
)
# 绑定事件
# confirm_btn.click(
# fn=on_confirm,
# inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio],
# outputs=data_table
# ).then(
# fn=load_analysis_report,
# inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio],
# outputs=[gr.State()]
# ).then(
# fn=plot_visualization,
# inputs=[task_type_radio,dataset_radio, perspective_radio, num_parts_slider, plot_type],
# outputs=chart
# ).then(
# fn=plot_recommendation_sankey,
# inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio],
# outputs=[recommendation_plot] # 注意这里是列表
# )
confirm_btn.click(
fn=on_confirm,
inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio],
outputs=data_table
).then(
fn=load_analysis_report,
inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio],
outputs=[gr.State()]
).then(
fn=plot_visualization,
inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio,plot_type],
outputs=chart
).then(
fn=plot_recommendation_sankey,
inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio],
outputs=[recommendation_plot] # 注意这里是列表
)
plot_type.change(
fn=plot_visualization,
inputs=[task_type_radio,dataset_radio, num_parts_slider, perspective_radio, division_method_radio,plot_type],
outputs=chart
)
# plot_type.change(
# fn=plot_visualization,
# inputs=[task_type_radio,dataset_radio, perspective_radio, num_parts_slider, plot_type],
# outputs=chart
# )
task_type_radio.change(
fn=update_dataset_options,
inputs=task_type_radio,
outputs=dataset_radio
)
# 启动界面
iface.launch() |