Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -76,7 +76,7 @@ def generate_standard_prompt(description, advantages, *selected_values):
|
|
76 |
return prompt
|
77 |
|
78 |
# Функции для генерации сообщений
|
79 |
-
def generate_message_gpt4o(prompt):
|
80 |
try:
|
81 |
headers = {
|
82 |
"Content-Type": "application/json",
|
@@ -85,11 +85,12 @@ def generate_message_gpt4o(prompt):
|
|
85 |
data = {
|
86 |
"model": "chatgpt-4o-latest",
|
87 |
"messages": [{"role": "system", "content": prompt}],
|
88 |
-
"max_tokens": 101
|
|
|
89 |
}
|
90 |
response = requests.post("https://api.openai.com/v1/chat/completions", json=data, headers=headers)
|
91 |
response_data = response.json()
|
92 |
-
return response_data["choices"][0]["message"]["content"].strip()
|
93 |
except Exception as e:
|
94 |
return f"Ошибка при обращении к ChatGPT-4o-Latest: {e}"
|
95 |
|
@@ -102,29 +103,29 @@ def clean_message(message):
|
|
102 |
return message
|
103 |
|
104 |
# Обновленные функции генерации сообщений с учетом обрезки незаконченных предложений
|
105 |
-
def generate_message_gigachat_pro(prompt):
|
106 |
try:
|
107 |
messages = [SystemMessage(content=prompt)]
|
|
|
108 |
res = chat_pro(messages)
|
109 |
-
|
110 |
-
return cleaned_message
|
111 |
except Exception as e:
|
112 |
return f"Ошибка при обращении к GigaChat-Pro: {e}"
|
113 |
|
114 |
-
def generate_message_gigachat_lite(prompt):
|
115 |
try:
|
116 |
-
time.sleep(2)
|
117 |
messages = [SystemMessage(content=prompt)]
|
|
|
118 |
res = chat_lite(messages)
|
119 |
cleaned_message = clean_message(res.content.strip())
|
120 |
return cleaned_message
|
121 |
except Exception as e:
|
122 |
return f"Ошибка при обращении к GigaChat-Lite: {e}"
|
123 |
|
124 |
-
def generate_message_gigachat_plus(prompt):
|
125 |
try:
|
126 |
-
time.sleep(2)
|
127 |
messages = [SystemMessage(content=prompt)]
|
|
|
128 |
res = chat_plus(messages)
|
129 |
cleaned_message = clean_message(res.content.strip())
|
130 |
return cleaned_message
|
@@ -231,16 +232,16 @@ def perform_personalization_gigachat(standard_message, personalization_prompt, m
|
|
231 |
return clean_message(result)
|
232 |
|
233 |
|
234 |
-
def perform_personalization_with_retry(standard_message, personalization_prompt):
|
235 |
for _ in range(10): # Максимум 10 попыток
|
236 |
-
message = perform_personalization(standard_message, personalization_prompt)
|
237 |
if len(message) <= 250:
|
238 |
return message
|
239 |
return message # Возвращаем последнее сгенерированное сообщение, если все попытки не удались
|
240 |
|
241 |
-
def perform_personalization_gigachat_with_retry(standard_message, personalization_prompt, model):
|
242 |
for _ in range(10):
|
243 |
-
message = perform_personalization_gigachat(standard_message, personalization_prompt, model)
|
244 |
if len(message) <= 250:
|
245 |
return message
|
246 |
return message
|
@@ -345,7 +346,7 @@ def check_errors_with_yield(*personalized_messages):
|
|
345 |
yield error_check_prompt, error_message_gpt4o, error_message_gigachat_pro, error_message_gigachat_lite, error_message_gigachat_plus, "Все результаты проверки сгенерированы"
|
346 |
|
347 |
|
348 |
-
def save_to_github(personalized_message, model_name, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form):
|
349 |
# Собираем все данные в один словарь
|
350 |
data_to_save = {
|
351 |
"Модель": model_name,
|
@@ -361,7 +362,8 @@ def save_to_github(personalized_message, model_name, comment, corrected_message,
|
|
361 |
"Психотип": psychotype,
|
362 |
"Стадия бизнеса": business_stage,
|
363 |
"Отрасль": industry,
|
364 |
-
"ОПФ": legal_form
|
|
|
365 |
}
|
366 |
|
367 |
# Преобразуем контент в JSON-строку и кодируем в base64
|
@@ -388,6 +390,13 @@ def save_to_github(personalized_message, model_name, comment, corrected_message,
|
|
388 |
with gr.Blocks() as demo:
|
389 |
gr.Markdown("# Генерация SMS-сообщений по заданным признакам")
|
390 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
391 |
with gr.Row():
|
392 |
with gr.Column(scale=1):
|
393 |
description_input = gr.Textbox(
|
@@ -474,8 +483,8 @@ with gr.Blocks() as demo:
|
|
474 |
|
475 |
# Привязка кнопок к функциям сохранения
|
476 |
save_gpt4o_btn.click(
|
477 |
-
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form:
|
478 |
-
save_to_github(personalized_message, "GPT-4o", comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form),
|
479 |
inputs=[
|
480 |
personalized_output_text_gpt4o,
|
481 |
comment_gpt4o,
|
@@ -489,14 +498,17 @@ with gr.Blocks() as demo:
|
|
489 |
selections[2], # Психотип
|
490 |
selections[3], # Стадия бизнеса
|
491 |
selections[4], # Отрасль
|
492 |
-
selections[5]
|
|
|
493 |
],
|
494 |
outputs=None
|
495 |
)
|
496 |
|
|
|
|
|
497 |
save_gigachat_pro_btn.click(
|
498 |
-
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form:
|
499 |
-
save_to_github(personalized_message, "GigaChat-Pro", comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form),
|
500 |
inputs=[
|
501 |
personalized_output_text_gigachat_pro,
|
502 |
comment_gigachat_pro,
|
@@ -510,14 +522,16 @@ with gr.Blocks() as demo:
|
|
510 |
selections[2], # Психотип
|
511 |
selections[3], # Стадия бизнеса
|
512 |
selections[4], # Отрасль
|
513 |
-
selections[5]
|
|
|
514 |
],
|
515 |
outputs=None
|
516 |
)
|
517 |
-
|
|
|
518 |
save_gigachat_lite_btn.click(
|
519 |
-
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form:
|
520 |
-
save_to_github(personalized_message, "GigaChat-Lite", comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form),
|
521 |
inputs=[
|
522 |
personalized_output_text_gigachat_lite,
|
523 |
comment_gigachat_lite,
|
@@ -531,14 +545,16 @@ with gr.Blocks() as demo:
|
|
531 |
selections[2], # Психотип
|
532 |
selections[3], # Стадия бизнеса
|
533 |
selections[4], # Отрасль
|
534 |
-
selections[5]
|
|
|
535 |
],
|
536 |
outputs=None
|
537 |
)
|
538 |
-
|
|
|
539 |
save_gigachat_plus_btn.click(
|
540 |
-
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form:
|
541 |
-
save_to_github(personalized_message, "GigaChat-
|
542 |
inputs=[
|
543 |
personalized_output_text_gigachat_plus,
|
544 |
comment_gigachat_plus,
|
@@ -552,11 +568,13 @@ with gr.Blocks() as demo:
|
|
552 |
selections[2], # Психотип
|
553 |
selections[3], # Стадия бизнеса
|
554 |
selections[4], # Отрасль
|
555 |
-
selections[5]
|
|
|
556 |
],
|
557 |
outputs=None
|
558 |
)
|
559 |
|
|
|
560 |
# Использование сохраненных переменных в следующем блоке
|
561 |
with gr.Row():
|
562 |
check_errors_btn = gr.Button("3. Проверить текст (нажимать только после кнопки 2) - экспериментальная фича, качество пока крайне низкое", elem_id="check_errors_button")
|
|
|
76 |
return prompt
|
77 |
|
78 |
# Функции для генерации сообщений
|
79 |
+
def generate_message_gpt4o(prompt, temperature):
|
80 |
try:
|
81 |
headers = {
|
82 |
"Content-Type": "application/json",
|
|
|
85 |
data = {
|
86 |
"model": "chatgpt-4o-latest",
|
87 |
"messages": [{"role": "system", "content": prompt}],
|
88 |
+
"max_tokens": 101,
|
89 |
+
"temperature": temperature
|
90 |
}
|
91 |
response = requests.post("https://api.openai.com/v1/chat/completions", json=data, headers=headers)
|
92 |
response_data = response.json()
|
93 |
+
return clean_message(response_data["choices"][0]["message"]["content"].strip())
|
94 |
except Exception as e:
|
95 |
return f"Ошибка при обращении к ChatGPT-4o-Latest: {e}"
|
96 |
|
|
|
103 |
return message
|
104 |
|
105 |
# Обновленные функции генерации сообщений с учетом обрезки незаконченных предложений
|
106 |
+
def generate_message_gigachat_pro(prompt, temperature):
|
107 |
try:
|
108 |
messages = [SystemMessage(content=prompt)]
|
109 |
+
chat_pro = authenticate_gigachat('GigaChat-Pro', 68, temperature)
|
110 |
res = chat_pro(messages)
|
111 |
+
return clean_message(res.content.strip())
|
|
|
112 |
except Exception as e:
|
113 |
return f"Ошибка при обращении к GigaChat-Pro: {e}"
|
114 |
|
115 |
+
def generate_message_gigachat_lite(prompt, temperature):
|
116 |
try:
|
|
|
117 |
messages = [SystemMessage(content=prompt)]
|
118 |
+
chat_lite = authenticate_gigachat('GigaChat', 68, temperature)
|
119 |
res = chat_lite(messages)
|
120 |
cleaned_message = clean_message(res.content.strip())
|
121 |
return cleaned_message
|
122 |
except Exception as e:
|
123 |
return f"Ошибка при обращении к GigaChat-Lite: {e}"
|
124 |
|
125 |
+
def generate_message_gigachat_plus(prompt, temperature):
|
126 |
try:
|
|
|
127 |
messages = [SystemMessage(content=prompt)]
|
128 |
+
chat_plus = authenticate_gigachat('GigaChat-Plus', 68, temperature)
|
129 |
res = chat_plus(messages)
|
130 |
cleaned_message = clean_message(res.content.strip())
|
131 |
return cleaned_message
|
|
|
232 |
return clean_message(result)
|
233 |
|
234 |
|
235 |
+
def perform_personalization_with_retry(standard_message, personalization_prompt, temperature):
|
236 |
for _ in range(10): # Максимум 10 попыток
|
237 |
+
message = perform_personalization(standard_message, personalization_prompt, temperature)
|
238 |
if len(message) <= 250:
|
239 |
return message
|
240 |
return message # Возвращаем последнее сгенерированное сообщение, если все попытки не удались
|
241 |
|
242 |
+
def perform_personalization_gigachat_with_retry(standard_message, personalization_prompt, model, temperature):
|
243 |
for _ in range(10):
|
244 |
+
message = perform_personalization_gigachat(standard_message, personalization_prompt, model, temperature)
|
245 |
if len(message) <= 250:
|
246 |
return message
|
247 |
return message
|
|
|
346 |
yield error_check_prompt, error_message_gpt4o, error_message_gigachat_pro, error_message_gigachat_lite, error_message_gigachat_plus, "Все результаты проверки сгенерированы"
|
347 |
|
348 |
|
349 |
+
def save_to_github(personalized_message, model_name, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature):
|
350 |
# Собираем все данные в один словарь
|
351 |
data_to_save = {
|
352 |
"Модель": model_name,
|
|
|
362 |
"Психотип": psychotype,
|
363 |
"Стадия бизнеса": business_stage,
|
364 |
"Отрасль": industry,
|
365 |
+
"ОПФ": legal_form,
|
366 |
+
"Температура": temperature # Добавляем температуру в сохраненные данные
|
367 |
}
|
368 |
|
369 |
# Преобразуем контент в JSON-строку и кодируем в base64
|
|
|
390 |
with gr.Blocks() as demo:
|
391 |
gr.Markdown("# Генерация SMS-сообщений по заданным признакам")
|
392 |
|
393 |
+
with gr.Column(scale=1):
|
394 |
+
# Добавляем слайдеры для установки параметра температуры для каждой модели
|
395 |
+
gpt4o_temperature = gr.Slider(label="GPT-4o: temperature", minimum=0, maximum=2, step=0.01, value=1)
|
396 |
+
gigachat_pro_temperature = gr.Slider(label="GigaChat-Pro: temperature", minimum=0, maximum=1.7, step=0.01, value=0.87)
|
397 |
+
gigachat_lite_temperature = gr.Slider(label="GigaChat-Lite: temperature", minimum=0, maximum=1.7, step=0.01, value=0.87)
|
398 |
+
gigachat_plus_temperature = gr.Slider(label="GigaChat-Plus: temperature", minimum=0, maximum=1.7, step=0.01, value=0.87)
|
399 |
+
|
400 |
with gr.Row():
|
401 |
with gr.Column(scale=1):
|
402 |
description_input = gr.Textbox(
|
|
|
483 |
|
484 |
# Привязка кнопок к функциям сохранения
|
485 |
save_gpt4o_btn.click(
|
486 |
+
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature:
|
487 |
+
save_to_github(personalized_message, "GPT-4o", comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature),
|
488 |
inputs=[
|
489 |
personalized_output_text_gpt4o,
|
490 |
comment_gpt4o,
|
|
|
498 |
selections[2], # Психотип
|
499 |
selections[3], # Стадия бизнеса
|
500 |
selections[4], # Отрасль
|
501 |
+
selections[5], # ОПФ
|
502 |
+
gpt4o_temperature # Температура
|
503 |
],
|
504 |
outputs=None
|
505 |
)
|
506 |
|
507 |
+
|
508 |
+
# Привязка кнопок к функциям сохранения для GigaChat-Pro
|
509 |
save_gigachat_pro_btn.click(
|
510 |
+
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature:
|
511 |
+
save_to_github(personalized_message, "GigaChat-Pro", comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature),
|
512 |
inputs=[
|
513 |
personalized_output_text_gigachat_pro,
|
514 |
comment_gigachat_pro,
|
|
|
522 |
selections[2], # Психотип
|
523 |
selections[3], # Стадия бизнеса
|
524 |
selections[4], # Отрасль
|
525 |
+
selections[5], # ОПФ
|
526 |
+
gigachat_pro_temperature # Температура
|
527 |
],
|
528 |
outputs=None
|
529 |
)
|
530 |
+
|
531 |
+
# Привязка кнопок к функциям сохранения для GigaChat-Lite
|
532 |
save_gigachat_lite_btn.click(
|
533 |
+
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature:
|
534 |
+
save_to_github(personalized_message, "GigaChat-Lite", comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature),
|
535 |
inputs=[
|
536 |
personalized_output_text_gigachat_lite,
|
537 |
comment_gigachat_lite,
|
|
|
545 |
selections[2], # Психотип
|
546 |
selections[3], # Стадия бизнеса
|
547 |
selections[4], # Отрасль
|
548 |
+
selections[5], # ОПФ
|
549 |
+
gigachat_lite_temperature # Температура
|
550 |
],
|
551 |
outputs=None
|
552 |
)
|
553 |
+
|
554 |
+
# Привязка кнопок к функциям сохранения для GigaChat-Plus
|
555 |
save_gigachat_plus_btn.click(
|
556 |
+
fn=lambda personalized_message, comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature:
|
557 |
+
save_to_github(personalized_message, "GigaChat-Plus", comment, corrected_message, description, advantages, non_personalized_prompt, non_personalized_message, gender, generation, psychotype, business_stage, industry, legal_form, temperature),
|
558 |
inputs=[
|
559 |
personalized_output_text_gigachat_plus,
|
560 |
comment_gigachat_plus,
|
|
|
568 |
selections[2], # Психотип
|
569 |
selections[3], # Стадия бизнеса
|
570 |
selections[4], # Отрасль
|
571 |
+
selections[5], # ОПФ
|
572 |
+
gigachat_plus_temperature # Температура
|
573 |
],
|
574 |
outputs=None
|
575 |
)
|
576 |
|
577 |
+
|
578 |
# Использование сохраненных переменных в следующем блоке
|
579 |
with gr.Row():
|
580 |
check_errors_btn = gr.Button("3. Проверить текст (нажимать только после кнопки 2) - экспериментальная фича, качество пока крайне низкое", elem_id="check_errors_button")
|