File size: 8,247 Bytes
407f023
87d27b7
 
7efd387
 
87d27b7
99d652f
70977e2
f1b5d20
6569227
99d652f
 
87d27b7
f1b5d20
699f862
 
 
87d27b7
70977e2
99d652f
 
19b9e57
87d27b7
 
 
7efd387
 
 
 
016dad0
7efd387
70977e2
 
 
7efd387
70977e2
 
 
 
 
 
016dad0
 
70977e2
7efd387
70977e2
 
 
 
 
7efd387
70977e2
 
 
7efd387
73410d3
7efd387
70977e2
 
7efd387
 
 
016dad0
 
70977e2
 
016dad0
 
7efd387
 
73410d3
99d652f
7efd387
 
 
 
 
 
73410d3
99d652f
 
 
 
 
 
 
 
 
 
 
 
7efd387
73410d3
70977e2
 
 
7efd387
 
 
 
 
 
 
016dad0
 
 
 
70977e2
7efd387
 
 
 
 
 
 
0013187
73410d3
7efd387
73410d3
7efd387
70977e2
73410d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70977e2
73410d3
7efd387
73410d3
70977e2
7efd387
 
 
 
 
70977e2
 
0013187
016dad0
70977e2
e381aca
70977e2
7efd387
 
 
 
 
70977e2
7efd387
 
 
 
70977e2
 
 
e381aca
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
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
import io
from PIL import Image

# Оценки от 1 до 5
metrics = {
    "Классификация обращений": {
        "ChatGPT": {"Точность": 5, "Интерпретируемость": 4, "Стабильность": 4, "Время отклика": 4, "Применимость": 4},
        "GigaChat": {"Точность": 4, "Интерпретируемость": 3, "Стабильность": 4, "Время отклика": 5, "Применимость": 4},
        "DeepSeek": {"Точность": 3, "Интерпретируемость": 4, "Стабильность": 3, "Время отклика": 4, "Применимость": 4},
    },
    "Антифрод": {
        "ChatGPT": {"Точность": 4, "Интерпретируемость": 3, "Стабильность": 5, "Время отклика": 3, "Применимость": 3},
        "GigaChat": {"Точность": 5, "Интерпретируемость": 4, "Стабильность": 4, "Время отклика": 3, "Применимость": 4},
        "DeepSeek": {"Точность": 3, "Интерпретируемость": 3, "Стабильность": 4, "Время отклика": 5, "Применимость": 4},
    },
    "Генерация SQL": {
        "ChatGPT": {"Точность": 5, "Интерпретируемость": 4, "Стабильность": 4, "Время отклика": 3, "Применимость": 4},
        "GigaChat": {"Точность": 3, "Интерпретируемость": 3, "Стабильность": 3, "Время отклика": 4, "Применимость": 3},
        "DeepSeek": {"Точность": 4, "Интерпретируемость": 3, "Стабильность": 5, "Время отклика": 5, "Применимость": 4},
    }
}

def fig_to_image(fig):
    buf = io.BytesIO()
    fig.savefig(buf, format="png", bbox_inches="tight", dpi=150)
    buf.seek(0)
    return Image.open(buf)

def update(task, selected_criteria):
    models = ["ChatGPT", "GigaChat", "DeepSeek"]
    cards = []

    for model in models:
        vals = metrics[task][model]
        criteria = selected_criteria if selected_criteria else list(vals.keys())
        items_html = ""
        for crit in criteria:
            score = vals[crit]
            desc = "Высокая" if score == 5 else "Средняя" if score >= 3 else "Низкая"
            items_html += f"<li>{crit}: {score}/5 ({desc})</li>"
        card_html = f"""
        <div class="card dark-card">
          <h3>{model}</h3>
          <ul>{items_html}</ul>
        </div>
        """
        cards.append(card_html)

    criteria = selected_criteria if selected_criteria else list(metrics[task][models[0]].keys())
    x = np.arange(len(models))
    width = 0.8 / len(criteria)

    # График 1
    fig1, ax1 = plt.subplots(figsize=(5, 3))
    for i, crit in enumerate(criteria):
        values = [metrics[task][m][crit] for m in models]
        bars = ax1.bar(x + i * width, values, width, label=crit)
        for bar in bars:
            height = bar.get_height()
            ax1.annotate(f'{height}', xy=(bar.get_x() + bar.get_width() / 2, height + 0.15),
                         ha='center', fontsize=9, color='white')
    ax1.set_xticks(x + width*(len(criteria)-1)/2)
    ax1.set_xticklabels(models)
    ax1.set_ylim(0, 5.5)
    ax1.set_ylabel("Оценка (1–5)")
    ax1.set_title(f"Сравнение моделей по критериям\nЗадача: {task}")
    ax1.grid(axis='y', linestyle='--', alpha=0.3)

    # Стили
    fig1.patch.set_facecolor('#1e1e1e')
    ax1.set_facecolor('#1e1e1e')
    ax1.tick_params(colors='white')
    ax1.yaxis.label.set_color('white')
    ax1.xaxis.label.set_color('white')
    ax1.title.set_color('white')

    # Легенда (сверху, вне графика)
    ax1.legend(
        fontsize=8,
        loc='lower center',
        bbox_to_anchor=(0.5, 1.05),
        ncol=3,
        frameon=True
    )
    ax1.legend().get_frame().set_facecolor('#2e2e2e')
    ax1.legend().get_frame().set_edgecolor('#444')
    ax1.xaxis.labelpad = 10
    fig1.subplots_adjust(top=0.85, bottom=0.25)

    # График 2
    avg_scores = []
    for model in models:
        vals = metrics[task][model]
        avg = np.mean([vals[crit] for crit in criteria])
        avg_scores.append(avg)

    fig2, ax2 = plt.subplots(figsize=(5, 3))
    bars = ax2.bar(models, avg_scores, color=['#4c78a8','#f58518','#54a24b'])
    for bar in bars:
        height = bar.get_height()
        ax2.annotate(f'{height:.2f}', xy=(bar.get_x() + bar.get_width() / 2, height + 0.15),
                     ha='center', fontsize=9, color='white')
    ax2.set_ylim(0, 5.5)
    ax2.set_ylabel("Средний балл (1–5)")
    ax2.set_title("Средний балл моделей")
    ax2.grid(axis='y', linestyle='--', alpha=0.3)
    fig2.patch.set_facecolor('#1e1e1e')
    ax2.set_facecolor('#1e1e1e')
    ax2.tick_params(colors='white')
    ax2.yaxis.label.set_color('white')
    ax2.xaxis.label.set_color('white')
    ax2.title.set_color('white')
    ax2.xaxis.labelpad = 10
    fig2.subplots_adjust(bottom=0.25)

    # Лидер в текущей задаче
    sums = {model: sum(metrics[task][model][crit] for crit in criteria) for model in models}
    leader = max(sums, key=sums.get)
    result = f"### 📌 <span style='font-size: 18px;'>**Модель `{leader}` лидирует** по выбранным критериям в задаче **{task}**.</span>"

    # Общий анализ по всем задачам
    model_scores = {model: [] for model in models}
    for tsk in metrics:
        for model in models:
            vals = metrics[tsk][model]
            selected = selected_criteria if selected_criteria else vals.keys()
            model_scores[model].extend([vals[c] for c in selected])

    avg_all = {model: round(np.mean(scores), 2) for model, scores in model_scores.items()}
    overall_leader = max(avg_all, key=avg_all.get)

    analysis_text = f"""
<br><br>
### 🔎 <span style='font-size: 17px;'>**Общий анализ моделей:**</span>

- ChatGPT — средняя оценка: **{avg_all["ChatGPT"]}/5**  
- GigaChat — средняя оценка: **{avg_all["GigaChat"]}/5**  
- DeepSeek — средняя оценка: **{avg_all["DeepSeek"]}/5**

📊 <span style='font-size: 18px;'>**Лидирует модель `{overall_leader}`** по суммарным показателям в выбранных задачах.</span>
"""

    return cards[0], cards[1], cards[2], fig_to_image(fig1), fig_to_image(fig2), result + analysis_text

# CSS
css = """
.gradio-container { font-family: Arial, sans-serif; background-color: #181818; color: white; }
.card.dark-card { background: #2e2e2e; border-radius: 8px; padding: 10px; margin: 10px; }
.card.dark-card h3 { text-align: center; color: #fff; margin-bottom: 6px; }
.card.dark-card ul { list-style: none; padding-left: 0; color: #ddd; font-size: 14px; }
.card.dark-card li { margin: 4px 0; }
"""

# Интерфейс
with gr.Blocks(css=css) as demo:
    gr.Markdown("## Сравнение моделей ChatGPT, GigaChat и DeepSeek", elem_id="title")
    with gr.Row():
        with gr.Column(scale=2):
            task_dropdown = gr.Dropdown(label="Выбор задачи", choices=list(metrics.keys()), value="Классификация обращений")
            criteria_check = gr.CheckboxGroup(label="Фильтр критериев", choices=list(next(iter(metrics.values()))["ChatGPT"].keys()))
        card1 = gr.HTML()
        card2 = gr.HTML()
        card3 = gr.HTML()
    with gr.Row():
        chart1 = gr.Image(label="Сравнение по критериям", interactive=True)
        chart2 = gr.Image(label="Средний балл", interactive=True)
    result_md = gr.Markdown()

    task_dropdown.change(update, [task_dropdown, criteria_check], [card1, card2, card3, chart1, chart2, result_md])
    criteria_check.change(update, [task_dropdown, criteria_check], [card1, card2, card3, chart1, chart2, result_md])

demo.launch()