FrostIce commited on
Commit
14305c6
·
verified ·
1 Parent(s): ff50948

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -133
app.py CHANGED
@@ -1,149 +1,77 @@
 
1
  import gradio as gr
2
- import random
3
- import g4f
4
 
5
- # Список доступных моделей (для примера)
6
- AVAILABLE_MODELS = [
7
- "gpt-3.5-turbo",
8
- "gpt-4",
9
- "claude-3-opus",
10
- "llama-2-70b",
11
- "mixtral-8x7b"
12
- ]
13
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- def generate_with_model(model_name, prompt):
16
  try:
17
- response = g4f.ChatCompletion.create(
18
- model=model_name,
19
- messages=[{"role": "user", "content": prompt}],
20
  )
21
- return response
22
  except Exception as e:
23
- return f"Ошибка генерации: {str(e)}"
24
- def generate_response(prompt, selected_model):
25
- """Генерация ответа выбранной моделью"""
26
- if not prompt:
27
- return "Введите запрос для генерации"
28
-
29
- # Здесь будет реальная интеграция с g4f
30
- # response = g4f.ChatCompletion.create(
31
- # model=selected_model,
32
- # messages=[{"role": "user", "content": prompt}]
33
- # )
34
-
35
- # Заглушка для демонстрации
36
- response = generate_with_model(selected_model, prompt)
37
- return response
38
 
39
- def clear_all():
40
- """Очистка всех полей"""
41
- return "", "", "", ""
42
 
43
- def random_generate(prompt):
44
- """Генерация случайной моделью"""
45
- random_model = random.choice(AVAILABLE_MODELS)
46
- response = generate_with_model(random_model, prompt)
47
- return random_model, response, response, ""
48
 
49
- def vote_for_best(response1, response2, vote):
50
- """Оценка лучшего ответа"""
51
- if not vote:
52
- return "Пожалуйста, выберите какой ответ лучше"
53
- return f"Спасибо за оценку! Вы выбрали: {vote}"
54
 
55
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
56
- gr.Markdown("# 🧠 Сравнение языковых моделей")
57
- gr.Markdown("Тестируйте разные модели и оценивайте качество ответов!")
58
-
59
  with gr.Row():
60
- with gr.Column(scale=1):
61
- model_selector = gr.Dropdown(
62
- choices=AVAILABLE_MODELS,
63
- label="Выберите модель для генерации",
64
- value=AVAILABLE_MODELS[0]
65
- )
66
- prompt_input = gr.Textbox(
67
- label="Введите ваш запрос",
68
- placeholder="Напишите здесь ваш вопрос или промпт...",
69
- lines=3
70
- )
71
-
72
- with gr.Row():
73
- clear_btn = gr.Button("🧹 Очистить", variant="secondary")
74
- skip_btn = gr.Button("⏭️ Пропустить", variant="secondary")
75
- random_btn = gr.Button("🎲 Случайная модель", variant="primary")
76
- generate_btn = gr.Button("🚀 Сгенерировать", variant="primary")
77
 
78
- with gr.Column(scale=2):
79
- response_output = gr.Textbox(
80
- label="Сгенерированный ответ",
81
- interactive=False,
82
- lines=6
83
- )
84
-
85
- with gr.Row():
86
- response1_eval = gr.Textbox(
87
- label="Ответ для оценки 1",
88
- interactive=False,
89
- lines=3
90
- )
91
- response2_eval = gr.Textbox(
92
- label="Ответ для оценки 2",
93
- interactive=False,
94
- lines=3
95
- )
96
-
97
- vote_radio = gr.Radio(
98
- choices=["Ответ 1 лучше", "Ответ 2 лучше", "Оба хороши", "Оба плохи"],
99
- label="Какой ответ лучше?",
100
- interactive=True
101
- )
102
-
103
- vote_btn = gr.Button("📊 Оценить ответы", variant="primary")
104
- vote_result = gr.Textbox(
105
- label="Результат оценки",
106
- interactive=False
107
- )
108
 
109
- # Обработчики событий
110
- generate_btn.click(
111
- fn=generate_response,
112
- inputs=[prompt_input, model_selector],
113
- outputs=response_output
114
- )
115
-
116
- clear_btn.click(
117
- fn=clear_all,
118
- outputs=[prompt_input, response_output, response1_eval, response2_eval]
119
- )
120
-
121
- random_btn.click(
122
- fn=random_generate,
123
- inputs=[prompt_input],
124
- outputs=[model_selector, response_output, response1_eval, response2_eval]
125
- )
126
-
127
- skip_btn.click(
128
- lambda: [gr.skip(), gr.skip()],
129
- outputs=[response1_eval, response2_eval]
130
- )
131
-
132
- vote_btn.click(
133
- fn=vote_for_best,
134
- inputs=[response1_eval, response2_eval, vote_radio],
135
- outputs=vote_result
136
- )
137
 
138
- # Инструкция
139
- gr.Markdown("""
140
- ## Как использовать:
141
- 1. Выберите модель из списка или используйте случайную
142
- 2. Введите ваш запрос
143
- 3. Нажмите "Сгенерировать" для получения ответа
144
- 4. Сравните два ответа и оцените какой лучше
145
- 5. Ваши оценки помогут улучшить систему!
146
- """)
147
 
148
- # Для запуска на Hugging Face Spaces
149
- demo.launch(share=True)
 
 
 
 
 
 
 
1
+ # app.py
2
  import gradio as gr
3
+ from g4f.client import Client
 
4
 
5
+ client = Client()
 
 
 
 
 
 
 
6
 
7
+ # --- Обработчик диалога ---
8
+ def respond(message, history):
9
+ # Добавляем системное сообщение только при старте истории
10
+ messages = [{"role": "system", "content": ""}]
11
+
12
+ for human, assistant in history:
13
+ messages.append({"role": "user", "content": human})
14
+ messages.append({"role": "assistant", "content": assistant})
15
+
16
+ messages.append({"role": "user", "content": message})
17
 
 
18
  try:
19
+ response = client.chat.completions.create(
20
+ model="gpt-4",
21
+ messages=messages
22
  )
23
+ bot_message = response.choices[0].message.content
24
  except Exception as e:
25
+ bot_message = f"Ошибка: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # Возвращаем обновлённую историю + новый ответ
28
+ return history + [[message, bot_message]]
 
29
 
30
+ # --- Интерфейс ---
31
+ with gr.Blocks(title="ESP Brain") as demo:
32
+ gr.Markdown("## For api")
 
 
33
 
34
+ chatbot = gr.Chatbot(
35
+ height=600,
36
+ )
 
 
37
 
 
 
 
 
38
  with gr.Row():
39
+ txt = gr.Textbox(
40
+ placeholder="Напиши сообщение...",
41
+ show_label=False,
42
+ scale=8
43
+ )
44
+ submit_btn = gr.Button("Отправить", scale=2)
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ with gr.Row():
47
+ retry_btn = gr.Button("🔄 Повторить")
48
+ undo_btn = gr.Button("↩️ Отменить")
49
+ clear_btn = gr.Button("🗑️ Очистить")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # Логика
52
+ txt.submit(fn=respond, inputs=[txt, chatbot], outputs=chatbot)
53
+ submit_btn.click(fn=respond, inputs=[txt, chatbot], outputs=chatbot)
54
+
55
+ def retry_last(history):
56
+ if history:
57
+ last_user_msg = history[-1][0]
58
+ return history[:-1] + [[last_user_msg, None]] # очищаем ответ
59
+ return history
60
+
61
+ retry_btn.click(fn=retry_last, inputs=chatbot, outputs=chatbot, queue=False)
62
+
63
+ def undo_last(history):
64
+ return history[:-1]
65
+
66
+ undo_btn.click(fn=undo_last, inputs=chatbot, outputs=chatbot, queue=False)
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ clear_btn.click(lambda: [], outputs=chatbot, queue=False)
 
 
 
 
 
 
 
 
69
 
70
+ # --- Запуск ---
71
+ if __name__ == "__main__":
72
+ demo.queue()
73
+ demo.launch(
74
+ share=True,
75
+ ssr_mode=False,
76
+ debug=True
77
+ )