fruitpicker01
commited on
Commit
•
34fa51c
1
Parent(s):
e4f28f3
Update app.py
Browse files
app.py
CHANGED
@@ -69,7 +69,7 @@ for sheet_name, df in data.items():
|
|
69 |
if sheet_name == "Пол Поколение Психотип":
|
70 |
features[sheet_name] = df.set_index(['Пол', 'Поколение', 'Психотип'])['Инструкция'].to_dict()
|
71 |
elif sheet_name == "Подход":
|
72 |
-
features[sheet_name] = df
|
73 |
else:
|
74 |
features[sheet_name] = df.set_index(df.columns[0]).to_dict()[df.columns[1]]
|
75 |
except Exception as e:
|
@@ -512,7 +512,7 @@ def notify_failed_checks(checks):
|
|
512 |
# return last_message
|
513 |
|
514 |
|
515 |
-
def generate_message_mistral_with_retry(prompt,
|
516 |
global approach_stats
|
517 |
last_message = None
|
518 |
for attempt in range(20):
|
@@ -521,7 +521,7 @@ def generate_message_mistral_with_retry(prompt, current_prefix, description, key
|
|
521 |
if message is None:
|
522 |
print("Не удалось получить сообщение от Mistral, повторная попытка...")
|
523 |
time.sleep(1)
|
524 |
-
continue
|
525 |
message = replace_k_with_thousands(message)
|
526 |
message = correct_dash_usage(message)
|
527 |
message_length = len(message)
|
@@ -531,10 +531,13 @@ def generate_message_mistral_with_retry(prompt, current_prefix, description, key
|
|
531 |
continue
|
532 |
checks = perform_checks(message, description, key_message)
|
533 |
last_message = message
|
534 |
-
|
|
|
|
|
|
|
535 |
for check_name, passed in checks.items():
|
536 |
if passed is False:
|
537 |
-
approach_stats[
|
538 |
break
|
539 |
notify_failed_checks(checks)
|
540 |
if all(checks.values()):
|
@@ -660,7 +663,7 @@ def generate_all_messages(desc, benefits, key_message, gender, generation, psych
|
|
660 |
standard_prompt = generate_standard_prompt(desc, benefits, key_message)
|
661 |
yield standard_prompt, None, None, None
|
662 |
|
663 |
-
#
|
664 |
approach_mapping = {
|
665 |
"Указание на пользу": (
|
666 |
"Начни сообщение с указания на пользу продукта. Используй глагол в побудительном наклонении.",
|
@@ -676,26 +679,48 @@ def generate_all_messages(desc, benefits, key_message, gender, generation, psych
|
|
676 |
)
|
677 |
}
|
678 |
|
679 |
-
#
|
680 |
-
|
681 |
-
|
|
|
|
|
|
|
682 |
|
683 |
-
|
684 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
685 |
return
|
686 |
|
687 |
-
|
688 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
689 |
gr.Warning("Подход не найден для выбранных параметров.")
|
690 |
return
|
691 |
|
692 |
-
|
|
|
|
|
|
|
|
|
693 |
|
694 |
-
#
|
695 |
non_personalized_messages = ''
|
696 |
personalized_messages = ''
|
697 |
flag = 1
|
698 |
-
for approach_name in
|
699 |
if approach_name not in approach_mapping:
|
700 |
gr.Warning(f"Неизвестный подход: {approach_name}")
|
701 |
continue
|
@@ -709,7 +734,7 @@ def generate_all_messages(desc, benefits, key_message, gender, generation, psych
|
|
709 |
yield standard_prompt, display_personalization_prompt, None, None
|
710 |
flag += 1
|
711 |
prompt = add_prefix_suffix(standard_prompt, current_prefix, current_suffix)
|
712 |
-
non_personalized_message = generate_message_mistral_with_retry(prompt,
|
713 |
non_personalized_length = len(non_personalized_message)
|
714 |
non_personalized_display = f"{non_personalized_message}\n------\nКоличество знаков: {non_personalized_length}"
|
715 |
if non_personalized_messages:
|
@@ -721,7 +746,7 @@ def generate_all_messages(desc, benefits, key_message, gender, generation, psych
|
|
721 |
non_personalized_messages, personalized_messages
|
722 |
)
|
723 |
full_personalized_prompt = f"{personalization_prompt}\n\nТекст для адаптации: {non_personalized_message}"
|
724 |
-
personalized_message = generate_message_mistral_with_retry(full_personalized_prompt,
|
725 |
personalized_length = len(personalized_message)
|
726 |
personalized_display = f"{personalized_message}\n------\nКоличество знаков: {personalized_length}"
|
727 |
if personalized_messages:
|
|
|
69 |
if sheet_name == "Пол Поколение Психотип":
|
70 |
features[sheet_name] = df.set_index(['Пол', 'Поколение', 'Психотип'])['Инструкция'].to_dict()
|
71 |
elif sheet_name == "Подход":
|
72 |
+
features[sheet_name] = df # Сохраняем как DataFrame
|
73 |
else:
|
74 |
features[sheet_name] = df.set_index(df.columns[0]).to_dict()[df.columns[1]]
|
75 |
except Exception as e:
|
|
|
512 |
# return last_message
|
513 |
|
514 |
|
515 |
+
def generate_message_mistral_with_retry(prompt, approach_name, description, key_message):
|
516 |
global approach_stats
|
517 |
last_message = None
|
518 |
for attempt in range(20):
|
|
|
521 |
if message is None:
|
522 |
print("Не удалось получить сообщение от Mistral, повторная попытка...")
|
523 |
time.sleep(1)
|
524 |
+
continue
|
525 |
message = replace_k_with_thousands(message)
|
526 |
message = correct_dash_usage(message)
|
527 |
message_length = len(message)
|
|
|
531 |
continue
|
532 |
checks = perform_checks(message, description, key_message)
|
533 |
last_message = message
|
534 |
+
# Инициализируем статистику для подхода, если ее нет
|
535 |
+
if approach_name not in approach_stats:
|
536 |
+
approach_stats[approach_name] = {"failed_checks": defaultdict(int), "total_attempts": 0}
|
537 |
+
approach_stats[approach_name]["total_attempts"] += 1
|
538 |
for check_name, passed in checks.items():
|
539 |
if passed is False:
|
540 |
+
approach_stats[approach_name]["failed_checks"][check_name] += 1
|
541 |
break
|
542 |
notify_failed_checks(checks)
|
543 |
if all(checks.values()):
|
|
|
663 |
standard_prompt = generate_standard_prompt(desc, benefits, key_message)
|
664 |
yield standard_prompt, None, None, None
|
665 |
|
666 |
+
# Сопоставление названий подходов с префиксами и суффиксами
|
667 |
approach_mapping = {
|
668 |
"Указание на пользу": (
|
669 |
"Начни сообщение с указания на пользу продукта. Используй глагол в побудительном наклонении.",
|
|
|
679 |
)
|
680 |
}
|
681 |
|
682 |
+
# Получаем DataFrame подходов
|
683 |
+
approaches_df = features.get("Подход", None)
|
684 |
+
|
685 |
+
if approaches_df is None:
|
686 |
+
gr.Warning("Таблица 'Подход' не найдена.")
|
687 |
+
return
|
688 |
|
689 |
+
# Создаем фильтры на основе выбранных параметров
|
690 |
+
filters = []
|
691 |
+
if gender:
|
692 |
+
filters.append(approaches_df['Пол'] == gender)
|
693 |
+
if generation:
|
694 |
+
filters.append(approaches_df['Поколение'] == generation)
|
695 |
+
if psychotype:
|
696 |
+
filters.append(approaches_df['Психотип'] == psychotype)
|
697 |
+
|
698 |
+
if not filters:
|
699 |
+
gr.Warning("Необходимо выбрать хотя бы один параметр для определения подхода.")
|
700 |
return
|
701 |
|
702 |
+
# Применяем комбинированный фильтр
|
703 |
+
combined_filter = filters[0]
|
704 |
+
for f in filters[1:]:
|
705 |
+
combined_filter &= f
|
706 |
+
|
707 |
+
matching_rows = approaches_df[combined_filter]
|
708 |
+
|
709 |
+
if matching_rows.empty:
|
710 |
gr.Warning("Подход не найден для выбранных параметров.")
|
711 |
return
|
712 |
|
713 |
+
# Извлекаем уникальные подходы из отфильтрованных строк
|
714 |
+
approach_set = set()
|
715 |
+
for approaches in matching_rows['Подход']:
|
716 |
+
approach_names = [a.strip() for a in approaches.split(',')]
|
717 |
+
approach_set.update(approach_names)
|
718 |
|
719 |
+
# Генерируем сообщения для каждого подхода
|
720 |
non_personalized_messages = ''
|
721 |
personalized_messages = ''
|
722 |
flag = 1
|
723 |
+
for approach_name in approach_set:
|
724 |
if approach_name not in approach_mapping:
|
725 |
gr.Warning(f"Неизвестный подход: {approach_name}")
|
726 |
continue
|
|
|
734 |
yield standard_prompt, display_personalization_prompt, None, None
|
735 |
flag += 1
|
736 |
prompt = add_prefix_suffix(standard_prompt, current_prefix, current_suffix)
|
737 |
+
non_personalized_message = generate_message_mistral_with_retry(prompt, approach_name, desc, key_message)
|
738 |
non_personalized_length = len(non_personalized_message)
|
739 |
non_personalized_display = f"{non_personalized_message}\n------\nКоличество знаков: {non_personalized_length}"
|
740 |
if non_personalized_messages:
|
|
|
746 |
non_personalized_messages, personalized_messages
|
747 |
)
|
748 |
full_personalized_prompt = f"{personalization_prompt}\n\nТекст для адаптации: {non_personalized_message}"
|
749 |
+
personalized_message = generate_message_mistral_with_retry(full_personalized_prompt, approach_name, desc, key_message)
|
750 |
personalized_length = len(personalized_message)
|
751 |
personalized_display = f"{personalized_message}\n------\nКоличество знаков: {personalized_length}"
|
752 |
if personalized_messages:
|